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:

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.

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


  • jeykiran says:

    Where do i type in this command
    x = int(input(“Tell X”))

    if x == 4:
    print(‘You guessed correctly!’)
    print(‘Wrong guess’)

    print(‘End of program.’)
    i tried to type this command in python 3.5.2 Shell, its showing an error. i need help in this.


    • CodeNinja says:

      Copy this code into a text file, save it as example1.py
      Then run “python3 example1.py”

  • emeka says:

    after writing print( ‘you guessed correctly!’) i get this error message indentation error ; expected an intend block please help , when i go back and click enter it works normal please assist

    • CodeNinja says:

      indention errors are about the number of spaces. Put four spaces inside the if statement blocks

Leave a Reply