Deals Of The Week - hours only!Up to 80% off on all courses and bundles.-Close
Introduction
Conditional statements
Summary

Instruction

Good. Now, let's introduce if statements. They are used to check some conditions and execute different parts of code depending on the results of these conditions:

john_age = 25
user_age = input('How old are you?')

if int(user_age) > john_age:
  print('You are older than John.')
  1. We started line #4 with the if keyword.
  2. After a space, we provided the condition: user_age must be greater than john_age (recall that user input is always treated as string, so we had to convert user_age to int).
  3. After the condition, we need a colon (:).
  4. On line #5, we wrote the instruction that should be executed when the condition is met (i.e., when user_age > john_age returns True).

Note that indentation is very important in Python. The code to be executed when the condition is met (i.e., the code after if) must be indented – the lines after if must start with a certain number of spaces (1 or more) or tabs. You can choose any of the two styles, but you have to be consistent.

The PEP8 (Python Enhancement Proposal 8 – the document that gives coding conventions for Python) proposes to use four spaces per indentation level.

Exercise

Write a program that will ask the user for their height in centimeters. For convenience, the user prompt is already in the Code Editor.

If the height is more than 185 centimeters, print the following line of code: You are very tall.

Stuck? Here's a hint!

Write an if statement. Remember that you need to convert user input into an integer using int().