LOOPING IN PYTHON
IF…..ELSE STATEMENT
- What are if...else statement in Python?
- Decision making is required when we want to execute a code only if a
certain condition is True.
Syntax of if...else (Example 1)
if test expression:
Body of if
else:
Body of else
The if..else statement evaluates test expression and will execute body of if only
when test condition is True .
If the condition is False, body of else is executed.
Note Indentation, Punctuation and cases are key when typing programs.
Example 2: Type a Python code to input marks for the following Subjects:
❖ Mathematics ❖ Computer ❖ Global
❖ English Science Perspectives
❖ Kiswahili ❖ History ❖ Chemistry
❖ Physics
The code should Calculate the Total Score and the Average.
The code should output the average and a comment based on the following
Criteria:
IF AVERAGE IS: COMMENT:
80 - 100 - Excellent
70 - 79 - Very Good
60 - 69 - Satisfactory
50 - 59 - Good
40 - 49 - Fair
30 - 39 - Work Hard
29 AND BELOW - Work Extra Hard
The Solution code to the Question: (Copy and Run it on the Python IDLE)
maths = int(input("Enter Mathematics Marks :"))
english = int(input("Enter English Marks :"))
kiswahili = int(input("Enter Kiswahili Marks :"))
cs = int(input("Enter Computer Science Marks :"))
history = int(input("Enter History Marks :"))
gp = int(input("Enter Global Perspectives Marks :"))
chemistry = int(input("Enter Chemistry Marks :"))
physics = int(input("Enter Physics Marks :"))
totalscore = maths + english + kiswahili + cs + history + gp + chemistry + physics
average =totalscore/8
if (average >=80):
print("Your Average Score is:" , average , "A* - That is Excellent")
elif (average >= 70):
print("Your Average Score is:" , average , "A - That is Very Good")
elif (average >= 60):
print("Your Average Score is:" , average , "B - That is Satisfactory")
elif (average >= 50):
print("Your Average Score is:" , average , "C - That is Good")
elif (average >= 40):
print("Your Average Score is:" , average , "D - That is Fair")
elif (average >= 30):
print("Your Average Score is:" , average , "E - That is Work Hard")
else:
print("Your Average Score is:" , average , "Work Extra Hard")
THE CODE ON THE PYTHON IDLE: