Python-3-Conditional Statements(if, While, For, Break, Continue)
Python-3-Conditional Statements(if, While, For, Break, Continue)
IF/ELSE 2
• if/else statement: Executes one block of statements if a certain condition is True, and a second
block of statements if it is False.
• Syntax:
if condition:
statements
else:
statements
• Example:
gpa = 1.4
if gpa > 2.0:
print "Welcome to Mars University!"
else:
print "Your application is denied."
• Syntax:
while condition:
statements
• Example:
number = 1
while number < 200:
print number,
number = number * 2
• Output:
1 2 4 8 16 32 64 128
WHILE LOOPS
>>> import whileloop
x=1 1
while x < 10 : 2
print x 3
x=x+1 4
5
6
7
8
In whileloop.py 9
>>>
In interpreter
THE LOOP ELSE CLAUSE
• The optional else clause runs only if the
loop exits normally (not by break)
x=1
~: python whileelse.py
while x < 3 : 1
print x 2
x=x+1 hello
else:
print 'hello'
Run from the command line
In whileelse.py
FOR LOOP
Here, val is the variable that takes the value of the item
inside the sequence on each iteration. Loop continues
until we reach the last item in the sequence. The body
of for loop is separated from the rest of the code using
indentation.
DIFFERENT WAYS OF USING FOR
LOOP
• 1.
for i in (2,3,4,”hey”,”hi”):
• Print(i)
2.
for i in range(1,6):
print (i)
3.
li=[“apple”,”mango”,”grapes”]
for i in li:
print(i)
CONDITIONAL FLOW
STATEMENTS
BREAK STATEMENT
The break statement terminates the loop containing it.
Control of the program flows to the statement
immediately after the body of the loop. If it is inside a
nested loop (loop inside another loop), break will
terminate the innermost loop.
CONTINUE STATEMENT