条件判断
简单if语句
>>>name=‘lily‘ >>>if name=‘lily‘: print ‘hello,‘, name hello,lily
if-else
>>>score=90 >>>if score>=80: print ‘very good‘ else: print ‘keep trying‘ very good
if-elif-else
>>> age=18 >>> if age>=18: print ‘adult‘ elif age<18: print ‘teenager‘ else: print ‘please enter the correct age‘ adult
循环
for
>>> L=[1,2,3,4,5] >>> for v in L: print v 1 2 3 4 5
while
>>> a=0 >>> while a<10: a=a+1 print a 1 2 3 4 5 6 7 8 9 10
退出循环
break与continue区别:
break:退出循环体
利用 while True 无限循环配合 break 语句,计算 1 + 2 + 4 + 8 + 16 + ... 的前20项的和。
>>> s = 0 >>> x = 1 >>> n = 1 >>> while True: if n>20: break s=s+x x=x*2 n=n+1 print s 1 3 7 15 31 63 127 255 511 1023 2047 4095 8191 16383 32767 65535 131071 262143 524287 1048575
continue:退出本次循环,不执行此次循环的循环体,继续下一个循环
>>> b=[0,1,2,6,3,4,1,5] >>> for v in b: if v<2: continue print v 2 6 3 4 5
时间: 2024-10-18 05:06:31