5 Common Problems Faced by Python Beginners

Share this article

5 Common Problems Faced by Python Beginners

Key Takeaways

  • Reading from the terminal in Python can be facilitated using the raw_input function, which takes user input through the terminal itself. However, the input is always a string and may need to be converted to be used in a different form.
  • Python allows for a different approach to array traversal than languages like C++ or Java, enabling direct traversal of each element without using indices. If indices are required, Python’s enumerate function can be used to create pairs of items in an array and their indices.
  • Python’s interpreted nature means that any encountered error will stop further execution of the code. To handle known exceptions, Python allows for the use of a try-except block, which can catch and process individual errors without interrupting the entire script.

Are you in the process of learning Python? It’s a fantastic language to learn, but as with any language, it does present challenges that can seem overwhelming at times, especially if you’re teaching yourself.

Given all the different ways of doing things in Python, we decided to compile a helpful list of issues that beginners often face — along with their solutions.

learning Python

1. Reading from the Terminal

If you’re running a program on the terminal and you need user input, you may need to get it through the terminal itself. (Other alternatives include reading a file to get inputs.)

In Python, the raw_input function facilitates this. The only argument the function takes is the prompt. Let’s look at a small program to see the result:

name = raw_input('Type your name and press enter: ')
print 'Hi ' + name

If you save those lines in a file (with a .py extension) and execute it, you get the following result:

Type your name and press enter: Shaumik
Hi Shaumik

One important thing to note here is that the variable is a string, and you need to filter and convert it to use it in a different form (like an input for the number of iterations or the length of a matrix):

name = raw_input('Type your name and press enter: ')
print 'Hi ' + name
num = raw_input('How many times do you want to print your name: ')
for i in range(int(num)):
    print name

2. Enumerating in Python

Python often presents ways of doing things different from other popular programming languages like C++ and Java. When you traverse an array in other languages, you increment an integer from 0 and access the corresponding elements of the array. The following shows a crude way of doing the same:

for (int i = 0; i < array_length; ++i)
    cout << array[i];

However, in Python, you can simply traverse each element of the array without using the indices at all:

for item in array:
    print item

What if there’s a need to access the indices too? The enumerate function helps you do so. Enumeration of an array (or a list, as it’s known in Python) creates pairs of the items in an array and their indices. The same can be demonstrated as follows:

>>> x = [10, 11, 12, 13, 14]
>>> for item in enumerate(x):
...     print item
...
(0, 10)
(1, 11)
(2, 12)
(3, 13)
(4, 14)

Imagine a situation where you need to print every alternate item in an array. One way of doing so is as follows:

>>> for index, item in enumerate(x):
...     if index % 2 == 0:
...         print item
...
10
12
14

3. Executing an External Command through Python

At some point, you may need to execute a terminal command within a Python script. This can be achieved through the call function under the subprocess module. There are many ways to do this, one of which is shown below:

>>> from subprocess import call
>>> call('cal')
     March 2016
Su Mo Tu We Th Fr Sa
       1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31

0

The last zero in the output shows that the subprocess we created within our script ended normally. In other words, there were no issues in running the command.

If you need to use arguments for the command, you need to append them to the main command as a list. For instance, to run the command ls -l, the following needs to be done:

>>> from subprocess import call
>>> call(['ls', '-l'])
total 16
-rw-------@ 1 donny  staff  439 Oct 21 16:06 chess.csv
-rw-r--r--  1 donny  staff   72 Mar  1 17:28 read.py
0

To check what happens to the 0 when something wrong happens, we can run a git command in a non git repository:

>>> from subprocess import call
>>> call(['git', 'status'])
fatal: Not a git repository (or any of the parent directories): .git
128

In the output, the second line is the output of the command, whereas 128 is the exit code.

4. Working with Exceptions

Python is an interpreted language, which means that the code is executed line by line. If an error is encountered on a line, further execution of the code stops. However, you can handle known exceptions in Python using the try-except block. Let’s look at a simple example, by generating a runtime error of dividing by 0:

>>> x = 1/0
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero

When the interpreter reaches this line, your program execution stops completely! However, using the try-except block can help avoiding the same.

>>> try:
...     x = 1/0
... except:
...     print "Some error occurred"
...
Some error occurred

When such an error occurs within the try block, the interpreter just executes the except block. The except block can further be extended by catching individual errors:

>>> try:
...     x = 1/0
... except ZeroDivisionError:
...     print "You tried to divide by zero"
... except:
...     print "Some unknown error occurred"
...
You tried to divide by zero

You can go one step ahead, catch the exception and further process it (like log the error somewhere) by modifying the except block:

>>> try:
...     x = 1/0
... except Exception as e:
...     print "Exception occurred: " + str(e)
...
Exception occurred: integer division or modulo by zero

5. Working with Modules

While looking at the code of others, you’ll often encounter this block of code:

def some_function():
    ...

if __name__ == '__main__':
    ...

This is used frequently when you create modules in Python. Ideally, the code in the last block usually demonstrates some basic usage of the function(s) above. When you run the file in the terminal, this code is executed. However, if you use this module in a different file for the purpose of using the function, this block is not executed. Confusing? Let’s understand this better through an example:

# File print.py
def print_me():
    print "me"

# demonstrating use of print_me
print_me()

Now, if I import this file to use the function in a new file, watch what happens:

>>> import print
me
>>>

The function gets executed as soon as you import the file. To avoid this, we put the function under a if __name__ == '__main__': block:

# File print.py
def print_me():
    print "me"

if __name__ == '__main__':
    # demonstrating use of print_me
    print_me()

When we modify the code, the print_me() function is executed only when you run it as a file, but not when you import it as a module:

>>> import print
>>>

Final Thoughts

If Python isn’t your first programming language, it’s going to take some time to adjust to its way of doing things. I recommend you watch an interesting YouTube video of Raymond Hettinger explaining this Pythonic Way of programming. In this post, I’ve attempted to cover a few of these Pythonic issues.

How was your Pythonic journey, or how is it still going? Do you prefer doing these tasks differently? Do let us know in the comments below!

Frequently Asked Questions (FAQs) about Python for Beginners

What are some common errors beginners make when learning Python?

One of the most common errors beginners make when learning Python is not understanding the importance of proper indentation. Python uses indentation to define blocks of code. If your code is not properly indented, it will not run correctly. Another common error is not understanding the difference between Python 2 and Python 3. These are different versions of Python, and some code that works in Python 2 will not work in Python 3. It’s important to know which version you’re using and to write your code accordingly.

Why is Python considered a good language for beginners?

Python is often recommended for beginners because of its simplicity and readability. The syntax in Python is designed to be easy to understand and write, which makes it a great language for beginners to learn. Additionally, Python has a large and supportive community, which means there are plenty of resources available for beginners.

What are some disadvantages of Python?

While Python is a powerful and versatile language, it does have some disadvantages. One of the main disadvantages is its speed. Python is an interpreted language, which means it tends to run slower than compiled languages like C or Java. Additionally, Python is not the best choice for mobile development, as it’s not as well-supported on mobile platforms as languages like Swift or Java.

How can I practice Python coding?

There are many online platforms where you can practice Python coding. Websites like Codecademy, HackerRank, and LeetCode offer interactive Python exercises that can help you improve your skills. Additionally, working on personal projects or contributing to open-source projects can also be a great way to practice.

What are some common Python coding challenges for beginners?

Some common Python coding challenges for beginners include understanding the syntax, learning how to work with data structures like lists and dictionaries, and getting comfortable with object-oriented programming. Additionally, beginners often struggle with understanding error messages and debugging their code.

How can I avoid common Python errors?

The best way to avoid common Python errors is to understand the basics of the language thoroughly. This includes understanding the syntax, data types, and control structures. Additionally, using a good IDE that provides syntax highlighting and error checking can also help you avoid common errors.

Is Python a good language for web development?

Yes, Python is a great language for web development. It has several powerful frameworks like Django and Flask that make it easy to build robust web applications. Additionally, Python’s simplicity and readability make it a good choice for server-side scripting.

Can I use Python for mobile app development?

While Python is not traditionally used for mobile app development, it is possible. There are frameworks like Kivy and BeeWare that allow you to write mobile apps in Python. However, these apps may not perform as well as apps written in languages that are more commonly used for mobile development, like Swift or Java.

What are some resources for learning Python?

There are many resources available for learning Python. Websites like Codecademy, Coursera, and Udemy offer online Python courses. Additionally, there are many great Python books available, like “Learn Python the Hard Way” and “Python Crash Course”.

How long does it take to learn Python?

The amount of time it takes to learn Python can vary greatly depending on your prior programming experience and how much time you can dedicate to learning. However, many people find that they can start writing simple Python programs after just a few weeks of study.

Shaumik DaityariShaumik Daityari
View Author

Shaumik is a data analyst by day, and a comic book enthusiast by night (or maybe, he's Batman?) Shaumik has been writing tutorials and creating screencasts for over five years. When not working, he's busy automating mundane daily tasks through meticulously written scripts!

python
Share this article
Read Next
Get the freshest news and resources for developers, designers and digital creators in your inbox each week