if statement

Statements under 'if' executes only when the given condition is true.

Otherwise those statements will not be part of program.


if condition:

Always False

if 0:
    print("I won't be a part of the execution")
if False:
    print("I won't be a part of the execution")

Always True

if 1:
    print("I am in")
if True:
    print("I am in")

if 100:  #any positive number
    print("I am in")

if -157: #any negative number
    print("I am in")

Likewise, when we give some expression or logical combination of expression in if statement, the statements under if only work, if the expressions output is non-zero.

Sample Program

Get a number from the user. If its negative, make it positive and print it. if its positive, print it straightaway.


num = int(input("Enter a number"))

if num < 0:
  num = -num;


Topics You Might Like