Introduction to programming using Python

Session 2

Matthieu Choplin

http://mattchoplin.com/

### Objectives of Session 2 * Remainder of Session 1: Quiz + exercices * Controlling the flow of our programs * Conditional statements * The boolean type * While loop
### Remainder of Session 1: Quiz (1) * Which of the following are operators, and which are values? - * - 'hello' - -88.8 - - - / - + - 5
### Remainder of Session 1: Quiz (2) * Which of the following is a variable, and which is a string? - spam - 'spam'
### Remainder of Session 1: Quiz (3) * Name three data types.
### Remainder of Session 1: Quiz (4) * What is an expression made up of? What do all expressions do?
### Remainder of Session 1: Quiz (5) * What does the variable bacon contain after the following code runs? ``` bacon = 20 bacon + 1 ```
### Remainder of Session 1: Quiz (6) * Name 3 builtin functions and explain what they do
### Remainder of Session 1: Quiz (7) * How do you call a function?
### Remainder of Session 1: Quiz (8) * What function can you use to take a value from a user? For example, how can you ask the age of a user and store it into a variable?
### Remainder of Session 1: Quiz (9) * What function can you use to convert the age entered by the user and compute the years when he was born?
### Remainder of Session 1: Quiz (10) * Name three types of errors that we can get in a program

Exercise 1: converting a currency (static version)

Write a program that converts pounds into euros.

• The values can be hard coded for now (it means that the program will not be dynamic)
• Use variables
• Use print

Show solution

Hide solution

``````rate = 0.8
pounds = 100
euros = pound * rate
print(pounds, "pounds is", euros, "euros")``````

Exercise 2: converting a currency (dynamic version)

• Write a program that ask the user what amount is to be converted in euros, convert it and display the result.
• Hint: we are going to need the function input and the function float

Show solution

Hide solution

``````rate = 0.8
pounds = float(
input("Enter the amount you would like to convert and press ENTER "))
euros = pound * rate
print(pounds, "pounds is", euros, "euros")``````

Exercise 3: computing the age of the user

• Ask a user to enter the year he was born, compute his age and tell him how old he will turn this current year.

Show solution

Hide solution

``````today_year = 2017
year_born = float(
input("Enter the year when you were born and press ENTER: "))
age = today_year - year_born
print("This year you are turning", age)``````

Exercise 4: fixing bugs

• Explain what this program is supposed to do and what the bug is here:
``````vat_rate = 20/100
car_price = 34500
car_price * (1 - vat_rate)
print("The gross value of the car is", car_price, "pounds")
``````

Controlling the flow of our programs

We can represent the flow of execution with a flow chart

Structure of a simple if statement

Pseudo code:

``````if condition:
# statement (mind the indentation)``````

Example, representation of the flow chart example in python code:

``````if name=='Alice':
print('Hi Alice')``````

The two-way if statement

Pseudo code:

``````if condition:
# statement (mind the indentation)
else:
# statement executed when the condition is False
``````

Example, representation of the flow chart example in python code with an else statement:

``````if name=='Alice':
print('Hi Alice')
else:
print('Hi')``````

Multiple Alternative if Statements

The naive way

``````if condition:
# statement (mind the indentation)
else:
if condition:
# statement executed when
# the previous condition is False
else:
# statement executed when none of
# the previous condition is verified
``````

Multiple Alternative if Statements

The better way, the pythonc way

``````if condition:
# statement (mind the indentation)
elif condition:
# statement executed when
# the previous condition is False
elif condition:
# statement executed when none of
# the previous condition is verified
else:
# executed when all conditions are False``````

Value of the condition

The program will execute the statement only if the condition is verified. Only if the condition is True.

The condition is actually a boolean.

The Boolean Type

• It has only 2 possible values: True or False. Notice that they are both capitalized, which is important because Python is case sensitive
• It is often obtained as a result of a comparison expression.

The Comparison Operators

Operator Meaning
< less than
<= less than or equal
> greater than
>= greater than or equal
== equal to
!= not equal to

Examples

``````'hello' == 'hello'
'hello' == 'Hello'
'dog' != 'cat'
True == True
True != False
42 == 42.0
42 == '42'``````

Difference between '==' and '='

• The sign = is the sign of assignment, it is used for assigning a value to a variable
• The sign == is the sign of comparison, it compares 2 values and return a boolean (True or False)

• If the word entered by the user matches the password, display "Access Granted", else, "Forbidden"

Show solution

Hide solution

``````PASSWORD = 'super_password123'
print("Access Granted")
else:
print("Forbidden")
``````

Truth tables

Show every possible result of a Boolean operator.

The and Operatorâ€™s Truth Table

Expression Evaluates to...
True and True True
True and False False
False and True False
False and False False

The or Operatorâ€™s Truth Table

Expression Evaluates to...
True or True True
True or False True
False or True True
False or False False

The not Operator

It operates on only one Boolean value (or expression). The not operator simply evaluates to the opposite Boolean value.

``````not True
not not True
not 1 != 2
``````

Show solution

Hide solution

``````PASSWORD = 'super_password123'
print("Access Granted")
else:
print("Forbidden")
``````

Exercise: check number divisor

Write a program that prompts the user to enter an integer. If the number is a multiple of 5, print HiFive. If the number is divisible by 2, print HiEven.

• Use input() take the user input
• Use int() to convert the value return by input into an integer
• Use % to see if a number x is divisible by an other number y, if x%y returns 0, then x is divisible by y
• Use print()

Solution: control flow

Show solution

Hide solution

``````number_x = int(input("Enter an integer: "))
if number_x % 5 == 0:
print("HiFive")
if number_x % 2 == 0:
print("HiEven")
``````

Write a program that is going to give the grade of a student according to the score obtained.

• Display 'A' if the score is greater than 90
• Display 'B' if the score is between 80 and 90
• Display 'C' if the score is between 70 and 80
• Display 'D' if the score is between 60 and 70
• Display 'F' if the score is lower than 60

Show solution

Hide solution

``````score = int(input("Enter the score: "))
if score >= 90.0:
elif score >= 80.0:
elif score >= 70.0:
elif score >= 60.0:
else:
``````

Exercise: determining a leap year

This program first prompts the user to enter a year as an int value and checks if it is a leap year.

A year is a leap year if it is divisible by 4 but not by 100, or it is divisible by 400.

• Use input() to take the user input (the year, i.e. 2016) and convert it with int()
• Use % to see if a number x is divisible by an other number y, if x%y returns 0, then x is divisible by y
• Check if the year is divisible by 4 AND not divisible by 100
• OR check if the year is divisible by 400.
• Use print()

Solution: determining a leap year

Complete solution

Hide solution

``````
year = input("Enter a year : ")
year = int(year)
leap_year = False # boolean value saying if
# the year is a leap_year or not
if year % 400 == 0:
leap_year = True
elif year % 4 == 0:
if year % 100 != 0:
leap_year = True
else:
leap_year = False
if leap_year:
print("The year entered is a leap year.")
else:
print("The year entered is not a leap year.")
``````

Solution optimized: determining a leap year

Condition to use

Hide hint

``(year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)``

Complete solution

Hide solution

``````year = int(input("Enter a year: "))
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("The year is a leap year")
else:
print("The year is not a leap year")
``````

Exercise: Chinese Zodiac sign

Now let us write a program to find out the Chinese Zodiac sign for a given year. The Chinese Zodiac sign is based on a 12-year cycle, each year being represented by an animal: rat, ox, tiger, rabbit, dragon, snake, horse, sheep, monkey, rooster, dog, and pig, in this cycle

Hint 1

Hide hint 1

Use the modulo (%).

Hint 2

Hide hint 2

2016 is the year of the monkey and 2016 % 12 equals 0

Exercise: Chinese Zodiac sign

Year Zodiac sign
0 monkey
1 rooster
2 dog
3 pig
4 rat
5 ox
6 tiger
7 rabbit
8 dragon
9 snake
10 horse
11 sheep

Complete solution

Hide solution

``````year = eval(input("Enter a year: "))
zodiacYear = year % 12
if zodiacYear == 0:
print("monkey")
elif zodiacYear == 1:
print("rooster")
elif zodiacYear == 2:
print("dog")
elif zodiacYear == 3:
print("pig")
elif zodiacYear == 4:
print("rat")
elif zodiacYear == 5:
print("ox")
elif zodiacYear == 6:
print("tiger")
elif zodiacYear == 7:
print("rabbit")
elif zodiacYear == 8:
print("dragon")
elif zodiacYear == 9:
print("snake")
elif zodiacYear == 10:
print("horse")
else:
print("sheep")``````