magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
print(f"I can't wait to see your next trick, {magician.title()}.\n")
Python根据缩进来判断代码行与前一个代码行的关系。如果你不小心缩进了无须缩进的代码行,Python将指出这一点。
for语句末尾的冒号告诉Python,下一行是循环的第一行。如果不小心遗漏了冒号,将导致语法错误。
列表非常适合用于存储数字集合,而Python提供了很多工具,可帮助你高效地处理数字列表。
Python函数range()让你能够轻松地生成一系列数。
for value in range(1, 5):
print(value)
1
2
3
4
numbers = list(range(1, 6))
print(numbers) // [1, 2, 3, 4, 5]
// 在这个示例中,函数range()从2开始数,然后不断加2,直到达到或超过终值
even_numbers = list(range(2, 11, 2))
print(even_numbers) // [2, 4, 6, 8, 10]
// 创建一个列表,其中包含前10个整数(1~10)的平方
squares = []
for value in range(1, 11):
square = value ** 2
squares.append(square)
print(squares) // [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
>>> digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> min(digits)
0
>>> max(digits)
9
>>> sum(digits)
45
squares = [value**2 for value in range(1, 11)]
print(squares) // [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[0:3]) // ['charles', 'martina', 'michael']
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[:4]) // ['charles', 'martina', 'michael', 'florence']
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[2:]) // ['michael', 'florence', 'eli']
players = ['charles', 'martina', 'michael', 'florence', 'eli']
print(players[-3:]) // ['michael', 'florence', 'eli']
for player in players[:3]:
print(player.title())
my_foods = ['pizza', 'falafel', 'carrot cake']
friend_foods = my_foods[:]
friend_foods.append('ice cream')
# 这行不通:
friend_foods = my_foods
my_foods.append('cannoli')
friend_foods.append('ice cream')
print(my_foods) // ['pizza', 'falafel', 'carrot cake', 'cannoli', 'ice cream']
列表非常适合用于存储在程序运行期间可能变化的数据集。
Python将不能修改的值称为不可变的,而不可变的列表被称为元组。
元组看起来很像列表,但使用圆括号而非中括号来标识。定义元组后,就可使用索引来访问其元素,就像访问列表元素一样。
dimensions = (200, 50)
print(dimensions[0])
print(dimensions[1])
my_t = (3,)
dimensions = (200, 50)
for dimension in dimensions:
print(dimension)
dimensions = (200, 50)
print("Original dimensions:")
for dimension in dimensions:
print(dimension)
dimensions = (400, 100)
print("\nModified dimensions:")
for dimension in dimensions:
print(dimension)
如果需要存储的一组值在程序的整个生命周期内都不变,就可以使用元组。
要提出Python语言修改建议,需要编写Python改进提案(Python Enhancement Proposal,PEP)。PEP 8是最古老的PEP之一,向Python程序员提供了代码格式设置指南。