Home/Blog/Programming/The Python FAQ: Quick answers to common Python questions
Home/Blog/Programming/The Python FAQ: Quick answers to common Python questions

The Python FAQ: Quick answers to common Python questions

Aaron Xie
Aug 31, 2020
11 min read

Become a Software Engineer in Months, Not Years

From your first line of code, to your first day on the job — Educative has you covered. Join 2M+ developers learning in-demand programming skills.

Each year, Python continues to grow in popularity. Simultaneously, areas like web development, data science, and machine learning continue to rise in need, with Python as a common programming language within these domains.

With more demand in Python, beginners and advanced programmers alike need more resources to master this in-demand language. So, we’ve put together a list of the most common questions developer like you have about Python. Everything from for loops to documentation to GUIs.

Today, we’ll be covering the following:


Master Python with hands-on projects.

By the time you’re done with these courses, you’ll be ready to apply for any high-paying Python job.

Python for Programmers: Learning Track


Basics and History#

What is Python?

Python is an object-oriented, interpreted, high-level programming language. Beyond object-oriented programming, Python offers paradigms such as procedural and functional programming. It uses modules, exceptions, dynamic typing, data types, and classes.

A language that is both powerful and clear, it incorporates interfaces to many system class and libraries. Python can also be used as an extension language for applications that require a programmable interface.


What is the history of Python?#

Python was created in the 1980s by Guido Van Rossum at the Centrum Wiskunde & Informatica in the Netherlands. Python was originally created to be a successor to the ABC language, which would be capable of exception handling and interfacing with the Amoeba operating system.

He was the sole person responsible for the Python project until July 12th, 2018. In January 2019, core developers elected Brett Cannon, Nick Coghlan, Barry Warsaw, Carol Willing, and Van Rossum to lead the project.

Python 2.0 was released on October 16th, 2000 with new features such as cycle-detecting garbage collector and support for Unicode. Python 3.0 was released on December 3rd, 2008.


What are the key features of Python?#

  • Easy to learn and use: Because Python’s syntax is straightforward and generally similar to the English language, Python is considered to be an easy language to learn. Python takes award semicolons and curly-bracket that defines the code block. As a high-level implementation, it is the recommended programming language for beginners.

  • Expressive: Python is able to perform complex tasks using just a few lines of code. For example, a hello world is simply one line: print("Hello World). While Python only takes one line to execute, a language like Java or C takes far more lines.

  • Interpreted Language: Python is an interpreted language, meaning that a Python program is executed line by line. An advantage to an interpreted language is that debugging is easy and portable.

  • Cross-platform language: Python can run equally on Widows, Linux, UNIX, macOS, etc, making the language portable. This allows engineers to create software on competing platforms with one program.

  • Free and open source: Python is free and available to the general public, in which you can download it at python.org. It has a massive worldwide community dedicated towards creating more python packages and functionality, with a dedicated team.

  • Object-oriented language: Python is an object-oriented programming language, using classes and objects. It also allows functionality like inheritance polymorphism, and encapsulation. This makes it easier for programmers to write reusable code.


Should I use Python 2 or Python 3?#

While there are many versions of Python, the main comparison is Python 2 vs. Python 3. Python 3 was initially released in December 2008, designed to rectify some fundamental design flaws that Python 2 introduced.

The guiding principle of Python 3 was: “reduce feature duplication by removing old ways of doing things.” Python 2 was created in a way that supported many ways to performing the same task.

Python 2:

  • Still entrenched in the software of many companies
  • Many of the older libraries for Python 2 are not forwards-compatible
  • Strings are stored as ASCII by default

Python 3:

  • Will take over Python 2 by 2020
  • More and more libraries are being created strictly for Python 2
  • Text strings are Unicode by default

Now, it’s clear that Python 3 is the popular choice as Python 2 is no long a supported language by the Python Software Foundation. With this change, the community as a whole has largely shifted towards Python 3, meaning there is no reason to learn Python 2.


How do I install Python?#

Python requires about 25 MB of disk space, so make sure that you have enough space. After installing, Python requires an additional 90 MB of space.

  1. You can download Python here.

  2. Click “Download Python 3.8.5”

  3. Scroll down and click “[your operating system] 64-bit installer.”

  4. After clicking the button, follower the directions of the installer, and you’re done!


What are the best Python IDEs?#

An IDE (Integrated Development Environment) is a program dedicated to software development. In this case, we are looking for an IDE dedicated towards python development. Some features of an IDE include:

  • An editor designed to handle code
  • Build, execution and debugging tools
  • Some form of source control

A good IDE for a Python environment offers certain important features: save and reload your code files, run code from within the environment, debugging support, syntax highlighting, and automatic code formatting.

General IDEs with Python support:

  • Eclipse + PyDev
  • Sublime Text
  • Atom

Python-specific editors and IDEs:

  • PyCharm
  • Spyder
  • Thonny

I recommend PyCharm, offering some amazing features like type checking, code inspections, automated refactoring, easy navigation in bigger projects, integration with debuggers and version control. The list goes on.


What are the best resources for learning Python?#

The best way to learn Python is with hands-on practice. Python is intuitive, so focusing on coding challenges will improve your skills. You can get ideas for these on GitHub, the official Python website, or online courses.

Blogs and forums are great resources, where you can see other people’s ideas, ask questions, and get step-by-step guides for free. Here are some suggestions:

In terms of courses, I recommend text-based instruction over video. You’ll spend way less time scrubbing and actually practicing what you want to learn. Here are some course suggestions to get started:


Programming Questions#

What are the basic concepts of Python?


Semicolons

Let’s first start with Python not using semicolons to finish lines, unlike most programming language. A new line is enough for the interpreter to detect a new command.

In the example using the print() method, we can see an example.

print('First command')
print('Second command')

Indentation#

Most languages will use curly brackets to define the scope of a code block, but Python’s interpreter will simply determine that through an indentation. This means that you have to be especially careful with white spaces in your code, which can break your application. Below is an example.

def my_function():
print('Hello world')

Comments#

To comment something in your code, you simply need to use a hash mark #. Below, is an example.

# this is a comment that does not influence the program flow
def my_function():
print('Hello world')

Variables#

With python, you can store and manipulate data in your program. A variable stores a data such as a number, a username, a password, etc. To create (declare) a variable you can use the = symbol.

name='Bob'
age=32

Notice that in Python, you don’t need to tell the program whether the variable is a string or integer, for instance. That’s because Python has dynamic typing, in which the interpreter automatically detects the data type.

Types#

To store data in Python, we have already established that you need to use variables. Still, with every variable, there will be a data type. Examples of data types are strings, integers, booleans, and lists.

A boolean type can only hold the value of True or False.

my_bool = True
print(type(my_bool))
my_bool = bool(1024)
print(type(my_bool))

An integer is one of three numeric types, including float and complex. An integer is a positive or negative whole number.

my_int = 32
print(type(my_int))
my_int = int(32)
print(type(my_int))

A string is one of the most common data type.

my_city = "New York"
print(type(my_city))
#Single quotes have exactly
#the same use as double quotes
my_city = 'New York'
print(type(my_city))
#Setting the variable type explicitly
my_city = str("New York")
print(type(my_city))

Operators#

Operators are symbols that can be used in your values and variables to perform comparison and mathematical operations.

Arithmetic operators:

  • +: addition
  • -: subtraction
  • *: multiplication
  • /: division
  • **: exponentiation
  • %: modulus, gives you the remainder of a division

Comparison operators:

  • ==: equal
  • !=: not equal
  • >: greater than
  • <: less than
  • >=: greater than or equal to
  • <=: less than or equal to

What are the rules for local and global variables?#

In Python, variables referenced within a function are implicitly global. If a variable is assigned a value within the function’s body, it’s local unless you explicitly declare it as global.


What is the best practice for using import in a module?#

In general, don’t use from modulename import *. This will clutter the importer’s namespace, which makes it much harder for linters to detect undefined names.

Import modules at the top of the file, which makes it clear what modules your code requires. Use one import per line.

Generally, it’s good practice to import modules in the following order:

  1. standard library modules
  2. third-party library modules
  3. locally-developed modules

You should only move your imports into a local scope if you need to solve a problem such as avoiding a circular import or trying to reduce the initialization time of a module.


What is a class in Python?#

Essentially everything in Python is an object, which has properties and methods. A class is an object constructor that acts as blueprint for creating objects.

Here, we create a class named MyClass with the property X. Then, we create a p1 object and print the value of X.

class MyClass:
x = 5
p1 = MyClass()
print(p1.x)

When you create a class, you create a new type of object, which allows for new instances of that type. Each class will have its unique attributes attached to it. Compared to other programming languages, Python’s class incorporation uses minimum syntax and semantics.


How do I use strings to call functions or methods?#

There are various techniques to achieve this, but the best way is to use a dictionary that maps strings to functions. With this approach, strings do not need to match the names of the functions. It’s also the primary technique that is used to emulate a case construct:

def a():
pass
def b():
pass
dispatch = {'go': a, 'stop': b} # Note lack of parens for funcs
dispatch[get_input()]() # Note trailing parens to call function

How to delete a file in Python#

  1. Open your Python File window.
  2. Type the follow coding
import os
os.remove("ChangedFile.csv")
print("File Removed!")

This task looks as simple as it is. All you do is is call os.remove() with the filename and path. Python defaults to the current directory.

  1. Run the application and you should see the File Removed! message.

How do I generate random numbers in Python?#

The generate a random number in Python, you can use the randint() function.

# Program to generate a random number between 0 and 9
# importing the random module
import random
print(random.randint(0,9))

Can I read or write binary data in Python?#

For complex and non-regular data formats, you should use the struct module. This allows you to take a string containing binary data and convert it to a Python object, and vice versa.

In the example below, the code reads two 2-byte integers and one 4-byte integer in big-endian format from a file:

f = open(filename, "rb") # Open in binary mode for portability
s = f.read(8)
x, y, z = struct.unpack(">hhl", s)

What GUI toolkits exist for Python?#

  • Tkinter: Standard builds of Python include tkinter, which is the easiest to install and use. You can learn more here.

  • Kivy: Kivy is the cross-platform GUI library for desktop operating systems and mobile devices, which is written in Python and Cithon. It is a free and open source software under the MIT license.

  • Gtk+: The GObject introspection bindings for Python allow you to write GTK+ 3 applications.

  • wxWidgets: wxWidgets is a free and portable GUI written in C++. wxPython is the Python binding for wxwidgets, offering an umber of features via pure Python extensions that are no available in other bindings.

Where to go next#

Now, you should have a good idea of the Python programming language, as well as an idea of what you need to do next. When it comes down to learning a programming language, it’s all about practice. It’s going to require hours upon hours for you to nail down the important concepts.

To continue your Python journey, check out Educative’s learning path Ace the Python Coding Interview. By the time you’re done with these seven modules, you will have thoroughly mastered Python and be ready to get a job as a Python dev or work on your own projects.

Happy learning!


Continue learning Python#


  

Free Resources