Course 3.1Lesson 2 of 5
An if statement runs the lines under it only when its condition is True. The line ends with a colon, and the lines that belong to it are indented by four spaces. An else part runs when the condition is False. Only one of the two parts runs, and the lines with no indent run every time. An if can stand alone with no else. Ask the user with input() and decide with if, and use a remainder with == to test for even and odd.
Try the code and the simulations beside the lesson.
After this lesson you can
if statement, and an if with an else,An if statement has a condition, the question, and some lines that run only when the answer is True.
What did the program do?
age >= 18?if.else.Only one of the two parts runs. Never both.
The first line of an if ends with a colon :. The lines that belong to the if are indented, by four spaces. The words if and else are written in small letters.
The indent is how Python knows which lines belong to the if. In many languages, curly brackets do this job. In Python, it is the white space. This is a strong rule, so be careful: the lines in one block must have the same indent, and the lines that come after the block go back to the left edge.
What happens when you forget the indent?
An age of exactly 18 goes to the if part, because 18 >= 18 is True.
An else is not necessary. Sometimes you only want to do something extra in a special case.
A program that decides on what the user types is a real program. Remember: input() gives text, so we change it with int().
Type 15 in the Input box and run it. The program says that you are not an adult yet, and it works out how many years remain. Run it with 30. Run it with 18: the condition age >= 18 is True for 18 exactly. This kind of test, at the edge, is important, and we study it in a later lesson.
An even number leaves a remainder of 0 when divided by 2.
if or the else line.= instead of == in the condition.else at a different indent from the if. The two words must line up.else. else never has a condition. For that, use elif, in the next lesson.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
if condition: and then indented lines. The lines run only when the condition is True.else: runs when the condition is False. Only one of the two parts runs.number % 2 == 0 tests for an even number.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
if and else run in one run?if block run in every case?if x = 5: do?n is odd?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.