Conditions: if, then, else - Learn Python 3 - Snakify

Lesson 3. Conditions: if, then, else




1/15. The syntax

Let's write a program which, given an integer x, prints |x| — its absolute value.

By definition of absolute value, if x > 0, such program should just print x. Otherwise, it should print -x. Naturally we are about to check if some condition is met. The behaviour is different when it is met and when it is not.

The keywords if and else are used in such situations. Look at the code.

Given -273 as the input data, it outputs 273. Why? Check the tick "step by step" and look at the visualizer.
x = int(input())
if x > 0:
    print(x)
else:
    print(-x)