CSX3001
FUNDAMENTALS OF COMPUTER
PROGRAMMING
CLASS 03 CONDITIONAL CONTROL STRUCTURE
COMPARISON OPERATORS, BOOLEAN VARIABLE AND OPERATORS,
USING IF-ELSE/IF-ELIF STATEMENTS, NESTED IF-ELSE STATEMENTS
PYTHON
1
BOOLEAN RECAP
Boolean value can be either True or False. They are used to represent truth values.
For instance, isOpen and isPossible are Boolean variables.
isOpen = True
isPossible = False
The common type of Boolean expression is one that compares two values
using a comparison operator. There are six comparison operators.
Considering the following code and each line’s value on the right column.
5 + 7 == 12 True
5 != -1 True
"Ada" == "Steve" False
23 + 2 >= 7 True
2
In addition, Boolean expressions can be joined together using compound
Boolean expressions. It’s a lot like making compound sentences in English with
the words and and or. In programming, there is a third case: not, and we call
these words logical operators.
The result of using compound Boolean expressions will be based on the truth
logic. The following code shows all possible joined expressions of the truth logic
of compound Boolean expressions: and, or, and not.
True and True True
True and False False
False and True False
False and False False
True or True True
True or False True
False or True True
False or False False
not True False
not False True
Considering the following code and each line’s value on the right column.
b1 = True True
b2 = False False
b3 = True True
b4 = False False
b1 or b2 True
b3 and not (b1 or b3) False
3
CONDITIONAL STATEMENT
Conditional statement in python called the if statement. This statement presents
the computer with a condition that the computer makes a choice based on.
IF STATEMENTS
if Boolean expression:
code block
Statement below if
An if statement starts with the keyword if followed by a condition, which is always
a Boolean expression. The computer checks the condition and executes the code
inside the if statement if the condition is true or skips over that code if the
condition is false. Let’s write some code below that tests whether a kid is tall
enough to ride a roller coaster.
1 heightToRideAlone = 150.0
2 userHeight = 152.5
3
4 if userHeight >= heightToRideAlone:
5 print("You are tall enough to ride this roller coaster.")
4
Here, we set 150 cm as the minimum height at which a kid can ride our roller
coaster alone, and we set our rider’s height to 152.5 cm. At line number 3, we
test whether the rider’s height is greater than or equal to heightToRideAlone. Id
it is, the program says that they are tall enough to ride the roller coaster.
Again! To write our if statement, we put the keyword if in front of the condition.
We then indent the code that we want to execute when that condition is true
next line after the colon (:).
1. What happens if we change our rider’s height to a number less than 150?
........................................................................................................................
Nothing shows up?...
ELSE STATEMENTS
Previously, you wanted to tell the computer to print something if a statement is
true. However, what if we want to print something else when the statement is
false? To do this,
if Boolean expression:
code block
else:
code block
... after the if statement and block of code, just type the keyword else followed
by another code block that you want to execute when the if condition isn’t true.
If the rider isn’t tall enough to meet the condition, let’s have the computer
tell them they can’t ride the roller coaster:
1 heightToRideAlone = 150.0
2 height = 152.5
3
4 if height >= heightToRideAlone:
5 print("You are tall enough to ride this roller coaster.")
6 else:
7 print("Sorry. You cannot ride this roller coaster.)
5
We could also test different conditions for the rider’s height to create more rules.
We can do this by adding elif conditions. Let’s see the example below.
1 heightToRideAlone = 150.0
2 heightToRideWithAdult = 140.0
3 height = 152.5
4
5 if height >= heightToRideAlone:
6 print("You are tall enough to ride this roller coaster.")
7 elif height >= heightToRideWithAdult:
8 print("You can ride this roller coaster with an adult.")
9 else:
10 print("Sorry. You cannot ride this roller coaster.")
Note that: once any part of an if or elif statements is found to be true, the rest of
the conditions will not be checked.
Here,
1. If condition1 evaluates to true, code block 1 is executed.
2. If condition1 evaluates to false, then condition2 is evaluated.
a. If condition2 is true, code block 2 is executed.
b. If condition2 is false, code block 3 is executed.
6
Shorthand If
If you have only one statement to execute, you can put it on the same line as the
if statement.
1 if a > b: print("a is greater than b")
Shorthand If ... Else
If you have only one statement to execute, one for if, and one for else, you can
put it all on the same line:
1 a = 2
2 b = 330
3 print("A") if a > b else print("B")
The pass Statement
if statements cannot be empty, but if you for some reason have an if statement
with no content, put in the pass statement to avoid getting an error.
1 a = 33
2 b = 200
3 if b > a:
4 pass
7
Nested-If Statement in Python
A nested if is an if statement that is the target of another if statement. Nested if
statements mean an if statement inside another if statement. Yes, Python allows
us to nest if statements within if statements. i.e., we can place an if statement
inside another if statement.
Syntax:
if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
else:
# Executes when condition2 is false
# if Block is end here
8
Examples:
1 # Example 1: Number checker
2 num = int(input("Enter a number: ")
3 if num > 0:
4 print("The number is positive.")
5 else:
if num < 0:
6 print("The number is negative.")
7 else:
8 print("The number is zero.")
1 # Example 2 : Age classifier
2 age = 35
3
4 if age >= 60:
5 print("You are a senior citizen.")
else:
6 if age >= 18:
7 print("You are an adult.")
8 else:
9 print("You are a teenager.")
1 # Example 3: Odd Even
2 num = 10
3 if num > 0:
4 if num % 2 == 0:
5 print("The number is positive and even.")
else:
6 print("The number is positive but odd.")
7 else:
8 print("The number is not positive.")
9
9
1 # Example 4: Username and Password Checking
2 username = input("Enter your username: ")
3 password = input("Enter your password: ")
4
5 if username == "admin":
if password == "password":
6 print("Login successful! Welcome, admin.")
7 elif password == "12345":
8 print("Weak password. Please reset your
9 password.")
10 else:
11 print("Incorrect password. Please try again.")
else:
12 if username == "guest":
13 if password == "guest":
14 print("Login successful! Welcome, guest.")
15 else:
16 print("Incorrect password. Please try
17 again.")
else:
18 print("Unknown user. Please try again.")
19
1 # Example 5: Username, Password, Email Validation
2 # Using if-else for Validation
3 name = input("Enter your name: ")
4 email = input("Enter your email address: ")
5 password = input("Enter your password: ")
6 if name == "":
7 print("Name cannot be empty.")
8 else:
9 if "@" not in email:
10 print("Invalid email address.")
11 else:
if len(password) > 8:
12 print("Password must be at least 8 characters
13 long.")
14 else:
15 print("Registration successful.")
10
1 # Example 6: User Authentication
2 username = input("Enter your username: ")
3 password = input("Enter your password: ")
4
5 if username == "admin":
if password == "password123":
6 print("Login successful.")
7 else:
8 print("Invalid password.")
9 else:
10 print("Invalid username.")
IF-ELSE EXERCISES
1. Write a Python code that takes three input integer and store them in three
variables, namely numX, numY and numZ. Define a conditional if-elif-else
statement so the code prints out the middle value. The expected
input/output is as follows.
Enter first number: 32
Enter second number: 50
Enter third number: 94
The mid value is 50
2. Write a Python code that takes 3-digits number as an input. If the left-most
digit is an odd number, the code prints “The number you entered starts
with either 1, 3, 5, 7 or 9.” Otherwise, the code prints “The left-most digit
is an even digit.”. If non-3-digit number is entered, the code print “Wrong
Input!!! Try Again.
Enter the 3-digits number: 324
The number you entered starts with either 1, 3, 5, 7,
or 9.
Enter the 3-digits number: 271
The left-most digit is an even number.
11
3. Modify Example #5 to first validate email followed by username and
password validation. Your code must be based on the structure of the code
in exercise 5.
4. Create a variable called heroName and assign a string value of "Superman".
Then the code takes your name as an input. If a total number of characters
of your name is higher than “Superman”, print "You are stronger than
Superman." Otherwise, print "You are weaker than an ant." Hint: use len()
function to determine a string’s length.
Let’s see an example of len() function below;
name = "Jimmy"
lengthOfString = len(name)
print(lenghtOfString) # this will print 5
The expected input/output as follow.
Enter your name: Jimmy
You are weaker than an ant.
5. Write a Python code that takes 3-digit integer value as an input. If the sum
of each digit is an even number, then print "Sum of all digits is an even
number." Otherwise, print "Sum of all digits is not an even number." If non-
3-digit number is entered, the code print “Wrong Input!!! Try Again. The
sample run is shown below.
Enter the 3-digit number: 325
Sum of all digits is an even number.
12
6. Write a Python code to take a height (in cm.) as an input. Print a message
on the screen according to the information shown in the table below. Note
that you must use f-strings for your output format.
Lower than 80 Your height is {height} cm. and you are too short for this ride.
80 – 180 Your height is ok for this ride.
Higher than 180 Your height is {height} are too tall for this ride.
7. Write a Python code to take the electric units from a user and calculate the
bill according to the following rates.
<= 100 units Free
Next 200 units 3 baht per unit
Above 300 units 4 baht per unit
For example, the number of units is 500 the total bill is = 0 + 600 + 800 = 1400
Sample Run 1
Enter the electric units: 350
The total bill is = 0 + 600 + 200 = 800.
Sample Run 2
Enter the electric units: 70
The total bill is = 0.
Sample Run 3
Enter the electric units: 500
The total bill is = 0 + 600 + 1200 = 1800.
13
8. From the given flowchart (shown in the next page), write a Python code
print take your birthday and month.
14
WEEKLY ASSIGNMENTS
1. Simple grade calculator
Write a Python code to take the student’s full name, student ID, two course
IDs, and their associated score.
The following grading criteria are used.
score >= 70 A
60 >= score > 70 B
50 >= score > 60 C
40 >= score > 50 D
score > 40 F
The code determines a grade based on the provided scores. The output
shall be in (or close to) the output format shown in the sample run.
*********************************
** Welcome to Grade Calculator **
*********************************
Enter your full name: Harry P
Enter your student ID: 6719995
*********************************
Enter your course ID: CSX3001
Enter your score: 78.9
*********************************
Enter your course ID: CSX2009
Enter your score: 65.6
*********************************
------------------------------
| Full name | Student ID |
| Harry P | 6719995 |
------------------------------
------------------------------
| Course | Score | Grade |
------------------------------
| CSX3001 | 78.90 | F |
------------------------------
| CSX2009 | 65.60 | F |
------------------------------
15
2. Write a menu-driven Python program, for Healthland Services Co. Ltd., that
gets two inputs; height and weight from a user and shows the service options
list, also referred to as the menu, from which the user chooses their option.
Three services are available.
a) Calculate BMI
b) Height conversion (meters to centimeters)
c) Weight conversion (kilograms to pounds)
After entering the weight and height, the menu is shown, and a user is asked to
select the option (a, b, or c)
Part of the program is given.
1 print('*'*34)
2 print(' Welcome to HealthLand Services Co. Ltd.,')
3 print()
4 weight = …..
5 height = …..
6 option = 'Available Services'
7 print('*'*34)
8 print(f'**** {option:^24s} ****')
9 print(f'* a) Calculate BMI *')
10 print(f'* b) …..
11 print(f'* c) …..
12 print(…..
13 service = input('Choose your service a), b) or c):')
14 print()
###################
## complete the remaining codes
if service == …..
Lines 7 – 12 show the menu on the screen. A user enters ‘a’, ‘b’ or ‘c’ for the
service option. The program prints an output according to the sample runs. Line
13 asks for the service option.
Please observe the sample runs for texts to be put in the menu. You also need to
complete codes in red fonts.
16
If a user enters other options, the program prints ‘Invalid option’
#Sample Run #1
**********************************
Welcome to HealthLand Services.
Enter your weight (kg): 89
Enter your height (m) : 1.89
**********************************
**** Available Services ****
* a) Calculate BMI *
* b) Height conversion (m to cm) *
* c) Weight conversion (kg to lb)*
**********************************
Choose your service a), b) or c): a
Your BMI is 24.92.
Thank you for using our service.
#Sample Run #2
**********************************
Welcome to HealthLand Services.
Enter your weight (kg): 76
Enter your height (m) : 1.69
**********************************
**** Available Services ****
* a) Calculate BMI *
* b) Height conversion (m to cm) *
* c) Weight conversion (kg to lb)*
**********************************
Choose your service a), b) or c): c
Your weight in Pounds is 167.55.
Thank you for using our service.
17