Python 3
Python 3
3.1 If statement
If statement allows us to choose which statements to execute.
if statement checks whether a given condition is met.
When the condition is true, a set of codes will be executed.
Otherwise, an alternative set of codes will be executed (or doing nothing).
To understand how if statement works, let’s type the following code.
1. scale = input("Do you like learning Python (1-100)? ")
2. scale = float(scale) #convert string to float
3. Q6
4. print("Good to know that you like it!")
5. print("Let’s learn more about coding!")
The section of code to run when the condition is met has to be indented.
Indentation can simply make by pressing “Enter” after the “:” in an if statement
You can also make the indentation by ”Tab” or inserting spaces.
More than one statement can be controlled by a conditional.
Each statement should use the same indentation
You can simply press “Enter” after the first statement to make the same indentation.
Insert a line after line 4, to print a message "Please like and subscribe! " when scale >= 80.
Python is a case-sensitive language, so IF and If are not working.
3.2 Else
Else statement allows you to perform an action when the given condition is not met.
Please insert the following lines after printing the message "Please like and subscribe".
6. else:
7. print("The later chapters would be more interesting!")
An else statement should have the same indentation level as the if statement.
To delete an indentation level, you can press “Shift”+“Tab” or “Backspace”.
The action taken when the else condition is met has to have one indentation level
higher than the else statement.
3.4 Elif
Elif statement helps us to make nested if statements easier to code and read.
if statement, elif statement and else statement should have the same indentation level.
5. elif scale >= 60:
6. print("The later chapters would be more interesting! ")
7. else:
8. print("Cheer up! You will like it one day! ")
9. print("Let’s learn more about coding! ")
Diagram 1
Flow chart for the if function
Diagram 2
Flow chart for the while loop
3.9 Exercises
1. Write a program to provide the suggested energy consumption per day based on their gender and
age. The following is the suggested calorie consumption:
Hints:
gender = input("Please input your gender (M for male and F for female): ")
age = int(input("Please input your age: "))
if age >= 18:
2. Use while loop to ask a user to input again if the first is neither “M” or “F”.
3. Write a program to ask a user to input an integer between 2 and 10,000, and identify whether it is a
prime number.
4. Write a program to ask a user to input a positive integer, and calculate the number of digits of this
number.
End of Module 3