python - loops
2020-08-27 本文已影响0人
Pingouin
loops and iteration
While
while loops are called indefinite loops because they keep going until a logical condition becomes False.
# break out of a loop
while True:
line = input('>')
if line == 'done':
break
print(line)
print('done!')
# finishing an iteration with contine
while True:
line = input('>')
if line[0] == '#':
continue # go up back to the tope of loop
if line == 'done':
break # get out of the loop
print(line)
print('done!')
for
definite loops iterate through the members of a set.
for i in [5,4,3,2,1]: # i is iteration variable
print(i)
print('blast off!')
friends = ['ke','xinlei','xjc']
for friend in friends:
print('hi',friend)
print('ok')
# count
count = 0
sum = 0
print('before',count,sum)
for things in [9,41,12,3,74,15]:
count += 1
sum += things
print(things,count,sum)
print('after',count,sum)
# a none type
smallest = None
print('before',smallest)
for value in [9,41,12,3,74,15]:
if smallest is None:
smallest = value
elif value < smallest:
smallest = value
print(smallest,value)
print('after',smallest)
# 'is' is stronger than '==' e.g. 0 == 0.00
# use is for None/ Ture False, not recommended use for integer
condition
astr = 'hello'
try:
print('hello')
astr = int(astr) #注意此处错误
except: # 只在try错误的时候触发 每一条
astr = -1
print('First', istr)