If Else Overview
If allows you to make a choice dependant on almost anything.
It can be used with text, numbers or users choices.
We use if else choices everyday.
If someone nice smiles at you smile back else keep a straight face.
Simple if else
happyorsad = input("Type h if you are happy. Type s if you are sad")
if happyorsad == ("h"):
print("I am so pleased you are happy")
else:
print("I am very sorry you are sad today")
If you typed h when asked if you were happy or sad the program would print
I am so pleased you are happy
If you typed s (or any other letter) the program would print
I am very sorry you are sad today
Note that both print lines are indented (don't start on far left) this means they are only run if the condition above them is met.
Adventure Game If Else
If event one is equal to letter s:
print("One outcome")
else:
print("different outcome")
Note if the user had typed using a capital S then it would not have been equal
Quiz Question If Else
(copy and paste to use)
score = 0
ans1 = int(input("How many sides does a triangle have?"))
if ans1 == 3:
score = score + 1
print("Well done you now have",score,"score")
else:
print("Wrong answer, your score is",score)
#Assign 0 to score
#Input user answer into ans1
#If ans1 same as 3 then
#run code
#run code
#else
#run code