控制语句(for/while)

版权声明:本文为博主原创文章,如有需要,可以随意转载,请注明出处。 https://blog.csdn.net/xunye_dream/article/details/82728305

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=' ')

猜你喜欢

转载自blog.csdn.net/xunye_dream/article/details/82728305
今日推荐