L4- Python Conditionals
L4- Python Conditionals
1
Sequential composition
• The examples of algorithms we have seen so far have been simple
instructional sequences.
• It is the easiest structure of all: we tell the processor that it must
consecutively execute a list of actions.
• To build a sequence we write one action per line.
Action 1 n1 = float(input())
<action 1>
n2 = float(input())
Action 2 <action 2> n3 = float(input())
… … mean_nums = (n1+n2+n3)/3
<action n> print(mean_nums)
Action n
Control structures
Conditional Iterative
Syntax
Flowchart
if (<condition>):
<action 1>
<action 2>
Condition? …
<action N>
Yes No
Actions
Important:
Indicate start actions with :
Indentation
4
Exercise
Ask the user to introduce an integer value. If the value is inside the interval [0,10],
display the message:
Otherwise display:
5
Solution
x = input()
x = int(x)
print(message)
6
Exercise
Write a program that reads the time of a clock and writes the time increased in
a second.
The input and output must follow the following format: 05:23:52
that is, hours, minutes, and seconds with two digits and separated by a colon.
First version:
• Read the time in the given format
• Display the read time in the given format
Second version:
• Increase the time in 1 second, controlling that sometimes we also need
to increase minutes and hours.
7
Remember what a string is
• A string is a sequence of characters.
• How is it stored?
characters
0 8 : 3 4 : 1 4
indices 0 1 2 3 4 5 6 7 8
• Operator [n:m] returns the part of the string from the n-th character
(included) to the m-th (not included):
8
Solution (I)
# Input
time = input("Enter the time with format hh:mm:ss = ")
hh = int(time[0:2])
mm = int(time[3:5])
ss = int(time[6:8])
#Process
ss+=1
#Output
new_time = str(hh)+":"+str(mm)+":"+str(ss)
print(new_time)
9
Solution (II)
# Input
time = input("Enter the time with format hh:mm:ss = ")
hh = int(time[0:2])
mm = int(time[3:5])
ss = int(time[6:8])
#Process
ss+=1
#Output
new_time =""
print(new_time)
10
Solution (III)
# Input
time = input("Enter the time with format hh:mm:ss = ")
hh = int(time[0:2])
mm = int(time[3:5])
ss = int(time[6:8])
#Process
ss+=1
if (ss == 60):
ss = 0
mm += 1
if (mm == 60):
mm =0
hh += 1
if (hh == 24):
hh = 0
#Output
new_time =""
print(new_time) 11
Exercise: Area and Perimeter of a circle
• The program must ask the user to enter the radius of a circle and compute
the area and the perimeter. After that, the program will show the result on
screen.
• The program must check that the radius is a positive value and do the
operations to compute the area and the perimeter only if the user has
entered a positive radius.
12
Solution
Example: Calculate the area and perimeter of a circle
# Program to compute area and perimeter of a circle
#Input
radius = float(input("Enter the radius of the circle: "))
#Process
if (radius > 0): # Check if radius is positive
area = PI * radius ** 2
perimeter = 2 * PI * radius
#Output
print("The area of the circle is: ", area)
print("The perimeter of the circumference is: ", perimeter)
else:
#Output
print("ERROR: The radius must be a positive value.")
13
Conditional structures: double alternative
Flowchart
Syntax
if (<condition>):
14
Exercise: Positive or negative?
15
Solution
"""
Program that displays the message:
”Positive” if a positive number (including 0) has
been read from keyboard
”Negative” otherwise.
"""
#Input
num = int(input("Enter an integer: "))
#Process
if (num >= 0):
#Output
print("Positive")
else:
#Output
print("Negative")
16
Exercise: Vowel or consonant?
Write a program that asks the user to enter a letter and then tells if it is a vowel
or a consonant.
17
Solution
"""
Program that displays the message:
”Vowel” if user enters a,e,i,o,u
”Consonant” otherwise
"""
#Input
letter = input("Enter a character: ")
#Process
if (letter=="a" or
letter=="e" or
letter=="i" or
letter=="o" or
letter=="u"):
#Output
print("Vowel")
else:
#Output
print("Consonant")
18
Solution
"""
Program that displays the message:
”Vowel” if user enters a,e,i,o,u
”Consonant” otherwise
"""
#Input
letter = input("Enter a character: ")
#Process
if letter in "aeiouAEIOU":
#Output
print("Vowel")
else:
#Output
print("Consonant")
19
Double alternative particular case: nested if-else
The structures that we have explained are like blocks that can be
used inside others, meanwhile we maintain their structure.
Flowchart Syntax
if (<condition>):
<actions YES>
else:
if (<condition>):
Condition?
No Yes <actions YES>
else:
<actions NO>
20
Exercise: Positive, negative or zero
Write a program that asks for an integer and displays if the number is
"Positive", "Negative" or "Zero".
21
Solution
"""
Program that displays the message:
”Positive” if the user enters a number > 0
”Negative” if the number is < 0
"Zero" otherwise
"""
#Input
num = int(input("Enter an integer: "))
#Process
if (num > 0):
#Output
print("Positive")
else:
if (num < 0):
#Output
print("Negative")
else:
#Output
print("Zero")
22
Exercise: Salary calculator
The program must calculate and show the final salary. This is calculated as the
base salary plus a percentage of the base salary based on the years in the
company of service.
23
Solution
"""
Program to compute the final salary depending on the service years
Less than 3 years: increase 1%
Between 3 and 5 years: increase 2%
More than 5 years: increase 3,5%
"""
#Input
base_salary = float(input("Enter the base salary: "))
service = int(input("Enter the years of service: "))
#Process
if (service < 3):
final_salary = base_salary * 1.01
else:
if (service < 5):
final_salary = base_salary * 1.02
else:
final_salary = base_salary * 1.035
#Output
print("The final salary is: ", final_salary)
24
Exercise: Final grades
The program must ask the user to enter a numerical mark that should be a real
number between 0 and 10.
After that, the program must show the final grade according to the following
correspondence:
25
Solution
"""
Program that computers the final grade from the numerical mark
"""
#Input
mark = float(input("Enter the numerical mark: "))
#Process
if(0<=mark<=10):
if (mark < 5):
grade = "Fail"
else:
if (mark < 7):
grade = "C"
else:
if (mark < 9):
grade = "B"
else:
if (mark < 10):
grade = "A"
else:
grade = "A with Honors"
#Output
print("The final grade is: ", grade)
else:
print("Error, the final grade must be in [0,10]")
26
Conditional structures: nested alternative
Flowchart Syntax
if (<condition>):
<actions YES>
elif (<condition>):
<actions YES>
Condition?
No Yes else:
<actions NO>
Actions Yes
27
Exercise: Tasks Menu
Write a program that allows us to simulate a menu of three options:
Menu
1 - Task 1
2 - Task 2
3 – Task 3
Select a task:
Once the user has entered one of the options, the program will display a
message indicating that the corresponding task is being done. These
messages will have format: "Doing Task X", where X will be an integer
corresponding to the selected option (1, 2 or 3).
If the user selects a task different to 1, 2 and 3, the program will display the
following error message: "ERROR: Wrong choice".
28
Solution
"""
This code implements a menu
"""
if (selection == 1):
print("Doing Task 1")
elif (selection == 2):
print("Doing Task 2")
elif (selection == 3):
print("Doing Task 3")
else:
print("ERROR: Wrong choice")
29
Exercise
First, the program will have to check that it is a letter ["a" ... "z"] or ["A" ... "Z"].
In any other case, the program will show a message warning that the character
is not allowed.
Output:
• "Lowercase vowel" if you enter a,e,i,o,u
• "Uppercase vowel" if you enter A,E,I,O,U
• "Lowercase consonant" if you enter b,c,d,f, ... x,y,z
• "Uppercase consonant" if you enter B,C,D,F, ... X,Y,Z
• "Character not allowed" in any other case
30
The ASCII Code (reminder)
The ASCII code is a Latin-based character code. It was created in 1963 by the
American Committee on Standards (source: Wikipedia).
The most interesting values for us are the letters "a" and "A", and the digit "0".
These characters have codes 97, 65 and 48 respectively.
The interest in choosing these comes from the fact that the entire lowercase
alphabet comes after letter "a", so "b" has code 98, "c" has code 99, and so on
until "z", which has code 122.
The same happens for capital letters: "B" is 66, "C" on 67, and so on until "Z",
which is 90.
31
The ASCII Code (reminder)
On the keyboard:
ALT + Num ® character from table
Example: ALT + 169 ® ©
Python
print(chr(65)) ® ‘A’
print(ord(“A”)) ® 65
32
Conditional structures: multiple alternative
"""
Program that displays the message:
"Lowercase vowel" if you enter a,e,i,o,u
"Uppercase vowel" if you enter A,E,I,O,U
"Lowercase consonant" if you enter b,c,d,f, ... x,y,z
"Uppercase consonant" if you enter B,C,D,F, ... X,Y,Z
"Character not allowed" in any other case
"""
#Input
letter = input("Enter a character: ")
numerical_code = (ord(letter))
#Proces
pre = ""
post = ""
if ((numerical_code >= ord("A") and numerical_code <= ord("Z"))):
pre = "Uppercase"
if letter in "AEIOU":
post = "vowel"
else:
post = "consonant"
elif ((numerical_code >= ord("a") and numerical_code <= ord("z"))):
pre = "Lowercase"
if letter in "aeiou":
post = "vowel"
else:
post = "consonant"
else:
pre = "Character not allowed"
#Output 33
print(pre,post)