Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
BASIC FORM
<expr> is an expression evaluated in Boolean context
if <expr>:
<statement> is a valid Python statement, which must be indented.
<statement(s)>
<following_statement(s)>
The colon ( : ) at the end of the if statement is required.
a=3
b=2
if a > b:print("a is greater than b")
BASIC FORM
if <expr>:
If <expr> is true, the first suite is executed, and the second is skipped.
<statement(s)_1>
else:
If <expr> is false, the first suite is skipped and the second is executed.
<statement(s)_2>
if age <21:
s='minor' age = 12
else: s = 'minor' if age < 21 else 'adult'
s='adult' print(s)
print(s)
Output:
minor
27
Output:
4
28
COMPOUND IF STATEMENTS
It is possible to use two conditions at the same time using an and/or
Output:
what is you name?
Alton
The name you entered is Alton
29
COMPARISON OPERATORS
Comparison operators in Python
operator function
< less than
<= less than or equal to
> greater than
>= greater than or equal to
== equal
!= not equal
if x < y:
STATEMENTS_A
elif x > y:
STATEMENTS_B
else:
STATEMENTS_C
31
ELIF – EXAMPLE 1
x=2
y=3
if x<y:
print("The maximum value is", y) Output:
elif x>y: The maximum value is 3
print("The maximum value is", x)
else:
print(y,"is equal to", x)
32
ELIF – EXAMPLE 2
x=2
if 0<x<10:
print(x, "is a positive digit")
Output:
elif x<-1:
2 is a positive digit
print(x, "is a negative digit")
else:
print(x, " is null")
33
NESTED CONDITIONALS
Sometimes a program might need to test a condition and a sub condition
based on the answer the first decision.
num1=float(input("Pick a number:"))
num2=float(input("Pick another number:"))
if num1<=num2:
if num1 == num2:
print("equal") Output:
Pick a number:12
else:
Pick another number:20
print("not equal") not equal
elif num1>num2:
print("greater")
else:
print("less")
34
EXERCISE
Write a program that begins by reading a letter grade from the user. Then your
program should compute and display the equivalent number of grade points.
Ensure that your program generates an appropriate error message if the user
enters an invalid letter grade. A 4
A- 3.7
B+ 3.3
B 3
B- 2.7
C+ 2.3
C 2
C- 1.7
D+ 1.3
D 1
F 0
35
EXERCISE - SOLUTION
x=input('Enter a letter grade')
if x in ['A','A+','A-','B+','B-','C','C+','C-','D+','D-','F']:
if x=='A':
g=4
elif x=='A-':
g=3.7
elif x=='B+':
g=3.3
elif x=='B':
g = 3
elif x=='B-':
g = 2.7
elif x=='C+':
g = 2.3
elif x=='C':
g = 2
elif x=='C-':
g = 1.7
elif x=='D+':
g = 1.3
elif x=='D':
g = 1
else:
g = 0
print(g)
else:
print("Enter a correct letter")