Loops are for repetitive operations
# Example Loops
# this loop from 0 to 99
for i in range (100):
print ( i )
# range (a,b) will loop from a to b
# and a must be less than b
for i in range (3,5):
print ( i )
# What is 3 doing here? Three is a crowd, or not?
for i in range (10,20,3):
print ( i )
# Break or continue? That is the question.
for i in range ( 0, 9 ):
if ( i == 7 ): break
if ( i % 2 == 0 ): continue
# Lazy Ann's version
for i in range(10):
if i == 7: break
if i%2: continue
# Look! I can do days too!
days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" ]
for d in days:
print ( d )
# Python has while loop too.
i = 0
while i < 3:
print ( i )
i += 1
## Remember, python does not do "i++"
while True:
print ( "I am in loop!" )
if True:
break
## See? You have to break it otherwise it goes on and on and on...
# No, python does not have do while loop
# But it has something cool called 'enumerator'
for i, d in enumerate (days):
print (i, d)
# descinding
for i in range (9,1,-1):
print (i)
x = range(10)
z = list(range(10))
y = list( 10-i for i in x )
print (x)
print (z)
print (y)
No comments:
Post a Comment