Conditional Statements in Python
Subject: Python Programming
As you continue to program you will soon realise that you may have to make some decisions in your program for example you may want to ensure that the age the user inputted is above 18, the score inputted is above 0.
This is done using the IF, ELSE IF and ELSE conditional statements. When the condition is true you may want to execute a block of code, else execute another block of code, this is also called branching in programming.
For example 1
age=int(input("How hold are you "))
#check is age is above 18
if age > 18:
#execute this line of code if the condition is true
print ("Welcome you are above 18")
else:
#if the condition is not true then execute this line
print ("Sorry you are underage")
Note the conditional statement uses the Logical Operators for it's decisions
< (less than)
<= (less than or equal to)
> (greater than)
>= (greater than or equal to)
== (equal to), please don't confuse this with assignment operator =
!= (not equal to)
Example 2
temp=int(input("What is the temperature ")
if temp >= 90:
print ("It's too hot")
elif temp <= 30:
print ("It's too cold")
else:
print ("The temperature is good")
Note: after the if, elif (else if), else statement Python expect the executed line after this statements to be indented, is is very important in Python programming else it will throw up an error message.
Example 3
username=input("Enter your username ")
if username.lower()=="onuorah":
print ("Welcome ",username)
else:
print ("Unauthorized user ",username)
Note the example 3 ask user to input there username, since it's a text or string you don't need to convert it with int(....)
The if statement check if you user entered "onuorah" (all in lower case), however because a user can mistakenly enter "Onuorah" (all NOT in lower case) we need to convert the input to lower case before comparing therefore we use the string method lower()
By:
Benjamin Onuorah
Comments
Joshua Fasinu (learner)
Date commented: 13-Aug-2024 08:05:14am
If i have more than one 'if statement' i can make use of the elif
Login to comment or ask question on this topic
Previous Topic Next Topic