Introductino to Python (part II)

This notebook provides introduction to python and includes material covered during the lecture.

Printing


In [1]:
print("Imagine all the people living life in peace... John Lennon")


Imagine all the people living life in peace... John Lennon

To print part of a text on a new line, \n tag is used.


In [2]:
print("Imagine all the people \nliving life in peace... \nJohn Lennon")


Imagine all the people 
living life in peace... 
John Lennon

To tabulate part of a text forward, \t tag is used.


In [3]:
print("Imagine all the people \nliving life in peace... \n\tJohn Lennon")


Imagine all the people 
living life in peace... 
	John Lennon

User inputs

To automatically save all user inputs ass one single string, raw_input() function is used.


In [4]:
collection = raw_input("Input some numbers seprated by a comma: ")


Input some numbers seprated by a comma: 5,6,7

In [5]:
print(collection)


5,6,7

In [6]:
type(collection)


Out[6]:
str

To convert the comma-separated string (as the one above, inputted by the user) into a list of elements, split() function is used.


In [7]:
# split function takes one argument: the character to split the string on (comma in our case).
our_list = collection.split(",")

In [8]:
print(our_list)


['5', '6', '7']

Functions

def is used to define a function.

A function should either return some value, or print it.


In [9]:
def adjectivizer(noun):
    return noun+"ly"

In [10]:
adjectivizer("man")


Out[10]:
'manly'

THe function below is the upgrade of above function. It first checks the length of the function argument. If it is more than 3, it adjectivizes the noun, else it adds "super" in front.


In [11]:
def superly(noun):
    if len(noun)>3:
        return noun+"ly"
    else:
        return "super"+noun

In [12]:
superly("cat")


Out[12]:
'supercat'

The function below is the upgrade of above function. It checks one more condition: adjectivizes if more than 4 letters, leaves the same in case of four (note the double equal sign) and adds the "super" in front in other cases.


In [13]:
def superly4(noun):
    if len(noun)>4:
        return noun+"ly"
    elif len(noun)==4:
        return noun
    else:
        return "super"+noun

In [14]:
superly4("late")


Out[14]:
'late'

Same function as above, just with one more condition checked (==5).


In [15]:
def superly5(noun):
    if len(noun)>4:
        return noun+"ly"
    elif len(noun)==4:
        return noun
    elif len(noun)==5:
        return "super"+noun
    else:
        return "to short noun"

In [16]:
superly5("truth")


Out[16]:
'truthly'

Currency converter

The function below asks the user to input some currency (\$ or e sign followd by amount of money) and converts it to Armenian drams. Those are the steps taken:

  1. Inputs is saved as one single string.
  2. The very first character of string is checked to understand the currency.
  3. If it is "\$", then the function takes the amount user inputted (all the string but the very first character which was the "\$" sign), converts to an integer (using the int() function), multiplies it by 484 (exchange rate) to get the value in drams, convert the results back to string (using the str() function) and adds " AMD" to that string.
  4. If it is "e", then the function takes the amount user inputted (all the string but the very first character which was the "e sign), converts to an integer (using the int() function), multiplies it by 535 (exchange rate) to get the value in drams, convert the results back to string (using the str() function) and adds " AMD" to that string.
  5. If the very first character is neither "\$" nor "e", then the function returns a notification, asking the user to type "\$" or "e" in front.

Then the result is printed.


In [17]:
amount = raw_input("Please, input currency followed by amount ")
def c_converter(amount):
    if amount[0]=="$":
        return str(484*int(amount[1:]))+" AMD"
    elif amount[0]=="e":
        return str(535*int(amount[1:])) + " AMD"
    else:
        return "Please, use $ or e sign in front"
print c_converter(amount)


Please, input currency followed by amount $100
48400 AMD

Multiple conditions

Given the numbers between 7 (included) and 1700 (not included), let's choose those that can be divided by 5. For that reason the % (knows as "modulus") operator is used. % operator results in the residual after the division. For example, 5%2 will result in 1 and 6%4 will result in 2. In order to check whether some number can be divided by 5 or not, we must check whether numer%5 is 0 or not.

If we want to save the resulting values somewhere, then let's first create an empty list, which will then be added by 5-divisable numbers.


In [18]:
# create an empty list
our_list=[]
# iterate over all numbers in the given range
for number in range(7,1700):
    # if the reminder is 0
    if number%5==0:
        # append/add that number to our list
        our_list.append(number)

In [19]:
# let's print our list
print our_list


[10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95, 100, 105, 110, 115, 120, 125, 130, 135, 140, 145, 150, 155, 160, 165, 170, 175, 180, 185, 190, 195, 200, 205, 210, 215, 220, 225, 230, 235, 240, 245, 250, 255, 260, 265, 270, 275, 280, 285, 290, 295, 300, 305, 310, 315, 320, 325, 330, 335, 340, 345, 350, 355, 360, 365, 370, 375, 380, 385, 390, 395, 400, 405, 410, 415, 420, 425, 430, 435, 440, 445, 450, 455, 460, 465, 470, 475, 480, 485, 490, 495, 500, 505, 510, 515, 520, 525, 530, 535, 540, 545, 550, 555, 560, 565, 570, 575, 580, 585, 590, 595, 600, 605, 610, 615, 620, 625, 630, 635, 640, 645, 650, 655, 660, 665, 670, 675, 680, 685, 690, 695, 700, 705, 710, 715, 720, 725, 730, 735, 740, 745, 750, 755, 760, 765, 770, 775, 780, 785, 790, 795, 800, 805, 810, 815, 820, 825, 830, 835, 840, 845, 850, 855, 860, 865, 870, 875, 880, 885, 890, 895, 900, 905, 910, 915, 920, 925, 930, 935, 940, 945, 950, 955, 960, 965, 970, 975, 980, 985, 990, 995, 1000, 1005, 1010, 1015, 1020, 1025, 1030, 1035, 1040, 1045, 1050, 1055, 1060, 1065, 1070, 1075, 1080, 1085, 1090, 1095, 1100, 1105, 1110, 1115, 1120, 1125, 1130, 1135, 1140, 1145, 1150, 1155, 1160, 1165, 1170, 1175, 1180, 1185, 1190, 1195, 1200, 1205, 1210, 1215, 1220, 1225, 1230, 1235, 1240, 1245, 1250, 1255, 1260, 1265, 1270, 1275, 1280, 1285, 1290, 1295, 1300, 1305, 1310, 1315, 1320, 1325, 1330, 1335, 1340, 1345, 1350, 1355, 1360, 1365, 1370, 1375, 1380, 1385, 1390, 1395, 1400, 1405, 1410, 1415, 1420, 1425, 1430, 1435, 1440, 1445, 1450, 1455, 1460, 1465, 1470, 1475, 1480, 1485, 1490, 1495, 1500, 1505, 1510, 1515, 1520, 1525, 1530, 1535, 1540, 1545, 1550, 1555, 1560, 1565, 1570, 1575, 1580, 1585, 1590, 1595, 1600, 1605, 1610, 1615, 1620, 1625, 1630, 1635, 1640, 1645, 1650, 1655, 1660, 1665, 1670, 1675, 1680, 1685, 1690, 1695]

Above, are all the numbers that can be divided by 5 without residual. Let's now choose a smaller set of numbers. Let's choose those that can both be divided by 5 and by 7 without residual.


In [20]:
our_list=[]
for number in range(7,1700):
    if number%5==0 and number%7==0:
        our_list.append(number)

In [21]:
print our_list


[35, 70, 105, 140, 175, 210, 245, 280, 315, 350, 385, 420, 455, 490, 525, 560, 595, 630, 665, 700, 735, 770, 805, 840, 875, 910, 945, 980, 1015, 1050, 1085, 1120, 1155, 1190, 1225, 1260, 1295, 1330, 1365, 1400, 1435, 1470, 1505, 1540, 1575, 1610, 1645, 1680]

As you nticed above, in order to add one more required condition inside if statement, one needs to use just and in between. Similarly, or can be used to checked whether at least one of the conditions is satisfied or not.


In [22]:
our_list=[]
for number in range(7,1700):
    if number%5==0 or number%7==0:
        our_list.append(number)

Maximum function

Let's define a function that will take two numbers as an argument and return the maximum of them


In [23]:
def max_of_2(x,y):
    if x>y:
        return x
    else:
        return y

In [24]:
print max_of_2(15,12)


15

Let's now define a max_of_3 function. As we already have max_of_2, we just need to nest them inside one another as shown below:


In [25]:
def max_of_3(x,y,z):
    return max_of_2(z,max_of_2(x,y))

In [26]:
max_of_3(10,15,33)


Out[26]:
33

Text reverser

Let's degine a function that will reverse a text. As we want to save the reversed text as a string, let's first create an empty string. Then, each letter, one by one, will be added to our empty strin.


In [27]:
def reverser(text):
    r_text = ""
    i = len(text)
    while i>0:
        r_text = r_text + text[i-1]
        i = i-1
    return r_text

In [28]:
print reverser("Globalization")


noitazilabolG

Finally, yet importantly, let read the Zen of Python (python's philosophy).


In [29]:
import this


The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!