控制语句(for/while)

49 篇文章 0 订阅

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

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值