while循环
格式:
while <test>:
<statements1>
else:
<statements2>
>>> x = "xunye"
>>> while x:
... print(x, end=' ')
... x = x[1:]
xunye unye nye ye e
end=' '关键字参数,所有输出都在同一行,输出之间以空格隔开。
break、continue、pass和循环else
(break和continue)只有在循环中才起作用。
while <test1>:
<statements1>
if <test2>: break
if <test3>: continue
else:
<statements2>
pass是空语句,相当于C++中的“;”语句。
continue
x = 10
while x:
x = x - 1
if x % 2 == 0: continue
print(x, end=' ')
输出结果:8 6 4 2 0
break
while True:
name = input('Enter Name: ')
if name == 'xunye': break
age = input('Enter Age: ')
print(name, ' => ', int(age))
else:主要用于测试循环的执行。
for循环
格式:
if <target> in <object>:
<statements1>
else:
<statements2>
for x in ['xunye', 'dream', 'hero', 'bea']
print(x, end=' ')