You are on page 1of 13

ISTLS Asma HADYAOUI

Chapter 2
Conditional statements
Alternative branches using the if statement

Example 1
age = int(input("How old are you? "))

if age > 17:


print("You are of age!")
print("Here's a copy of GTA6 for you.")

print("Next customer, please!")

When the user is over the age of 17, the execution of the program
should look like this:

Sample output

1
ISTLS Asma HADYAOUI

How old are you? 18 You are of age! Here's a copy of GTA6 for you.
Next customer, please!

If the user is 17 or under, only this is printed out:

Sample output
How old are you? 16 Next customer, please!

Comparison operators
Very typically conditions consist of comparing two values. Here is a
table with the most common comparison operators used in Python:

Example

number = int(input("Please type in a number: "))

if number < 0:
print("The number is negative.")

if number > 0:
print("The number is positive.")

2
ISTLS Asma HADYAOUI

if number == 0:
print("The number is zero.")

Indentation
Python recognizes that a block of code is part of a conditional
statement if each line of code in the block is indented the same. That
is, there should be a bit of whitespace at the beginning of every line of
code within the code block. Each line should have the same amount
of whitespace.

You can use the Tab key, short for tabulator key, to insert a set amount
of whitespace:

When you want to end an indented :

Boolean values and Boolean expressions

3
ISTLS Asma HADYAOUI

Any condition used in a conditional statement will result in a truth


value, that is, either true or false. For example, the condition a < 5 is
true if a is less than 5, and false if a is equal to or greater than 5.

These types of values are often called Boolean values, named after the
English mathematician George Boole. In Python, they are handled by
the bool data type. Variables of type bool can only have two
values: True or False.

Example:

a = 3
condition = a < 5
print(condition)
if condition:
print("a is less than 5")
Sample output
True a is less than 5

Programming exercise 1:
Loyalty bonus
This program calculates the end-of-year bonus a customer receives
on their loyalty card. The bonus is calculated with the following
formula:

• If there are less than a hundred points on the card, the bonus is 10 %
• In any other case the bonus is 15 %

The program should work like this:

Sample output
How many points are on your card? 55 Your bonus is 10 % You now
have 60.5 points

Programming exercise 2:

4
ISTLS Asma HADYAOUI

What to wear tomorrow


Please write a program that asks for tomorrow's weather forecast and
then suggests weather-appropriate clothing.

The suggestion should change if the temperature (measured in


degrees Celsius) is over 20, 10, or 5 degrees and if there is rain on the
radar.

Some examples of expected behavior:

Sample output
What is the weather forecast for tomorrow?
Temperature: 21
Will it rain (yes/no): no
Wear jeans and a T-shirt
Sample output
What is the weather forecast for tomorrow?
Temperature: 11
Will it rain (yes/no): no
Wear jeans and a T-shirt I recommend a jumper as well

Programming exercise 3:
Solving a quadratic equation
In the Python math module there is the function sqrt, which
calculates the square root of a number. You can use it like so:

from math import sqrt

print(sqrt(9))
This should print out

Sample output
3.0

5
ISTLS Asma HADYAOUI

We will return to the concept of a module and the import statement


later. For now, it is sufficient to understand that the line from math
import sqrt allows us to use the sqrt function in our program.

Please write a program for solving a quadratic equation of the form


ax²+bx+c. The program asks for values a, b and c. It should then use
the quadratic formula to solve the equation. The quadratic formula
expressed with the Python sqrt function is as follows:

x = (-b ± sqrt(b²-4ac))/(2a).

You can assume the equation will always have two real roots, so the
above formula will always work.

An example of expected behavior:

Sample output
Value of a: 1

Value of b: 2

Value of c: -8

The roots are 2.0 and -4.0

6
ISTLS Asma HADYAOUI

Alternative branches using the if-else statement

Example:

number = int(input("Please type in a number: "))

if number % 2 == 0:
print("The number is even")
else:
print("The number is odd")
Sample output
Please type in a number: 5 The number is odd

7
ISTLS Asma HADYAOUI

Alternative branches using the elif statement


Often there are more than two options the program should account
for. For example, the result of a football match could go three ways:
home wins, away wins, or there is a tie.

A conditional statement can be added to with an elif branch. It is


short for the words "else if", which means the branch will contain an
alternative to the original condition. Importantly, an elif statement is
executed only if none of the preceding branches is executed.

8
ISTLS Asma HADYAOUI

Example:
goals_home = int(input("Home goals scored: "))
goals_away = int(input("Away goals scored: "))

if goals_home > goals_away:


print("The home team won!")
elif goals_away > goals_home:
print("The away team won!")
else:
print("It's a tie!")

This program could print out three different statements given


different inputs:

Sample output
Home goals scored: 4 Away goals scored: 2 The home team won!

Programming exercise:
Alphabetically last
Python comparison operators can also be used on strings. String a is
smaller than string b if it comes alphabetically before b. Notice
however that the comparison is only reliable if

• the characters compared are of the same case, i.e. both UPPERCASE or
both lowercase
• only the standard English alphabet of a to z, or A to Z, is used.

Please write a program that asks the user for two words. The program
should then print out whichever of the two comes alphabetically last.

Some examples of expected behaviour:

Sample output
Please type in the 1st word: car Please type in the 2nd word: scooter
scooter comes alphabetically last.

9
ISTLS Asma HADYAOUI

Combining conditions
• Logical operators

You can combine conditions with the logical operators and and or.
The operator and specifies that all the given conditions must be true
at the same time. The operator or specifies that at least one of the
given conditions must be true.

For example, the condition number >= 5 and number <=


8 determines that number must simultaneously be at least 5 and at
most 8. That is, it must be between 5 and 8.

number = int(input("Please type in a number: "))


if number >= 5 and number <= 8:
print("The number is between 5 and 8")

The following truth table contains the behaviour of these operators in


different situations:

10
ISTLS Asma HADYAOUI

Simplified combined conditions


The condition x >= a and x <= b is a very common way of checking
whether the number x falls within the range of a to b. An expression
with this structure works the same way in most programming
languages.

Python also allows a simplified notation for combining conditions:


a <= x <= b achieves the same result as the longer version
using and. This shorter notation might be more familiar from
mathematics, but it is not very widely used in Python programming,
possibly because very few other programming languages have a
similar shorthand.

Example
n1 = int(input("Number 1: "))
n2 = int(input("Number 2: "))
n3 = int(input("Number 3: "))
n4 = int(input("Number 4: "))

if n1 > n2 and n1 > n3 and n1 > n4:


greatest = n1
elif n2 > n3 and n2 > n4:
greatest = n2
elif n3 > n4:
greatest = n3
else:
greatest = n4

print(f" {greatest} is the greatest of the numbers.")

Sample output
Number 1: 2
Number 2: 4

11
ISTLS Asma HADYAOUI

Number 3: 1
Number 4: 1
4 is the greatest of the numbers.

Programming exercise:
Alphabetically in the middle
Please write a program that asks the user for three letters. The
program should then print out whichever of the three letters would
be in the middle of the letters were in alphabetical order.

You may assume the letters will be either all uppercase or all
lowercase.

Some examples of expected behaviour:

Sample output
1st letter: x
2nd letter: c
3rd letter: p
The letter in the middle is p

Programming exercise:
Gift tax calculator
Some say paying taxes makes Finns happy, so let's see if the secret of
happiness lies in one of the taxes set out in Finnish tax code.

According to the Finnish Tax Administration, a gift is a transfer of


property to another person against no compensation or payment. If
the total value of the gifts you receive from the same donor in the
course of 3 years is €5,000 or more, you must pay gift tax.

When the gift is received from a close relative or a family member, the
amount of tax to be paid is determined by the following table:

12
ISTLS Asma HADYAOUI

Value of gift Tax at the lower limit Tax rate for the exceeding part (%)

5 000 — 25 000 100 8

25 000 — 55 000 1 700 10

55 000 — 200 000 4 700 12

200 000 — 1 000 000 22 100 15

1 000 000 — 142 100 17

So, for a gift of 6 000 euros the recipient pays a tax of 180 euros (100
+ (6 000 - 5 000) * 0.08). Similarly, for a gift of 75 000 euros the
recipient pays a tax of 7 100 euros (4 700 + (75 000 - 55 000) * 0.12).

Please write a program which calculates the correct amount of tax for
a gift from a close relative. Have a look at the examples below to see
what is expected. Notice the lack of thousands separators in the input
values - you may assume there will be no spaces or other thousands
separators in the numbers in the input, as we haven't yet covered
dealing with these.

Sample output
Value of gift: 3500 No tax!

Sample output
Value of gift: 5000 Amount of tax: 100.0 euros

Sample output
Value of gift: 27500 Amount of tax: 1950.0 euros

13

You might also like