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:
> greater than < smaller than == equals != 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.')
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.')
See the demonstration below:
If x is set to 2, the second code block is executed. If x equals (==) four, the first code block is executed.