Python3.7.4入门-2流程控制工具,流程工具


2 流程控制工具

记得在语句后加冒号

2.1 while

# Fibonacci series:
# the sum of two elements defines the next
a, b = 0, 1
while a < 10:
    print(a,end=',')
    a, b = b, a+b
  • while 循环只要它的条件(这里指: a < 10)保持为真就会一直执行
  • 循环体用 tab 缩进
  • 关键字参数 end 可以用来取消输出后面的换行, 或是用另外一个字符串来结尾

2.2 if

x = int(input("Please enter an integer: "))

if x < 0:
    x = 0
    print('Negative changed to zero')
elif x == 0:
    print('Zero')
elif x == 1:
    print('Single')
else:
    print('More')
  • 一个 if ... elif ... elif ... 序列可以看作是其他语言中的 switchcase 语句的替代

2.3 for

words = ['cat', 'window', 'defenestrate']
for w in words:
    print(w, len(w))
  • Python中的 for 是对任意序列进行迭代(例如列表或字符串),条目的迭代顺序与它们在序列中出现的顺序一致

2.4 range()

a = ['Mary', 'had', 'a', 'little', 'lamb']
for i in range(len(a)):
    print(i, a[i])
range(5, 10)
   5, 6, 7, 8, 9

range(0, 10, 3)
   0, 3, 6, 9

range(-10, -100, -30)
  -10, -40, -70
  • range() 所返回的对象在许多方面表现得像一个列表,但实际上却并不是。此对象会在你迭代它时基于所希望的序列返回连续的项,但它没有真正生成列表,这样就能节省空间
  • range(2,2) 无输出

2.5 break/continue

  • break 语句用于跳出最近的 for 或 while 循环
  • continue 语句表示继续循环中的下一次迭代

2.6 pass

def f(arg): pass    # a function that does nothing (yet)
class C: pass       # a class with no methods (yet

pass是一个空操作 --- 当它被执行时,什么都不发生。 它适合当语法上需要一条语句但并不需要执行任何代码时用来临时占位Python3.7.4入门-2流程控制工具

相关内容

    暂无相关文章

评论关闭