The program makes decisions using if. This is known as a conditional structure.
You hear if used everyday - "If it's sunny, wear a hat", "If you are hungry have an apple", "If you don't tidy your room it's all going in the bin!!", etc. All these sentences have a thing to check and then a thing that will happen if that check is true. Python works the same way.
We follow the if keyword with a condition followed by a colon, then there is an indented section of code that only gets run if the condition is true. If the condition is not true then the program skips the indented piece of code and goes to the next unindented line after that, eg
username = input("Please tell me your name: ")
if username == "Anne":
print("Welcome, Anne.")
print("Proceed through to security")
print("Next")
The program will ask the user for their name and store their response as username. If username is equal to Anne then it will print 'Welcome, Anne. Proceed through to security' it will then print 'Next'. If username is not equal to Anne then it will only print 'Next'.
Note the double equal == used to compare the username to the text string Anne.
A single = assigns the identifier on the left the value of the stuff on the right. It can be thought of as saying 'make this equal to' so age = 15 can be read as 'the variable age is now equal to the number 15' or 'The number 15 now has the identifier age associated with it'
== means 'compare the stuff on the left and the stuff on the right and if they are the same say it is True, if they are not equal say it is False'
We use the word 'equal' for both of these cases but a computer needs different symbols.
Just as we can use == to check if two things are equal we can use other mathematical comparisons:
this > that means this is greater than that
this < that means this is less than that
this >= that means this is greater or equal to that
this <= that means this is less than or equal to that
this != that means this is not equal to that
We can combine several if statements to make it look like the computer is quite intelligent when really it is just following a series of yes/no questions. With a series of if statements the computer deals with each one as a separate question.
number = 8
if number < 5 :
print("Tiny")
if number < 10 :
print("Medium")
if number < 20 :
print("Big")
Will print Medium and Big because 8 is less than 10 and number is less than 20 so both Medium and Big get printed. If we want to stop looking for an answer once you find a first correct one then we need to tell the program to consider all of the ifs as a single decision. For this we need if...else or if...elif...else
If Part 1 - First if
If Part 2 - more than one if
If Part 3 - Greater than and Less than. Also getting numbers from input
If Recap video for IDLE users
Links to some other IF related content...though not related to Python