选择
-
真值/假值
假(7种):False(标准真值)、None、0、[](空列表)、()(空元组)、‘’(或"",空字符串)、{}(空集合或空字典)
真(无数种):其他所有(包括True(标准真值))
>>>bool('I think, therefore I am') True >>>bool(42) True >>>bool('') False >>>bool(0) False
-
if else
num = int(input('Enter a number: ')) if num > 0: print('This number is positive') elif num < 0: print('This number is negative') else: print('This number is zero')
-
条件运算符(相当于:?)
status = "friend" if name.endswith("Gumby") else "stranger"
-
比较运算符
表达式 描述 x is y x和y是同一个对象 x is not y x和y是不同的对象 x in y x是容器(如序列)y的成员 x not in y x不是容器(如序列)y的成员 链式比较
>>>if 0 < key < 2: ... print('0 < key < 2') 0 < key < 2
列表比较
>>>[1, 2] < [2, 1] True >>>[2, [1, 4]] < [2, [1, 5]] True
循环
-
for循环
>>>words = ['this', 'is', 'an', 'ex', 'parrot'] >>>for word in words: ... print(word) >>>for number in range(1, 101): print(number) >>>d = {'x':1, 'y':2, 'z':3} >>>for key in d: ... print(key, 'corresponds to', d[key]) ... x corresponds to 1 y corresponds to 2 z corresponds to 3 # 序列解包 >>>for key, value in d.items(): ... print(key, 'corresponds to', value) ... x corresponds to 1 y corresponds to 2 z corresponds to 3 # 使用zip >>>list(zip(names, ages)) [('anne', 12), ('beth', 45), ('george', 32), ('damon', 102)] >>>for name, age in zip(names, ages): ... print(name, 'is', age, 'years old') ... anne is 12 years old beth is 45 years old george is 32 years old damon is 102 years old # 使用enumerate for index, string in enumerate(strings): if 'xxx' in string: strings[index] = '[censored]'
-
while循环
>>>x = 1 >>>while x <= 100: ... print(x) ... x += 1 name = '' while not name: name = input('Please enter your name: ') print('Hello, {}!'.format(name))