本节介绍如何在 Python 中使用基本运算符。
算术运算符
就像任何其他编程语言一样,加法、减法、乘法和除法运算符可以与数字一起使用。
number = 1 + 2 * 3 / 4.0
print(number)
试着预测答案会是什么。Python是否遵循操作顺序?
结果:2.5
另一个可用的运算符是模 (%) 运算符,它返回除法的整数余数。被除数 % 除数 = 余数。
remainder = 11 % 3
print(remainder)
结果:2
使用两个乘法符号可建立幂关系。
squared = 7 ** 2
cubed = 2 ** 3
print(squared)
print(cubed)
结果:
49
8
将运算符与字符串一起使用
Python 支持使用加法运算符连接字符串:
helloworld = "hello" + " " + "world"
print(helloworld)
结果:
hello world
Python还支持将字符串相乘以形成具有重复序列的字符串:
lotsofhellos = "hello" * 10
print(lotsofhellos)
结果:
hellohellohellohellohellohellohellohellohellohello
将运算符与列表一起使用
列表可以使用加法运算符连接:
even_numbers = [2,4,6,8]
odd_numbers = [1,3,5,7]
all_numbers = odd_numbers + even_numbers
print(all_numbers)
结果:
[1, 3, 5, 7, 2, 4, 6, 8]
就像在字符串中一样,Python支持使用乘法运算符形成具有重复序列的新列表:
print([1,2,3] * 3)
结果:
[1, 2, 3, 1, 2, 3, 1, 2, 3]
练习(Exercise)
本练习的目标是创建两个名为 x_list 和 y_list 的列表,它们分别包含变量 x 和 y 的 10 个实例。您还需要创建一个名为 big_list 的列表,该列表包含变量 x 和 y,每个变量 10 次,方法是将您创建的两个列表连接起来。
x = object()
y = object()
# 改变这些代码
x_list = [x]
y_list = [y]
big_list = []
print("x_list contains %d objects" % len(x_list))
print("y_list contains %d objects" % len(y_list))
print("big_list contains %d objects" % len(big_list))
# testing code
if x_list.count(x) == 10 and y_list.count(y) == 10:
print("Almost there...")
if big_list.count(x) == 10 and big_list.count(y) == 10:
print("Great!")