2.0 Python – Conditionals – The if Keyword
Conditionals are what allow our programs to make decisions. Conditionals are generally based on evaluating items that are:
|!=||Not Equal To|
|>=||Greater than or equal to|
|<=||Less than or equal to|
An example may be a program that determines if a user is old enough to vote by asking the user their age. If the user is 18 or older, then that user can vote.
#Ask the user their age YourAge=input(“What is your age? “) #Convert users age to an integer to evaluate numerically IYourAge=int(YourAge) #if statement -> Conditional! if (IYourAge>17): print(“You are old enough to vote!”) else: print(“Sorry, you can’t vote yet!”)
The if statement is used to evaluate conditions and take action base on whether the condition evaluates to true or false.
if (Condition To Evaluate):
#Do This is true —>All items indented under if are executed until next
if / else
An if / else statement lets the programmer create a conditional that does one thing if the condition evaluates to true and another if the condition evaluates to false.
if (Condition to Evaluate):
#Do this if true
#Do this if false
if / elif / else
if / elif / else allows the programmer to evaluate multiple conditions. For example, assigning letter grades to numeric values may use if / elif / else:
#Assign letter grades if (grade>95): LetterGrade="A+" elif (grade>90): LetterGrade="A" elif (grade>85): LetterGrade="B+" elif (grade>79): LetterGrade="B" elif (grade>69): LetterGrade="C" elif (grade>64): LetterGrade="D" else: LetterGrade="F"