Python Chapter4
Python Chapter4
Selections
Introduction
A program can decide which statements to execute based on
a condition.
If you enter a negative value for radius the program displays
an invalid result. If the radius is negative, the program cannot
compute the area. How can you deal with this situation?
if radius<0:
print("Incorrect Input")
else:
area = radius * radius * math.pi
# Display results
print("The area is ", area)
What is 1 + 4? 5
1 + 4 = 5 is True random() function to generate a
>>>
What is 7 + 9? 15
random float r such that 0 <= r < 1.0
7 + 9 = 15 is False
if Statements
A one-way if statement executes the statements if the condition
is true.
Python has several types of selection statements:
one-way if statements,
two-way if else statements,
nested if statements,
multi-way if-elif-else statements and conditional expressions.
The syntax for a one-way if statement is:
if boolean-expression:
statement(s)
Enter an integer: 8
HiEven
>>>
Enter an integer: 10
HiFive
HiEven
Two-Way if-else Statements
A two-way if-else statement decides which statements to execute
based on whether the condition is true or false.
Here is the syntax for a two-way if-else statement:
if boolean-expression:
statement(s)-for-the-true-case
else:
statement(s)-for-the-false-case
Two-Way if-else Statements
develop a program for a first grader to practice subtraction.
Nested if and Multi-Way if-elif-else
statements
One if statement can be placed inside another if statement
to form a nested if statement.
There is no limit to the depth of the nesting.
if score >= 90.0: if score >= 90.0:
grade = 'A' grade = 'A'
else: elif score >= 80.0:
if score >= 80.0:
grade = 'B'
grade = 'B'
else:
elif score >= 70.0:
if score >= 70.0: grade = 'C'
grade = 'C' elif score >= 60.0:
else: grade = 'D'
if score >= 60.0: else:
grade = 'D' grade = 'F'
else:
grade = 'F' This is better
Nested if and Multi-Way if-elif-else
statements
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, and each year in this cycle is represented by an animal
— monkey, rooster, dog, pig, rat, ox, tiger, rabbit, dragon,
snake, horse, and sheep
Logical Operators
The logical operators not, and, and or can be used to create
a composite condition.
Ex: checks whether a number is divisible by 2 and 3, by 2 or 3,
and by 2 or 3 but not both.