If/ else Statements

Decisions are implemented in Python with if statements. Based on the evaluation of conditions, if statements let you change the flow of control in a (Python or Java) program. Almost all nontrivial(what does it mean? Keep going anyway.) programs use one or more if-statements, so they are important to understand.

The syntax

if (condition is) True:    
    do this                   # if clause
elif (condition is) True:     # (optional)
    do that                   # elif clause
else:                         # (optional)
    do something else         # else clause

The elif and else parts are optional.

simple if statement

n=3
if n > 1:
    print(n)

The console result: 3

Adding an else

Sometimes adding an else statement is completely optional, but if you include the else, you have to put a block of code under it.

n=3
if n > 10:
    print ('n is larger than 10')
else:
    print ('n is smaller than 10')

Console result:

n is smaller than 10

Then change n=3 to be n=12, run again:

n is larger than 10

Testing many things with elif

An if/elif-statement is a generalized if-statement with more than one conditions.

age = int( input('Enter your age:') )

if age > 12:
    print('It will be hard to get you laugh.')
elif age>5 and age<=12:
    print('What did o said to 8?')
    print('Hi, guys!')
else:
    print('You are too young for my jokes.')

Run the program, the console shows a message:

Enter your age:

Type in 8 Console results:

What did o said to 8?
Hi, guys!

Next run again and enter 15:

Enter your age: 15
It will be hard to get you laugh.

Try if statements in CodeCraft

We can test some Boolean in CodeCraft world. Show True/False results with green block(66) at the right side or red block(73) at the left side.

# line1 (y=1)
if True:
    block(1,1,-20, 66)
else:
    block(-1,1,-20, 73)

# line2 (y=2), call block(x,y,z,m)
if 2>3:
    block(1,2,-20, 66)
else:
    block(-1,2,-20, 73)

# line3
if 'cat' != 'dog':
    block(1, 3, -20, 66)
else:
    block(-1, 3, -20, 73)

# line 4
if (4==2*2 and 2==3):
    block(1, 4, -20, 66)
else:
    block(-1, 4, -20, 73)

# line 5  (add yellow for the second condition)
if 2>3:
    block(1, 5, -20, 66)
elif (5**2) >= 25:
    block(0, 5, -20, 76)
else:
    block(-1, 5, -20, 73)

The results are direct to see: Green --> True Red --> False The top middle yellow block means for the last if, the second condition is True

results matching ""

    No results matching ""