If statements are all about choices.
A block of code is executed based on one or more conditions. The block of code will only be executed if the condition is true.
Computer programs do not only execute instructions. Occasionally, a choice needs to be made. Such as a choice is based on a condition.
Python has several conditional operators:
< smaller than
!= is not
Conditions are always combined with variables. A program can make a choice using the if keyword. For example:
x = int(input("Tell X")) if x == 4: print('You guessed correctly!') print('End of program.')
The condition is shown on line 3.
When you execute this program it will always print ‘End of program’, but the text ‘You guessed correctly!’ will only be printed if the variable x equals to four (see table above).
Python can also execute a block of code if x does not equal to 4. The else keyword is used for that.
x = int(input("Tell X")) if x == 4: print('You guessed correctly!') else: print('Wrong guess') print('End of program.')
If x is set to 2, the second code block is executed. If x equals (==) four, the first code block is executed.
Take a look at the execution below: