and和or的短路逻辑
从左往右,只有当第一个操作数的值无法确定逻辑运算的结果时,才对第二个操作数进行求值。
运算符优先级
流程图
循环
while语句
continue break pass
(for语句同样可使用)
for letter in 'Python':
if letter == 'h':
pass
print '这是 pass 块'
print '当前字母 :', letter
结果:
当前字母 : P
当前字母 : y
当前字母 : t
这是 pass 块
当前字母 : h
当前字母 : o
当前字母 : n
while…else…
count = 0
while count < 5:
print count, " is less than 5"
count = count + 1
else:
print count, " is not less than 5"
结果:
0 is less than 5
1 is less than 5
2 is less than 5
3 is less than 5
4 is less than 5
5 is not less than 5
for语句
代码:
for letter in "python":
print(letter)
结果:
p
y
t
h
o
n
代码:
fruits = ['apple', 'banana', 'watermelon', 'peer', 'grapes']
for fruit in fruits:
print(fruit)
或使用序列索引:
for index in range(len(fruits)):
print(fruits[index])
结果:
apple
banana
watermelon
peer
grapes
for…else…
for num in range(10,20):
for i in range(2,num):
if num%i == 0:
print('%d = %d * %d' % (num, i, num/i))
break
else: print ('%d is a special number!' % (num))
结果:
10 = 2 * 5
11 is a special number!
12 = 2 * 6
13 is a special number!
14 = 2 * 7
15 = 3 * 5
16 = 2 * 8
17 is a special number!
18 = 2 * 9
19 is a special number!
range()生成数字序列
- range(stop) - 从 0 开始,到 stop(不包含)的整数数列
- range(start, stop) - 从 start 开始,到 stop(不包含)的整数数列
- range(start, stop, step) - 从start 开始,到 stop(不包含)结束,步进跨度为 step 的整数数列
循环嵌套
打印九九乘法表:
for num in range(1,10):
for i in range(1,num+1):
print('%d * %d = %d' % (i, num, i*num), end = ' ')
print(' ')