print
如果需要,可自定义分隔符:print(a,b,sep=" 分隔符 ")
>>> print("I", "wish", "to", "register", "a", "complaint", sep="_")
I_wish_to_register_a_complaint
自定义结束字符串,以替换默认的换行符。例如,如果将结束字符串指定为空字符串,
以后就可继续打印到当前行。
print('Hello,', end=' ')(这代表当前未结束还可以拼接下一个)
print('world!')
上述代码打印
Hello , world! 。
import
导入的方法
import somemodule
from somemodule import somefunction
from somemodule import somefunction, anotherfunction, yetanotherfunction
from somemodule import *
特别的(起别名)
import math as foobar
foobar.sqrt(4)
2.0
下面是一个导入特定函数并给它指定别名的例子:
>>> from math import sqrt as foobar
>>> foobar(4)
2.0
判断语句
普通:
if (条件):
print("xxxx")
else:
print("aaaa")
多重:
if (条件一):
print("xxxx")
elif (条件二):
print("ccccc")
else:
print("aaaa")
多重嵌套:
name = input('What is your name? ')
if name.endswith('Gumby'):
if name.startswith('Mr.'):
print('Hello, Mr. Gumby')
elif name.startswith('Mrs.'):
print('Hello, Mrs. Gumby')
else:
print('Hello, Gumby')
else:
print('Hello, stranger')
还有一个与 if 语句很像的“亲戚”,它就是条件表达式——C语言中三目运算符的Python版本。下面的表达式使用 if 和 else 确定其值:
status = "friend" if name.endswith("Gumby") else "stranger"
如果条件(紧跟在 if 后面)为真,表达式的结果为提供的第一个值(这里为 “friend” ),否则为第二个值(这里为 “stranger” )。
Python比较运算符
x == yx 等于 y
x < yx 小于 y
x > y x 大于 y
x >= y x 大于或等于 y
x <= y x 小于或等于 y
x != y x 不等于 y
x is y x 和 y 是同一个对象
x is not y x 和 y 是不同的对象
x in y x 是容器(如序列) y 的成员
x not in y x 不是容器(如序列) y 的成员
断言
基本上,你可要求某些条件得到满足(如核实函数参数满足要求或为初始测试和调试提
供帮助),为此可在语句中使用关键字 assert 。
>>> age = 10
>>> assert 0 < age < 100
>>> age = -1
>>> assert 0 < age < 100
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError
如果知道必须满足特定条件,程序才能正确地运行,可在程序中添加 assert 语句充当检查点,这很有帮助。还可在条件后面添加一个字符串,对断言做出说明。
>>> age = -1
>>> assert 0 < age < 100, 'The age must be realistic'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AssertionError: The age must be realistic (断言产生的错误提示)
while 循环
为避免前述示例所示的繁琐代码,能够像下面这样做很有帮助:
x = 1
while x <= 100:
print(x)
x += 1
那么如何使用Python来实现的?你猜对了,就像上面那样做。不太复杂,不是吗?你还可以使用循环来确保用户输入名字,如下所示:
name = ''
while not name:
name = input('Please enter your name: ')
print('Hello, {}!'.format(name))
请尝试运行这些代码,并在要求你输入名字时直接按回车键。你会看到提示信息再次出现,因为 name 还是为空字符串,这相当于假。
如果你只是输入一个空格字符(将其作为你的名字),结果将如何呢?试试看。程序将
接受这个名字,因为包含一个空格字符的字符串不是空的,因此不会将 name 视为假。这无疑是这个小程序的一个瑕疵,但很容易修复:只需将 while not name 改为 while not name or name.isspace() 或 while not name.strip() 即可。
for 循环
words = ['this', 'is', 'an', 'ex', 'parrot']
for word in words:
print(word)
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
for number in numbers:
print(number)
Python提供了一个创建范围的内置函数。
>>> range(0, 10)
range(0, 10)
>>> list(range(0, 10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
迭代字典
第一种:
d = {'x': 1, 'y': 2, 'z': 3}
for key in d:
print(key, 'corresponds to', d[key])
第二种:
for key, value in d.items():
print(key, 'corresponds to', value)
并行迭代
有时候,你可能想同时迭代两个序列。假设有下面两个列表:
names = ['anne', 'beth', 'george', 'damon']
ages = [12, 45, 32, 102]
如果要打印名字和对应的年龄,可以像下面这样做:
for i in range(len(names)):
print(names[i], 'is', ages[i], 'years old')
i 是用作循环索引的变量的标准名称。一个很有用的并行迭代工具是内置函数 zip ,它将两个序列“缝合”起来,并返回一个由元组组成的序列。返回值是一个适合迭代的对象,要查看其内容,可使用 list 将其转换为列表。
>>> 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')
函数 zip 可用于“缝合”任意数量的序列。需要指出的是,当序列的长度不同时,函数 zip 将在最短的序列用完后停止“缝合”。
>>> list(zip(range(5), range(100000000)))
[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4)]
迭代时获取索引
解决方案是使用内置函数enumerate
for index, string in enumerate(strings):
if 'xxx' in string:
strings[index] = '[censored]'
这个函数让你能够迭代索引值对,其中的索引是自动提供的。
反向迭代和排序后再迭代
来看另外两个很有用的函数: reversed 和 sorted 。它们类似于列表方法 reverse 和 sort ( sorted接受的参数也与 sort 类似),但可用于任何序列或可迭代的对象,且不就地修改对象,而是返回反转和排序后的版本。
>>> sorted([4, 3, 6, 8, 3])
[3, 3, 4, 6, 8]
>>> sorted('Hello, world!')
[' ', '!', ',', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
>>> list(reversed('Hello, world!'))
['!', 'd', 'l', 'r', 'o', 'w', ' ', ',', 'o', 'l', 'l', 'e', 'H']
>>> ''.join(reversed('Hello, world!'))
'!dlrow ,olleH'
请注意, sorted 返回一个列表,而 reversed 像 zip 那样返回一个更神秘的可迭代对象。你无需关心这到底意味着什么,只管在 for 循环或 join 等方法中使用它,不会有任何问题。只是你不能对它执行索引或切片操作,也不能直接对它调用列表的方法。要执行这些操作,可先使用 list 对返回的对象进行转换。
跳出循环
- break 结束循环
- continue 跳过本次循环,但不结束循环
简单推导
列表推导是一种从其他列表创建列表的方式,类似于数学中的集合推导。列表推导的工作原理非常简单,有点类似于 for 循环。
>>> [x * x for x in range(10)]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
这个列表由 range(10) 内每个值的平方组成,非常简单吧?如果只想打印那些能被3整除的平方值,该如何办呢?可使用求模运算符:如果 y 能被3整除, y 3 % 将返回0(请注意,仅当 x 能被3整除时, x*x 才能被3整除)。为实现这种功能,可在列表推导中添加一条 if 语句。
>>> [x*x for x in range(10) if x%3 == 0]
[0, 9, 36, 81]
还可添加更多的 for 部分。
>>> [(x, y) for x in range(3) for y in range(3)]
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]