[PyTUT 7] FUNCTIONS IN PYTHON

Hi everyone,

So far, we have known how to use basic control structures to perform sequential, looping and selecting tasks. In this tutorial, to take a further step, I would show you the way to help you to manage your program easier when the number of lines in your code become larger and to make the program more concise.

The first thing I wanna show you is functions. It can be seen as blocks of code written to execute a specific task. A function can return whether values (like numbers, strings, lists, etc.) by using the command return or nothing (for example, functions that are used just to display information).

How to create a function

To create a function, we use the structure below:

def name_of_the_function(parameters):                      (1)
   statements                                              (2)

   (return value)                                          (3)

Remember, just like when using for-looping structures or if-structures, we need an indentation to make the Python interpreter understand which parts of code belong to the function.

Elements of a function

OK, let’s take a look at the structure of the function above.

In the line (1), the command def help the interpreter know that you are defining a function, followed by the name of the function. In addition, a function could have parameters or not. In the next section, I will show you more detail about how to pass arguments into a function.

In the line (2), we put statements here to perform desired tasks.

The line (3) shows that a function could return a value or not, depending your purpose when writing it.

Together, let’s make a ‘Hello World’ program, but now, we will write a function to do it instead of only using the command print.

The say_hello above is a function that doesn’t return any values, its purpose is just to print the line “Hello World” on the screen.

Here is another example, in which, a function return a value of an addition.

Or you can even return a list.

All the codes above can be downloaded from my github: https://github.com/tenga061/basic_python_tutorials/blob/master/pytut7_functions/lab1_elements_of_a_function.py.

Parameters of a function

Now, it’s time to take a further detail in parameters in function and how to pass arguments into it.

Now, let’s tweak the ‘Hello world’ program above by adding a parameter ‘name’ to it. Our program now won’t say hello world when we call it but say hello to the name that we have entered, instead.

By that way, we added a parameter and passed argument to our function.

The code can be downloaded from my github: https://github.com/tenga061/basic_python_tutorials/blob/master/pytut7_functions/lab2_say_hello.py.

Passing a fixed number of arguments

Let’s take a look at another example below. The code show a function using Euclid algorithm to find the greatest common divisor of two nonnegative m and n.

Functions that we made above is kind of functions with fixed number of parameters. Because of this, be careful when calling a function with parameters, the number of arguments you pass need to be equal to the number of parameters, otherwise, errors will occur.

You can download the code from my github: https://github.com/tenga061/basic_python_tutorials/blob/master/pytut7_functions/lab3_euclid_gcd.py.

Passing an arbitrary number of arguments

So, to have a function that permit you to pass the arbitrary number of arguments, there is two ways.

The first one is to put all values into a list and pass the list to the function.

The second is to put the symbol ‘*’ before the parameters of the function.

The codes can be downloaded from the link: .

Using default values

Sometimes, you want to set the default value for the parameters.

For example, back to the ‘Hello World’ example above. Now, we set the default value of parameter ‘name’ of the function to ‘World’, so, if we don’t pass any value into the function when calling it, it will print ‘Hello World!’ again, otherwise, it will say hello to the name we have passed.

The code can be downloaded here: https://github.com/tenga061/basic_python_tutorials/blob/master/pytut7_functions/lab5_say_hello_2.py.

The scope of variables

The last thing in this post I wanna tell you is that how vital to know the scope of variables.

Let’s continue to learn from codes together.

You can download the code here: https://github.com/tenga061/basic_python_tutorials/blob/master/pytut7_functions/lab6_scope_of_variable_1.py.

So, you can see the results clearly. The variables a and b which are initialized in the function check_print just exist while the function was running.

Now, if you wanna use the variables a and b as global variables, how could you do that? What if we don’t declare variable names in the function like the code below?

It’s OK, but don’t do that frequently, it sometimes brings to you serious mistakes in your code. To use global variables, I prefer to put ‘global’ before the name of variable in the function.

The code can be downloaded here: https://github.com/tenga061/basic_python_tutorials/blob/master/pytut7_functions/lab7_scope_of_variable_2.py.

OK, that’s all I wanna talk about in this post, in the next tutorial, I will introduce basic of classes in Python.

Hope you enjoy it,

Curious Chick

Advertisements

[PyTUT 6] CONTROL STRUCTURES

Hi everyone!

First of all, I would like to say thank you to all my friends and people who support me to make this series of Python tutorial. Two weeks ago, I shared the series with some of my friends and got many positive comments from them and they encouraged me to continue further. I would say that your concern really is my motivation to continue to do this.

OK now, let’s take a look at last tutorials a bit, in which, I introduced how to do some basic math with numbers, play with strings and three types of Python array, then assign values to variables.

To take a further step, in this tutorial, I want to show you control structures in Python.

By the way, I set up a new account on Github and from now, all codes will be published to the link below.

https://github.com/tenga061/basic_python_tutorials

And all codes in this tutorials were published on:

https://github.com/tenga061/basic_python_tutorials/tree/master/pytut6_control_structure

As usual, I recommend you to read the following topics before beginning this tutorial.

Related topics

Introduction

There are three types of control structures as you can see in Fig. 1. The first one is sequence structure that you used in the preceding tutorials. The second and last one is selection and loop structure, respectively.

fig.1

Fig. 1. Flow charts of three types of control structures [1]

In most programs, the two last structures proved to be helpful to make the codes more concise or more clear. But now, before beginning with them, let’s try using sequence structure again to make a simple program that print numbers from 0 to 9 on the screen but using Python script editor instead of Python Shell (or Python interpreter prompt).

Sequence

To open Python script editing window, do the following steps:

  • First, you need to open IDLE (read [PyTUT 1] AN INTRODUCTION OF PYTHON again if you don’t remember how to open IDLE).
  • Second, press CTRL + N  or left click on File -> New File on IDLE tool bar in order to open the Python script window.

fig.2_1

Fig. 2 Open IDLE script
  • Third, in Python script editing window, press CTRL + S or left click on File -> Save and name the file to save the script. Actually, it is unnecessary to save the script when you begin to code, but you ultimately must do this if you want to run the script.

fig.3_1.png

Fig. 3 Save script file

Following to this, we will start to write a first script that print the numbers from 0 to 9.

print 'The number from 0 to 9'
print 0
print 1
print 2
print 3
print 4
print 5
print 6
print 7
print 8
print 9

After that, press F5, then select OK when you are asked whether you wanna save this program or not in order to run the script (see Fig. 4).

fig.4_1

Fig. 4 Save all changes in your code before running

The result is showed in Fig. 5.

fig.5_1.png

Fig. 5 The result was showed on Python Shell

This code is available on: https://github.com/tenga061/basic_python_tutorials/blob/master/pytut6_control_structure/lab1_sequence_structure.py.

As you can see, in sequence structure, the computer will start to run the program from the begin to the end and follow the statements in order. However, imagine what if you want to print the numbers from 0 to 10,000. OK, it is still possible if you have a lot of time, right? Believe me, you will not want to do this.

For the reason of this, in the next section, I will introduce to you repetition structures which will help you to solve such repetitive problems.

Repetition

As I mentioned before, repetition structures are useful for repetitive problems. There are three types of repetition structures, including: for-loop, while-loop, and do-while-loop. First, look at the for-looping structure as showed in Fig. 6.

For-Looping Structure

The flow chart in Fig. 6 was taken from a C++ book but I think it’s still good to help you understand the mechanism of the for-looping structure in Python or even in any other programming languagues you want to learn in the future.

fig.6

Fig. 6 For-Looping Structure [1]

In C++, to create a for-loop, you first need a initial statement to initialize a loop variable. Then, declare a loop condition such as i < 10, where i is a loop variable. If i satisfies the condition (i < 10), statements in the loop will be performed and the loop variable will be updated after that (like i = i + 1 or i = i + 3, etc.). By contrast, the computer will close the loop and perform another statement.

The mechanism of for-loop in Python is similar to C++. However, if you were not familiar with C++ before, it still is OK. Let’s take a look at the example below that print numbers from 0 to 10 using the for-looping structure in Python:

for i in range(0, 10):
   print i

As you can see, to create a for-loop in Python, we first initialize a loop variable i, just like C++. However, there is a little bit different from C++. In Python, to create a loop condition, we use range(m, n) function which make a list from m to (n-1) with n>m, the upper bound n of the range function is implied as the loop condition i < (n-1). Additionally, the loop variable will automatically update itself in every value in the list in every loop (see Fig. 7 to understand how it works).

fig.7

Fig. 7 The way the for-loop structure work in Python

Now, what if you want to print only odd numbers from 0 to 9? Fortunately, you can add step argument into the range(m, n, step) function. So, the code become:

for i in range(1, 10, 2):
   print i

(This script is available on: https://github.com/tenga061/basic_python_tutorials/blob/master/pytut6_control_structure/lab2_for_loop.py)

The results are illustrated in Fig. 8.

fig.8

Fig. 8 For-looping structure example results

Not only those, for-looping structure of Python is even more flexible, by which, you can loop to print arbitrary numbers as you want by assigning the value of each element in the list to loop variable.

arbitrary_numbers = [9, 123, 59, 1039, 23, 27]
for number in arbitrary_numbers:
   print number

You can even do this for tupe:

lovely_cities = ('Paris', 'Los Angeles', 'Seoul', 'Tokyo')
print 'Here is some of the lovely cities: '
for city in lovely_cities:
   print '   + ' + city

Or dictionary type:

hp_characters = {'Danial Radcliffe': 'Harry Potter', 
                 'Emma Watson': 'Hermione Granger',
                 'Rupert Grint': 'Ron Weasley'}
for actor, character in hp_characters.iteritems():
   print actor + ' played ' + character + ' in the series of Harry Potter'

OK, you saw how useful is it when using for-loop to solve repetitive tasks. But you can only use the for-loop if you know exactly how many time it loop. For some problems that you don’t now the number of loop, you need to use while-looping structures which will be introduced in the next section.

While-Looping Structure

fig.4.png

Fig. 9 While Looping Structure [1]

As I mentioned before, in while-loop, you don’t needa know how many times your loop will run but loop conditions such as i \leq n or i \neq n . In the case, we use while-looping structure.

While-looping structure begin by checking the condition loop or expression like i \leq n . Then, if the condition is satisfied, statements in the loop will be executed. Otherwise, the loop will be ended. Note that, of course we can’t type symbol like \geq or \neq in any programming languages. Instead, we use these signs in the table below.

Table 1. Relational operators [1]

operator_in_python

For example, we want to write a program that read arbitrary numbers from user. If the number is equal or less than 9, the program is continue, by contrary, it stop and print the line “Goodbye and see ya”.

user = 1

while (user<=9):
   a = raw_input('Please enter an arbitrary number: ')
   user = float(a)

print 'Goodbye and see ya'

The code can be downloaded here: https://github.com/tenga061/basic_python_tutorials/blob/master/pytut6_control_structure/lab3_while_loop_game_1.py.

Now, what if you wanna use more than one looping condition, for example, the program will continue requiring you to enter an arbitrary number if your entered-number is equal or less than 9 and more than 6. In the case, we needa use boolean operator and.

user = 1

while (user>6) and (user<=9):
 a = raw_input('Please enter an arbitrary number: ')
 user = float(a)

print 'Goodbye and see ya'

Similarly, you can use boolean operator or in Python by typing or. It’s little bit different for people who were familiar with C++ or other lower programming language, in which, they must use && for the boolean and and || for the or. So, please note that, in Python, we just needa type and for the and and or for the or.

Do-While-Looping Structure

fig.5

Fig. 10 Do-While-Looping Structure [1]

The only difference between while-loop and do-while loop is that statments in the loop will be excuted at least one. In detail, if the looping condition is wrong from the begining of the loop, the while-loop will end without any statements executed, while statements in do-while-loop still is executed once because it is executed before looping conditions are checked.

Nested Looping Control Structures

Just like other programming languages, we can use looping structures in looping structures to handle more complicated tasks. You can write a simple code that paint a Christmas tree using only for loop. Here is my sample:

for m in range(3):
   for i in range(1, 5+m):
      for j in range(5-i+1):
         print ' ',
      for k in range(5-i+1, 5+i):
         print '*',
      print

And the result:

christmas_tree

Fig. 11 The result of the Christmas tree program

You can download the code from my github link: https://github.com/tenga061/basic_python_tutorials/blob/master/pytut6_control_structure/lab4_christmas_tree.py.

Python loop controls

In this part, I would like to introduce some special commands that help you handle your loop somtimes.

pass

As its name, it mean ‘don’t do anything’. It sounds pointless, but sometimes we use it with the loop to wait for an occurrence of an event or an interupt.

Here is an example of using pass command in a loop:

while(1):
   pass

The program above will run until you close the termial.

break

This command is another way to end looping structures whenever it satisfy the condition that you set.

For example,

i = 0
while 1:
   print i
   i = i + 1
   if i > 5:
      break

Running the program and you will get the result as illustrated in Fig. 12.

Theoretically, the program should run and print the value of i till we close the terminal. However, because we set a break in the if block (will be introduced in the next section), the break break the loop when i = 6.

break_command

Fig. 12 An example of using break for while-loop

You can also use the break command in for-loop. The example below using for-loop but show the same result.

for i in range(10):
   if i > 5:
      break
   print i

When I was an undergraduate student, my professor who taught me the subject ‘Programming Fundamentals’ often prohibit us from using this command because, as he said, the break break the structure of programs. However, I think this control command sometimes is useful, especially, it is used frequently in programming for microcontroller. Anyway, you should consider carefully if you want to use it in your program.

continue

This command returns the control to the beginning of the loop. Let’s run the following program to see how it work.

i = 0
while i<10:  
   i = i + 1
   if i == 5:
      continue
   print i

The result is described in Fig. 13.

continue_command

Fig. 13 An example of using the command continue in a program

We can see that the command continue in the program above is the reason why we miss the number 5. In details, when i reach the value 5, the if condition is satisfied, then the command continue is run. As a result, the control of the loop go back to the begining without execute the line print i (i.e print i = 5 on the screen).

Selection

Now, we turn to the last structure of this tutorial – selection or if-structure. In the previous section (Python loop control), I briefly show you using the selection structure to make condition for breaking the loop. Now, we introduce further.

One-Way Selection

The simplest form of selection structures are one-way selection. In which, we use an if condition or expression to decide whether statements should be executed or not. In selection structures, the expression is described as the same way as the expression of while-loop in Table 1.

fig.2

Fig. 14 One-Way selection [1]

Let’s me show you an example in the normal life. Assume that you go to the market and want to buy a fish for lunch. You go to a stall and ask the price of a fish, if it is lower than $10, you buy it, but if not, you don’t. Here is a code:

print 'How much money for this fish?'
fish_price = raw_input("It's: $")
fish_price = float(fish_price)
if fish_price>10:
   print 'Sorry, I don\'t wanna buy it'

Now, run the program, enter 20 for the cost of the fish, you will get the result ‘Sorry, I don’t wanna buy it’.

Multiple Selection

fig.3

Fig. 15 Two-Way selection [1]

From the view of real life problems, you can see that it’s not simple like that. Here is another script: You go to the supermarket, ask the price of the fish, if the price less than $10 then you buy it, if not, you deal with the salesman that if you could buy it with the price of $13.

To do the script above we need to know how to use the multiple selection structure. Here is the structure of two-way selection (as described as Fig. 15)

if condition:
   statements
else:
   statments_2

If you need more than 2, we use elif for conditions and else for the last one.

if condition_1:
   statements
elif condition_2:
   statements_2
...
elif condition_n:
   statments_n
else:
   statements_(n+1)

Here is the script of the problem above.

print 'How much money for this fish?'
fish_price = raw_input("It's: $")
fish_price = float(fish_price)
if fish_price<10:
   print 'OK, give me one.'
else:
   print 'Could I buy it with $13?'

Nested Selecting Control Structures

Just like repetition structures, you can put selection structures into others. Here is a small example of using nested selecting control structures.

Just for fun

OK, so, I introduced you the foundation of control structures in Python. Now we can use it to make a simple entering-password code. In which, users are asked to enter their password, if the entered password is right, the program will show them where were  the mythical treasures hide, if not, the program will end with curse: ‘You have wrong answer for 5 times. Now, you will not be able to eat candy. Ha ha ha!’.

You can download the code from my github: https://github.com/tenga061/basic_python_tutorials/blob/master/pytut6_control_structure/lab5_mythical_treasure.py.

So this is the end of this topic. In the next, I would introduce you function, class and package in Python. Goodbye and see you again.

Hope you enjoy it,

Curious Chick

References

[1] D. S. Malik, C++ Programming: From problem analysis to program design (Sixth Edition), Cengage Learning (2013)

[PyTUT 5] ARRAYS IN PYTHON

Hi everyone, in this tutorial, I want to introduce another type of data in Python – array.

Related topics

Before beginning this tutorial, I recommend you should read the following topics:

[PyTUT 2] NUMBERS AND OPERATORS

[PyTUT 3] STRINGS

[PyTUT 4] VARIABLES AND COMMENTS

If you have already read these, let’s start to know what is array and what is it used for?

Introduction

Some of you may know that array is an useful type of data that permits programmers to store sets of information in one variable and to do the same thing with each element of it. This helps you to avoid making a lot of duplicated code. For example, assume that you want to store test scores of 5 students and then calculate the average test score of them. So, how could you do that? Here is 2 ways, let’s open IDLE and follow me.

Code 1

>>> student1 = 7.5
>>> student2 = 9.0
>>> student3 = 8.5
>>> student4 = 8.5
>>> student5 = 10.0
>>> average_score = (student1 + student2 + student3 + student4 + student5)/5
>>> print average_score
8.7

Well, everything seem to be more effective when using array.

Code 2

>>> student_scores = [7.5, 9.0, 8.5, 8.5, 10.0]
>>> average_score = sum(student_scores)/len(student_scores)
>>> print average_score
8.7

OK, in the example above, you saw how useful is it when using array instead of declaring a lot of variables. And it will be more effective to use array when the number of students (in the example) increase to n, with n is extremely large.

Now, let’s continue to know how to create an array in Python.

If you used to program in C/C++ or other compiled programming languages such as Java and C# before, you could know the popular structure below to create an array:

type variable_name = {value 1, value 2, value 3, ... , value n}

The compiled programming languages use braces {} to declare array of values, and you have to put the ‘type of variable’ before ‘variable’s name’. And of course, because the array have its type, the values in which must respect to the type of the array. It means if you declare the type of array string, all values in array must be string data type. Similarly, you must put integer (or float) values into your array, if you declare its type integer (or float). It sounds a bit complicated.

In Python, you don’t have to declare array data type. Instead of that, Python will consider the array data type by looking at the type of the value in array. Moreover, you can put any type of value in an array (like the code below). What a powerful weapon!

>>> iron_man = ['Tony Stark', 38, 1.82, 83, 'billionaire', 'play-boy']

However, there are some discrepancies between Python arrays depending on which kind of arrays you use. Let’s take a look through typical types of array in Python.

List

  • Creating a list

In Python, we use square bracket [] to make a list and commas to separate individual elements. For example:

>>> student_name = ['harry potter', 'ron westly', 'hermione granger']
>>> student_weight = [54, 60, 43]
  • List index

Index is an essential part of array. It is used to access elements in an array. For example, accessing the score of the third student in ‘student_scores’ array from previous example.

>>> print student_scores[2]
>>> 8.5

Remember that, index is counted from 0, so you use index 0 for the first element, 1 for the second one, 2 for the third one, and so forth.

On the other hand, you can use a negative number to be an index of a list. In this case, the index will be counted from the right, begin from -1.

>>> print student_scores[-1] 
>>> 10.0
>>> print student_scores[-2] 
>>> 8.5

In addition, you can access more than one elements from the index m to (n-1) by using the structure below:

>>> print array_name[m, n]

For example:

>>> print student_scores[1:3]
>>> [9.0, 8.5]
  • Updating an element in a list

To update an element in a list, you just simply call its index in the list and change its value. Look at the example below to see how is the score of the third student changed.

>>> print 'The score of the third student is: %.1f' %student_scores[2]
>>> The score of the third student is: 8.5
>>> student_score[2] = 9.5
>>> print 'The new score of the third student is: %.1f' %student_scores[2]
>>> The new score of the third student is: 9.5
  • Deleting an element in a list

There are many ways to delete an element in a list. You can delete an element by using ‘del’ command as the example below:

>>> print student_scores
>>> [7.5, 9.0, 9.5, 8.5, 10.0]
>>> del student_scores[2]
>>> print student_scores
>>> [7.5, 9.0, 8.5, 10.0]

Or you can use the built-in methods ‘remove’ to delete an element if you want to delete the exact value that you knew in the list. In the example below, I want to delete the value 7.5 in the list ‘student_scores’.

>>> print student_scores
>>> [7.5, 9.0, 8.5, 10.0]
>>> student_scores.remove(7.5)
>>> print student_scores
>>> [9.0, 8.5, 10.0]
  • Adding an element into a list

To add an element into a list, we use append() which is a built-in methods of list to add the element into the end of the list.

>>> print student_scores 
>>> [9.0, 8.5, 10.0]
>>> student_scores.append(9.5)
>>> print student_scores 
>>> [9.0, 8.5, 10.0, 9.5]

On the other hand, you can use insert() which is also a built-in methods of list to add the element into any position you want in the list.

>>> print 'The score of the third student is: %.1f' %student_scores[2]
>>> 10.0
>>> student_scores.insert(8.0, 2)
>>> print 'The score of the new third student is: %.1f' %student_scores[2]
>>> 8.0
  • Basic List Operations

Similar to strings, we can use addition operator + and multiplication operator * to concatenate and repeat lists, respectively.

>>> a = [1, 2, 3]
>>> b = [4, 5, 6]
>>> c = a + b
>>> print c
>>> [1, 2, 3, 4, 5, 6]
>>> d = a*3
>>> print d
>>> [1, 2, 3, 1, 2, 3, 1, 2, 3]
  • Useful Built-in methods for number list

Now, you are able to do a lot of things with lists. However, I want to show you a little further with some useful built-in methods which are often used to treat a list of number. I will illustrate these methods with the ‘student_scores’ example above.

>>> print 'The number of student:'
>>> The number of student:
>>> print len(student_scores)
>>> 5
>>> print 'The highest score:'
>>> The highest score:
>>> print max(student_scores)
>>> 10.0
>>> print 'The student who have the highest score: '
>>> The student who have the highest score:
>>> print 'Student number %d' %(student_scores.index(max(student_scores))+1)
>>> Student number 4
>>> print 'The lowest score:'
>>> The lowest score
>>> print min(student_scores)
>>> 8.0
>>> print 'The student who have the lowest score:'
>>> The student who have the lowest score:
>>> print 'Student number %d' %(student_scores.index(min(student_scores))+1)
>>> Student number 3
>>> print 'The number of student who get 9.0 in the examination: '
>>> The number of student who get 9.0 in the examination:
>>> print student_scores.count(9.0)
>>> 1
>>> print 'The order of the scores from low to high'
>>> The order of the scores from low to high
>>> print student_scores.sort()
>>> [8.0, 8.5, 9.0, 9.5, 10.0]
  • Dimension of a list

In the previous examples, we created 1D dimension list, now try to create a higher dimension list by adding a list into another lists.

>>> 1d_list = [1, 2, 3] # 1D list with shape [3]
>>> 2d_list = [[1, 2, 3], [4, 5, 6]] # 2D list with shape [2, 3]
>>> 3d_list = [[[1], [2], [3]], [[4], [5], [6]]] # 3D list with shape [2, 3, 1]
>>> print 3d_list[0][1][0]
>>> 2

High dimension lists seem to be unfamiliar now, but you will probably work a lot with it in the future if you expect to work in the field of image processing.

Tuple

Tuple is known as immutable list. It means you cannot change, append or delete the value of elements in tuple.

To declare a tuple, we use parentheses () instead of square brackets [].

>>> countries = ('Vietnam', 'America', 'Germany', 'France', 'Canada')
>>> first_eleven_fibonacci_number = (1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)

Most built-in methods or operations which are used in list can also be used in tuple.

>>> print max(first_eleven_fibonacci_number)
>>> 89
>>> print sum(first_eleven_fibonacci_number)
>>> 232
>>> k = countries + first_eleven_fibonacci_number
>>> print k
>>> ('Vietnam', 'America', 'Germany', 'France', 'Canada', 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89)

However, as I mentioned before, you cannot change, append or delete in tuple. If you try to do it, you will get errors.

>>> first_eleven_fibonacci_number[4] = 99

Traceback (most recent call last):
 File "<pyshell#39>", line 1, in <module>
 first_eleven_fibonacci_number[4] = 99
TypeError: 'tuple' object does not support item assignment
>>> del first_eleven_fibonacci_number[7]

Traceback (most recent call last):
 File "<pyshell#40>", line 1, in <module>
 del first_eleven_fibonacci_number[7]
TypeError: 'tuple' object doesn't support item deletion

Dictionary

In the final section, I would like to introduce another type of arrays in Python – dictionary.

pytut5

Fig. 1 Structure of a dictionary

A dictionary which is declared by using braces {} include keys and values as Fig. 1. The keys are used to connect to and access values. The values can be numbers, strings, lists, or even dictionaries.

>>> satre = {'name': 'Jean-Paul Satre', 'aged': 74, 'country': 'France', \
             'works': ['Le mur', 'Les mouches', 'Le sursis']}
>>> print '%s died in Paris, France, aged %d' %(satre['name'], satre['aged'])
>>> Jean-Paul Satre died in Paris, France, aged 74
>>> print 'Three of his famous books are:'
>>> Three of his famous books are:
>>> print satre['works'][0]
>>> Le mur
>>> print print satre['works'][1]
>>> Le mouches
>>> print print satre['works'][2]
>>> Le sursis

Most things you can do with lists and tuples, you can also do with dictionaries but you need to use key instead of index.

>>> print 'Deleting Satre's age'
>>> Deleting Satre's age
>>> del satre['age']
>>> print 'The amount of information about Satre: %d' %len(satre)
>>> The amount of information about Satre: 3

However, you cannot use operator such as + or * for dictionaries as lists and tuples. On the other hand, to add a new key-value into the dictionary, you cannot use append() method. Instead, you can do this.

>>> satre['philosophy'] = 'Existentialism'

So, with all basic things I introduced, you are now able to do a lot of things with arrays in Python. In the next tutorial, I will introduce control structures and we will try writing the first script in Python.

 

Hope you enjoy it,

Curious Chick

[PyTUT 4] VARIABLES AND COMMENTS

Hi everybody, this is a small tutorial I want to show you before introducing arrays in Python because we will use it in the next tutorial.

Related topics

[PyTUT 2] NUMBERS AND OPERATORS

[PyTUT 3] STRINGS

Variables

To put it simply, we can think of a variable as a name of a value which can be a number, string, list, tuple, or even dictionary. In fact, every time when we declare a variable, the interpreter will allocate memory for its value.

A value can be assigned to a variable by using equal sign = and it can be any type of data such as number, string, or array data type in Python (list, tuple, and dictionary).

>>> a = 8
>>> b = 9.0
>>> c = float(a)
>>> print c
>>> 8.0
>>> d = 'Hello '
>>> e = 'Adele'

To access a value from a string or number type variable, we simply call and perform operations with its name.

>>> s = a + b
>>> print s
>>> 17.0
>>> st = d + e
>>> print st
>>> Hello Adele

See that, whatever you can do with 2 numbers or 2 strings, you can also do with 2 variables which stores 2 numbers or 2 strings.

However, it is different when accessing value from array data types in Python. In the next tutorial, I will introduce to you how to deal with it.

Comments

Sometimes, you may make a long code in your project and it will be tough to work with it again after a long time if you don’t note the meaning of parts in your program. That’s why we need to use comments in our program. A comment is made by putting a hash mark # before a message.

>>> theta = 5.0 # initializing theta
>>> bias = 1.3 # initializing bias
>>> x = 2 # initializing variable
>>> y = theta*x + bias # estimating the model

Although all comments are ignored by Python interpreter, it is an crucial part in a Python program. The more you make good comments in your code, the more you save your time.

That’s all. Is it easy?

In the next tutorial I will introduce array data types used in Python. Well, it will be a long tutorial and you will have a lot of things to do.

 

Hope you enjoy it,

Curious Chick

[PyTUT 3] STRINGS

In the last tutorial, you knew how to do basic math with number and convert a number type to another one. In this tutorial, I will introduce a non-number type in Python called Strings.

Creating a string

There are two ways to create a string:

>>> 'Put the string here'
'Put the string here'

or

>>> "Put the string here"
'Put the string here'

It is simple, isn’t it? In Python, there is no distinction between single quoted and double quoted string. So, you can choose your favorite way to create it. For me, I prefer the first one.

In a Python program, a string is often used to display information or the value of a variable by using ‘print’ command. So, the string will has no sense if it stays alone. On the other hand, the string above is displayed on the screen every time you enter a string because you are using IDLE script. Nevertheless, string will not print itself when you run .py file unless you use ‘print’ command in your program.

Now, we will try using ‘print’ command to print a string on IDLE scripts. Do you still remember this command which was introduced in the first tutorial? It will be OK if you do not, because I will show it again.

>>> print 'I wanna be Spider-man'
I wanna be Spider-man

String with special character

Now, try printing this string “Bobby’s cat was killed by “You-know-who””. It seems straightforward, right? However, if you try doing this

>>> print "Bobby's cat was killed by "You-know-who""
SyntaxError: invalid syntax

or

>>> print 'Bobby's cat was killed by "You-know-who"'
SyntaxError: invalid syntax

you will get the error. It is caused by the Python recognize a string by looking at the characters between two single or double quotes. Thus, you may confuse the Python by using many quotes in a string.

So, to deal with this problem, you need to use a trick by adding character \ before the quote to make Python understand that you are using the special character in a string. The problem is solved now.

>>> print "Bobby's cat was killed by \"You-know-who\""
Bobby's cat was killed by "You-know-who"

or

>>> print 'Bobby\'s cat was killed by "You-know-who"'
Bobby's cat was killed by "You-know-who"

Besides, there are many special characters which are used in string (refer to [1] for more information). For example, \t is used to make a horizontal tab while \v used to make a vertical tab.

>>> print 'Hello there'
Hello there
>>> print 'Hello \t there'
Hello      there

Operators with string

Different from number types, addition operator is used to concatenate two string.

>>> print 'Spider' + 'man'
Spiderman

On the other hand, you can use *2 to double the string.

>>> print 'Dona '*2
Dona Dona

However, you cannot use *, -, or / with the aim of multiplying, subtracting, or dividing two strings.

Some useful built-in string methods

Sometimes, you can use these built-in methods below to manipulate your string easily.

>>> print 'hey jude'.capitalize()
Hey jude
>>> print 'hey jude'.title()
Hey Jude
>>> print 'hey jude'.upper()
HEY JUDE
>>> print 'HEY JUDE'.lower()
hey jude

If you want to get the length of the string, use len method.

>>> print len('hey jude')
8

To know more about the built-in methods in Python, you can refer to [2].

String with numbers

This is the final section and also the most important in this tutorial.

As I mentioned before, string is often used to display information or the value of a variable in a program. The problem is that, if you use this structure

>>> print 'The value of x is ' + 9
Traceback (most recent call last):
   File "<pyshell#22>", line 1, in <module>
      print 'The value of x is ' + 9
TypeError: cannot concatenate 'str' and 'int' objects

you will get the error because you cannot add a string to a number. So, if you want to do this you will need to convert the number to the string by using:

>>> str(9)

And now, you get the result:

>>> print 'The value of x is ' + str(9)
The value of x is 9

Moreover, to display the value of a variable, you can also use this structure:

>>> print 'The value of x is %d' %9
The value of x is 9

or

>>> print 'The value of x is ', 9
The value of x is 9

OK, with these simple knowledge, you can do somethings cool with string by yourself. In the next tutorial, I will introduce Python array type called list and tuple.

Hope you enjoy it,

Curious Chick

References

[1] https://www.tutorialspoint.com/python/python_strings.htm

[2] https://docs.python.org/2/library/strings.html

[PyTUT 2] NUMBERS AND OPERATORS

Have you installed Python on your computer?

Following to the previous tutorial, today I would like to introduce you the numbers and operators used in Python. Before beginning this tutorial, I want to notice again that all codes in the series of ‘Basic Python tutorials’ are written in Python 2.7.11. Thus, may be you have to change a little bit with your code if you use another version, especially  version 3.

Let’s take a look at the numbers and operators used in Python.

Numbers and operators

Python treats the numbers in two main types: integer and float. The others are long and complex. This tutorial focuses on the first two number types. However, you can do the same tasks with the long and complex.

Just like the other programming language, integer and float numbers can be used with the operators such as add ‘+’, subtract ‘-‘, multiply ‘*’ and divide ‘/’. However, there are some different between these two types of numbers (you can see it soon).

Now, let’s open IDLE (or your text editor, or even Command Prompt) and do basic math with Python:

Example 1: The operators with two integers

>>> 9+4
13
>>> 9-4
5
>>> 9*4
36
>>> 9/4
2

Example 2: The operators with two floats

>>> 9.0+4.0
13.0
>>> 9.0-4.0
5.0
>>> 9.0*4.0
36.0
>>> 9.0/4.0
2.25

After the examples, we can see that the significant different is showed when you used the division operator ‘/’. When two integer are divided, the result is always an integer (see Ex. 1). If you want to determine the remainder of 9/4, you will need the remainder operator ‘%’ (this operator is useful in some cases that I will mention it later in another tutorial).

>>> 9%4
1

Note: If you use the operators with an integer and a float, Python will understand that you want to use the operators with two floats. For example:

>>> 9/2.0
4.5

Number type conversion

Sometimes, you expect to change the type of number to satisfy requirements of an operator or an function parameter. Here are some ways:

To convert a number x to integer, we use the following structure:

>>> int(x)

Example 3: Convert a complex number 4.0 to integer

>>> int(4.0)
4

Similar to this, Python supports the structures that help you to convert a number to

float type

>>> float(x)

long type

>>> long(x)

complex type ( where x is real part and y is imaginary part)

>>> complex(x)
>>> complex(x, y)

Note: You cannot convert complex to int

 

That is all about basic math with Python. It is simple, isn’t it?

In the next tutorial, I will talk about string in Python and some ways you can do to treat strings.

 

Hope you enjoy it,

Curious Chick

 

[PyTUT 1] AN INTRODUCTION OF PYTHON

Hi everybody!

Today, I decided to make a series of tutorials in order to introduce Python programming language to beginners.

In this series, I will not get into detail. Instead, I will introduce a decent information to you so that you can use it to build your own applications. On the other hand, in every tutorial, I will recommend some good books to you to improve your knowledge if it is necessary.  OK, let’s take a look at the introduction.

Introduction

Nowadays, Python has been being used widely. According to [1], Python was ranked third among the most popular programming languages in the world in 2016. Its popularity can be explained by 3 main reasons.

The first reason is that Python is a high-level programming language with clear syntax. Thus, user can learn it quickly without any hard efforts (honestly, it is not true if you learn programming language for the first time). However, there are a lot of high-level programming languages and some of theme even more efficient than Python like Julia, why have Python still been a favorite choice? That was caused by a large number of Python communities. A lot of people and organization currently use Python, it means there are a lot of available sources for you when you begin to learn. On the other hand, you can take part in a community and easily find out the solutions by asking the questions if you get troubles. The final reason is that some programming language such as MATLAB or Mathematica may cost you thousand dollars to legally use it, so you may get troubles if you use crack version of these software in your publications. By contrast, Python and most of its library are open-source, so you can use it without any cost. That is also the main reason why I love Python much.

Installation

To install Python, you can access the link: https://www.python.org/downloads/ and choose the version you want to download. After that, run the setup file to install Python in your computer.

installing_python

Fig. 1 The versions of Python

There are two versions of Python: 2.* and 3.*. I prefer to use the version 2.* rather than 3.*, and the version I installed in my computer is 2.7.11. You can choose your favorite verson, but please note that there are a bit different between these two versions.

For example:

  • You can use this syntax for Python 2.* to print the string “My name is Javis” on the screen but cannot use it for Python 3.*.
>>> print "My name is Javis"
  • If you want to print this string on screen by Python 3.*, you have to put the string into the parentheses. The syntax now change a little bit.
>>> print ("My name is Javis")

On the other hand, there are some libraries which can be used in a Python version but cannot be used in the other one. An example of this is that only Python version 3.5 can run TensorFlow library on Window.

Running the first program

After installation, you can run the IDLE which was installed along with Python to write your first program. However, if you do not like using IDLE, you can download the other text editors such as Geany, Spyder, etc or even you can use Notepad to code.

To keep it simple, I will use IDLE of Python version 2.7.11 for this tutorial.

In order to open IDLE on Windows OS, type ‘idle’ in search box and choose IDLE (Python GUI) as Fig. 2.

idle

Fig. 2 Open IDLE of Python 2.7.*

In the screen of IDLE, type the string below:

>>> print "Hello World!"

Then, press Enter, you will see the result as Fig. 3.

python_hello_world

Fig. 2 “Hello World” program

This is the end of this tutorial. In the next tutorial, you will learn how to use numbers and operators in Python.

Hope you enjoy it,

Curious Chick

References

[1] http://spectrum.ieee.org/computing/software/the-2016-top-programming-languages