Python

If statements

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.

Related Course: Complete Python Bootcamp: Go from zero to hero in Python

If statements

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.')

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).

Note: Code is executed based on the variable x. Try different numbers: 2,3,4

If else

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:

if statement

Previous Post Next Post

Cookie policy | Privacy policy | ©