You are on page 1of 5

Python IF...ELIF...

ELSE Statements

The syntax of the if...elif...else statement is:

if test1:
statement(s)1
elif test2:
statement(s)2
else:
statement(s)3
Python IF...ELIF...ELSE Statements

age = 20
#simple if
if age > 18:
print("I can vote") # remember indentation

#if-else
if age > 18:
print("I can vote")
else:
print("I cannot vote")

#if-elif-else
if age > 18:
print("I can vote")
elif age == 18:
print("I just turned 18 and can vote too")
else:
print("I cannot vote")
Test syntax
== equal to
and != not equal to
or > greater than
not < less than
True >= greater than or equal
False <= less than or equal

Figure out if these are True or False and then try them out in Python:

1) True and True


2) True and False
3) True or False
4) not True
5) "test" == "test"
6) "test" == "testing"
7) not (10 == 1 or 1000 == 1000)
8) "water" == "cooler" and not (3 == 4 or 3 == 3)
9) 3 == 3 and ("test" == "test" or "Python" == "Fun")
Recap: in and not in operator in conditional statements
Test for membership in strings, lists, tuples and dictionaries
Testing for values in strings:
character(s) in string
character(s) not in string
'p' in 'python'
'p' not in 'python'
You can test if an item is or is not in a list or tuple
item in list
item not in list
1 in [1,2,3]
1 not in [1,2,3]

You can test if a key is or is not in a dictionary


key1 in d
key1 not in d
D1={1:'a',2:'b',3:'c'}
1 in D1
1 not in D1

You can test if a value is or is not in a dictionary


value1 in d.values()
value1 not in d.values()
'a' in D1.values()
If-statements in Functions

def c2(arg):
if arg < 2:
return arg*10
else:
return arg**2

Run the function:

x2=c2(1)
print(x2)

x3=c2(3)
print(c3)

You might also like