Python 1

Section 4

We saw in the last section how to use libraries like math, os, datetime, random and others. In addition we talked about conditions ('if', 'elif', 'else'), comparison operators (==, >, <, >=, <=, !=) and logical operators ('not', 'and', 'or' - NAO). Now let's talk about the awesome LOOPS!

Loops

Loops have a specific function in Python, just like in many other programming languages. Loops, as the name already says, keep requesting a determined action until a condition is fulfilled. In Python, we have two types of loops, one is the "while" function and the other is the "for" function. Let's see them now in details.

while

The "while" function keeps running a loop until a particular condition is not satisfied. Let's see a practical example.


In [1]:
count = 0 # Who is this guy?
while count<=10:
    print (count)
    count += 1 # there is another way to write this
print("That's over!")


0
1
2
3
4
5
6
7
8
9
10
That's over!

In [2]:
# We can use the while function to loop through lists, tuples and even strings.
################################################################################

# with lists
print ('Lists')
a = [0,1,2,3,5,6,6,7]
count = 0     # This guy is here again!!
while count < len(a):
    print(a[count])
    count += 1

################################################################################

# with tuples
print('\nTuples')
a = (52,14,15,1,45,5,4,7,8)
count = 0     # and again!!
while count < len(a):
    print(a[count])
    count += 1

################################################################################

# with string
print('\nStrings')
a = 'Python'
count = 0     # AND AGAIN!! WTF??
while count < len(a):
    print(a[count])
    count += 1


Lists
0
1
2
3
5
6
6
7

Tuples
52
14
15
1
45
5
4
7
8

Strings
P
y
t
h
o
n

In [3]:
# Task 01: write a code that loops through the list of numbers called 'data' and devide 
# them in two extra lists, one with odd numbers and another with even numbers.

# That is OK if you don't get this part. We will talk about it latter.
import random
data = [random.randint(0,100) for i in range(0,20)]
count = 0
even = []
odd = []
while count < len(data):
    if data[count]%2==0:
        even.append(data[count])
    else:
        odd.append(data[count])
    count+=1
print('These are the original numbers:\n', data)
print('These are the even numbers:\n', even)
print('These are the odd numbers:\n', odd)


These are the original numbers:
 [49, 88, 77, 42, 83, 61, 2, 66, 4, 25, 6, 34, 23, 66, 18, 86, 42, 78, 86, 62]
These are the even numbers:
 [88, 42, 2, 66, 4, 6, 34, 66, 18, 86, 42, 78, 86, 62]
These are the odd numbers:
 [49, 77, 83, 61, 25, 23]

In [4]:
# Task 02: write a code that takes a sentence and separate each letter into two lists (vowels and consonants).
sentence = "The problem is not the problem - the problem is your attitude about the problem.".lower()
count = 0
vowels = []
consonantes = []
while count < len(sentence):
    if sentence[count] in 'aeiou':
        vowels.append(sentence[count])
    elif sentence[count] in '-. ':
        pass
    else:
        consonantes.append(sentence[count])
    count += 1
print('These are the vowels:\n', vowels)
print('These are the consonantes:\n',consonantes)


These are the vowels:
 ['e', 'o', 'e', 'i', 'o', 'e', 'o', 'e', 'e', 'o', 'e', 'i', 'o', 'u', 'a', 'i', 'u', 'e', 'a', 'o', 'u', 'e', 'o', 'e']
These are the consonantes:
 ['t', 'h', 'p', 'r', 'b', 'l', 'm', 's', 'n', 't', 't', 'h', 'p', 'r', 'b', 'l', 'm', 't', 'h', 'p', 'r', 'b', 'l', 'm', 's', 'y', 'r', 't', 't', 't', 'd', 'b', 't', 't', 'h', 'p', 'r', 'b', 'l', 'm']

In [13]:
""" In the last section, when we talked about conditions, we did Task 01 and Task 02 (see below):

    Task 01: ask the user for a number a use a if statement to see if this number is even or uneven
    Task 02: create a game that asks the user for a number. Then, tell the user if he/she won the game.
    
The way we wrote the code to solve these tasks was not effective, since the user needs to go inside 
the code and change the values. However, with a while loop you can keep asking for numbers and make
things far more intersting. Let's see how it works"""

# Task 01: ask the user for a number and use a if statement to see if this number is even or uneven.
# But now add a while loop and keep asking for a number until the user doesn't want to play anymore.

data = input("Please enter a number. If you don't want to play anymore type 'exit': ")
even = []
odd = []
while data != 'exit':
    if int(data)%2==0:
        even.append(int(data))
    else:
        odd.append(int(data))
    data = input("Please enter a number. If you don't want to play anymore type 'exit': ")

print('These are the even numbers:\n', even)
print('These are the odd numbers:\n', odd)


Please enter a number. If you don't want to play anymore type 'exit': 22
Please enter a number. If you don't want to play anymore type 'exit': 14
Please enter a number. If you don't want to play anymore type 'exit': 15
Please enter a number. If you don't want to play anymore type 'exit': 16
Please enter a number. If you don't want to play anymore type 'exit': 17
Please enter a number. If you don't want to play anymore type 'exit': 18
Please enter a number. If you don't want to play anymore type 'exit': 19
Please enter a number. If you don't want to play anymore type 'exit': 20
Please enter a number. If you don't want to play anymore type 'exit': 22
Please enter a number. If you don't want to play anymore type 'exit': 24
Please enter a number. If you don't want to play anymore type 'exit': 25
Please enter a number. If you don't want to play anymore type 'exit': 30
Please enter a number. If you don't want to play anymore type 'exit': 35
Please enter a number. If you don't want to play anymore type 'exit': 51
Please enter a number. If you don't want to play anymore type 'exit': 77
Please enter a number. If you don't want to play anymore type 'exit': exit
These are the even numbers:
 [22, 14, 16, 18, 20, 22, 24, 30]
These are the odd numbers:
 [15, 17, 19, 25, 35, 51, 77]

In [14]:
# Task 02: write a code that takes a sentence and separate each letter into two lists (vowels and consonants).
sentence = "The problem is not the problem - the problem is your attitude about the problem.".lower()
count = 0
vowels = []
consonantes = []
while count < len(sentence):
    if sentence[count] in 'aeiou':
        vowels.append(sentence[count])
    elif sentence[count] in '-. ':
        pass
    else:
        consonantes.append(sentence[count])
    count += 1
print('These are the vowels:\n', vowels)
print('These are the consonantes:\n',consonantes)


These are the vowels:
 ['e', 'o', 'e', 'i', 'o', 'e', 'o', 'e', 'e', 'o', 'e', 'i', 'o', 'u', 'a', 'i', 'u', 'e', 'a', 'o', 'u', 'e', 'o', 'e']
These are the consonantes:
 ['t', 'h', 'p', 'r', 'b', 'l', 'm', 's', 'n', 't', 't', 'h', 'p', 'r', 'b', 'l', 'm', 't', 'h', 'p', 'r', 'b', 'l', 'm', 's', 'y', 'r', 't', 't', 't', 'd', 'b', 't', 't', 'h', 'p', 'r', 'b', 'l', 'm']

In [16]:
# Task 03: Now try to implement task 2 again but now use the while function and 
# keep looping until the user get the right number. For each loop, tell the user 
# if he is getting close or not.

import random
data = int(input("Gress a number betweeon 0 and 100. If you don't want to play anymore type 'exit': "))
number = random.randint(0,100)
while data != 'exit':
    if int(data) > number:
        print('{} is too high!'.format(int(data)))
    elif int(data) < number:
        print('{} is too low!'.format(int(data)))
    else:
        print('Well done! You won!')
        break
    data = int(input("Gress a number betweeon 0 and 100. If you don't want to play anymore type 'exit': "))
print('Game Over!')


Gress a number betweeon 0 and 100. If you don't want to play anymore type 'exit': 50
50 is too high!
Gress a number betweeon 0 and 100. If you don't want to play anymore type 'exit': 30
30 is too low!
Gress a number betweeon 0 and 100. If you don't want to play anymore type 'exit': 40
40 is too low!
Gress a number betweeon 0 and 100. If you don't want to play anymore type 'exit': 45
45 is too high!
Gress a number betweeon 0 and 100. If you don't want to play anymore type 'exit': 43
43 is too low!
Gress a number betweeon 0 and 100. If you don't want to play anymore type 'exit': 44
Well done! You won!
Game Over!

for

A 'for' loop, different from the 'while', do not need a condition to execute a code. Loops of the type 'for' need an interactible variable to work such as lists, tuples, strings and dictionaries. Those are variables that contain more then one element. 'For' loops do not work in integer and floats for example, since they are single element variables.


In [3]:
# Let's have an example on how to use the 'for' loop comparing 
# with the same code done with the while function.

# while function
a = [0, 1, 2, 3, 5, 6, 6, 7]
count = 0     # This guy is here again!!
while count < len(a):
    print(a[count])
    count += 1
    
print('\n')

# for function
a = [0, 1, 2, 3, 5, 6, 6, 7]
for number in a:   # the word 'number' does not mean anything. Could have been anything else.
    print(number)


0
1
2
3
5
6
6
7


0
1
2
3
5
6
6
7

In [4]:
# Let's try now using strings
string = 'Python is awesome!'
for c in string:
    print(c)


P
y
t
h
o
n
 
i
s
 
a
w
e
s
o
m
e
!

In [5]:
# A common combination is to put for and the function 'range' together.
# Let's see an example
for i in range(0,20):  # what if I just want even numbers?
    print(i)


0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

In [6]:
# Task 03: rewrite the code that loops through the list of numbers called 'data' 
# and devide them in two extra lists, one with odd numbers and another with even 
# numbers.

# That is OK if you don't get this part. We will talk about it latter.
import random
data = [random.randint(0,100) for i in range(0,20)]
even = []
odd = []
for i in data:
    if i%2==0:
        even.append(i)
    else:
        odd.append(i)
print('These are the even numbers:\n', even)
print('These are the odd numbers:\n', odd)


These are the even numbers:
 [58, 54, 94, 100, 52, 56, 66, 84, 16]
These are the odd numbers:
 [75, 13, 47, 45, 1, 23, 45, 57, 25, 75, 23]

In [7]:
# Task 04: write a program which will find all such numbers which are divisible 
#by 7 but are not a multiple of 5, between 2000 and 3200 (both included). The 
#numbers obtained should be printed in a comma-separated sequence on a single line.

l=[]
for i in range(2000, 3201):
    if (i%7==0) and (i%5!=0):
        l.append(str(i))

#print(','.join(l))
for i in l:
    print(i,',',)


2002 ,
2009 ,
2016 ,
2023 ,
2037 ,
2044 ,
2051 ,
2058 ,
2072 ,
2079 ,
2086 ,
2093 ,
2107 ,
2114 ,
2121 ,
2128 ,
2142 ,
2149 ,
2156 ,
2163 ,
2177 ,
2184 ,
2191 ,
2198 ,
2212 ,
2219 ,
2226 ,
2233 ,
2247 ,
2254 ,
2261 ,
2268 ,
2282 ,
2289 ,
2296 ,
2303 ,
2317 ,
2324 ,
2331 ,
2338 ,
2352 ,
2359 ,
2366 ,
2373 ,
2387 ,
2394 ,
2401 ,
2408 ,
2422 ,
2429 ,
2436 ,
2443 ,
2457 ,
2464 ,
2471 ,
2478 ,
2492 ,
2499 ,
2506 ,
2513 ,
2527 ,
2534 ,
2541 ,
2548 ,
2562 ,
2569 ,
2576 ,
2583 ,
2597 ,
2604 ,
2611 ,
2618 ,
2632 ,
2639 ,
2646 ,
2653 ,
2667 ,
2674 ,
2681 ,
2688 ,
2702 ,
2709 ,
2716 ,
2723 ,
2737 ,
2744 ,
2751 ,
2758 ,
2772 ,
2779 ,
2786 ,
2793 ,
2807 ,
2814 ,
2821 ,
2828 ,
2842 ,
2849 ,
2856 ,
2863 ,
2877 ,
2884 ,
2891 ,
2898 ,
2912 ,
2919 ,
2926 ,
2933 ,
2947 ,
2954 ,
2961 ,
2968 ,
2982 ,
2989 ,
2996 ,
3003 ,
3017 ,
3024 ,
3031 ,
3038 ,
3052 ,
3059 ,
3066 ,
3073 ,
3087 ,
3094 ,
3101 ,
3108 ,
3122 ,
3129 ,
3136 ,
3143 ,
3157 ,
3164 ,
3171 ,
3178 ,
3192 ,
3199 ,

In [10]:
# Task 05:Write a program that calculates and prints the value according to the 
# given formula:

# Q = Square root of [(2 * C * D)/H]

# Following are the fixed values of C and H:
# C is 50. H is 30.
# D is the variable whose values should be input to your program in a 
# comma-separated sequence.

# Example
# Let us assume the following comma separated input sequence is given to the 
# program:
# 100,150,180
# The output of the program should be:
# 18,22,24

# Hints:
# If the output received is in decimal form, it should be rounded off to its 
# nearest value (for example, if the output received is 26.0, it should be 
# printed as 26). In case of input data being supplied to the question, it 
# should be assumed to be a console input. 

import math
c=50
h=30
value = []
items=[x for x in input().split(',')]
print(items)
for d in items:
    value.append(str(int(round(math.sqrt(2*c*float(d)/h)))))

print(','.join(value))


35,22,14
['35', '22', '14']
11,9,7

List comprehension

List comprehension is a powerful and efficient technique to work with for loops associated with lists or tuples. You already saw at some point the following line of code:

data = [random.randint(0,100) for i in range(0,20)]

You were told not to worry about this. The 'data'is created but our new friend list comprehension. This is a method implemented in Python 2 to allow an option to write the code like mathematicians would. A fundamental way of writing the code would be:

variable = [x for x in range(0,10)]


In [11]:
# Let's try this
variable = [x for x in range(0,10)]
print(variable)


[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

In [12]:
# You can also use with strings
variable = [s for s in 'Python']
print(variable)


['P', 'y', 't', 'h', 'o', 'n']

In [13]:
# Let's take a look at the code we saw earlier.
print([random.randint(0,100) for i in range(0,20)])


[83, 78, 65, 35, 99, 74, 33, 24, 85, 7, 19, 58, 68, 3, 50, 31, 14, 76, 45, 93]

In [14]:
# Another way to to that.
data = []
k = []
for i in range(0,20):
    data.append(random.randint(0,100))
for j in data:
    if j > 50:
        k.append(j)
print(k)


[99, 61, 56, 76, 80, 57, 87, 52, 63, 99]

In [15]:
# You can also use list comprehension with conditions
data = [t for t in data if t > 50]
print(data)


[99, 61, 56, 76, 80, 57, 87, 52, 63, 99]

In [16]:
################################################################################
# Task 06: Let's use the example of the odd and even numbers usign list comprehension. 
# Your code can't have more then 3 lines.
data = [random.randint(0,100) for i in range(0,20)]
print([number for number in data if number%2==0])
print([number for number in data if number%2!=0])


[58, 70, 42, 16, 74, 82, 90, 50, 92]
[27, 53, 77, 19, 41, 45, 63, 11, 81, 91, 57]

In the next episode of Python 1...

You will dive into:

  • Def function: create your own functions in Python
  • Class function: learn object oriented programming by creating your classes

To be continued...