In [1]:
#just repeatedly do ten times
for i in range(0,10):
print "*"
In [2]:
#each time print more stars
for i in range(0,10):
print "*"*i
In [13]:
#each time print less stars
for i in range(0,10):
print "*"*(10-i)
In [13]:
#it could be funny
for i in range(0,10):
print "*"*i+" "*3+"*"*(10-i)
In [3]:
#loop index i is not use in the loop command, nothing is changed.
a=5
for i in range(0,10):
print "*"*a
In [4]:
for i in range(0,10):
print i
In [14]:
for i in range(0,10):
print i, i*i
In [5]:
#we can iterate through i
for i in range(0,10):
print i**0.5,i, i**2, i**3
In [15]:
#format is not good. use rjust() a string function.
#use str and float to convert data type to str and float
print 'square root'.rjust(15),'integer'.rjust(10), 'square'.rjust(10), 'cubic'.rjust(10)
for i in range(0,10):
print str(float(i)**0.50).rjust(15),str(i).rjust(10), str(i**2).rjust(10), str(i**3).rjust(10)
In [15]:
#comparator and logic and/or
a=10
print a<20
print a<20 and a>5
print a<20 or a<12
print 12<a<20
In [17]:
a=10
while a<20:
print a
a=a+1
In [19]:
#if we set the wrong conditions, loop command will never be excute.
#nothing will be printed
a=10
while a==20:
print a
a=a+1
In [1]:
#if we do no change loop index, it will execute forever.
#following code will never stop
#do not run.
a=10
while a<20:
print a
In [2]:
#while could be used just like a for loop
a=0
while a<10:
print a
a=a+1
In [3]:
#while could be used just like a for loop
#be careful while you change the loop index
a=0
while a<10:
print a
a=a+1
a=a*2
In [11]:
#check if a is a prime
# we can use a flag to trig the exit immediately, save time
a=131
i=2
found=False
is_prime=True
while (i<a) and found==False:
print i, " : testing......"
if a%i==0:
print a," = ", i, " * ",a/i
found=True
is_prime=False
else:
#print i,"can not divide ", a
found=False
i=i+1
#note that once a%i=0, the while loop just stop/exit
print "Prime => ",is_prime
In [12]:
#check if a is a prime
# we can use a flag to trig the exit immediately, save time
#actually we do not have to check till a-1, sqrt(a) is enough
a=131
i=2
found=False
is_prime=True
while (i<float(a)**0.5) and found==False:
print i, " : testing......"
if a%i==0:
print a," = ", i, " * ",a/i
found=True
is_prime=False
else:
#print i,"can not divide ", a
found=False
i=i+1
#note that once a%i=0, the while loop just stop/exit
print "Prime => ",is_prime
While and For are powerful loop tools, we can use them to do repeated operation. Pay attention to
In [ ]:
test