Wednesday, May 11, 2016

5 Common Problems Faced by Python Beginners

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:

[code]name = raw_input('Type your name and press enter: ')
print 'Hi ' + name[/code]

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

[code]Type your name and press enter: Shaumik
Hi Shaumik[/code]

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):

[code]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[/code]

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:

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

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

[code]for item in array:
print item[/code]

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:

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

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

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

Continue reading %5 Common Problems Faced by Python Beginners%


by Shaumik Daityari via SitePoint

No comments:

Post a Comment