查看全部 Python3 基础教程
if
>>> x = int(input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
... x = 0
... print('Negative changed to zero')
... elif x == 0:
... print('Zero')
... elif x == 1:
... print('Single')
... else:
... print('More')
...
More
elif
可能有零个或多个,else
部分是可选的。elif
是 else if
的缩写,这避免了过度缩进。if … elif … elif …
序列用于替代其他语言中的 switch
或 case
语句。
while
输出 Fibonacci 数列:
>>> # Fibonacci series:
... # the sum of two elements defines the next
... a, b = 0, 1
>>> while a < 10:
... print(a)
... a, b = b, a+b
...
0
1
1
2
3
5
8
示例包括以下特点:
- 多个变量可以同时分别赋值,赋值前先运算右边表达式(从左到右)。
- 与 C 类似,Python 中任何非零值都为
true
,零为false
。条件表达式还可以是字符串或列表,实际上可以是任何序列类型,序列长度非零为true
,空序列为false
。标准比较操作符与 C 中一致。 - 循环体是缩进的,缩进是 Python 中语句分组的方式。在交互提示符位置,可以为每个缩进行输入一个 tab 或多个空格。当在交互模式下输入一个复合语句时,必须以一个空行表示输入结束。注意基本语句块中的每一行的缩进数量必须相同。
print()
函数可以同时输出多个表达式,输出字符串时没有引号,多个输出项之间有空格。例如
参数>>> i = 256*256 >>> print('The value of i is', i) The value of i is 65536
end
用于避免输出结束后换行,或以一个不同的字符串结束输出。>>> a, b = 0, 1 >>> while a < 1000: ... print(a, end=',') ... a, b = b, a+b ... 0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,
for
Pascal 中的迭代总是基于数字的算术过程,C 中的迭代由用户给定迭代步骤和中止条件,而 Python 的 for
语句依据任意序列(列表或字符串)中的子项,按它们在序列中的顺序来进行迭代。
>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print(w, len(w))
...
cat 3
window 6
defenestrate 12
在迭代过程中修改集合可能会引发错误,通常更直接的方式是迭代一个集合副本或创建一个新集合。
# Strategy: Iterate over a copy
for user, status in users.copy().items():
if status == 'inactive':
del users[user]
# Strategy: Create a new collection
active_users = {}
for user, status in users.items():
if status == 'active':
active_users[user] = status
range() 函数
内置函数 range()
用于生成一个等差数值序列。
>>> for i in range(5):
... print(i)
...
0
1
2
3
4
range(10)
会生成一个包含 10 个元素的列表,但不包含终点值 10。可以指定 range
的起始值和步长,步长可以为负数。
range(5, 10)
5, 6, 7, 8, 9
range(0, 10, 3)
0, 3, 6, 9
range(-10, -100, -30)
-10, -40, -70
需要迭代列表索引的话,可以结合使用 range()
和 len()
。
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print(i, a[i])
...
0 Mary
1 had
2 a
3 little
4 lamb
range()
返回的对象实际上不是一个列表,而是一个可以迭代的对象,这样节省空间。
>>> print(range(10))
range(0, 10)
可以用 list()
从 range()
获取列表。
>>> list(range(4))
[0, 1, 2, 3]
for
语句是一种迭代结构,sum()
函数是一个迭代函数。
>>> sum(range(4)) # 0 + 1 + 2 + 3
6
循环中的 break、continue、else
break
语句和 C 中的类似,用于跳出最近的一级 for
或 while
循环。
循环可以有一个 else
子句,它在 for
循环迭代完整个列表或 while
循环执行条件为 false
时执行,但循环被 break
中止的情况下不会执行。
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else: # else belongs to for loop
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
与
if
语句中的else
子句相比,循环中的else
子句更像try
语句中的else
子句。
try
语句中的else
子句在没有异常发生时运行;循环中的else
子句在没有break
发生时运行。
continue
语句是从 C 中借鉴来的,表示循环继续执行下一次迭代。
>>> for num in range(2, 10):
... if num % 2 == 0:
... print("Found an even number", num)
... continue
... print("Found an odd number", num)
Found an even number 2
Found an odd number 3
Found an even number 4
Found an odd number 5
Found an even number 6
Found an odd number 7
Found an even number 8
Found an odd number 9
pass 语句
pass
语句什么也不做,用于在句法上必须要有但是程序上什么都不用做的情况。
>>> while True:
... pass # Busy-wait for keyboard interrupt (Ctrl+C)
...
通常用于创建最小类。
>>> class MyEmptyClass:
... pass
...
新开发代码时,pass
还能用于函数或条件体中的占位符,方便抽象代码,这里 pass
会被忽略。
>>> def initlog(*args):
... pass # Remember to implement this!
...