在ex4中,已经知道了什么是变量以及如何定义及使用变量,在接下来的这些习题中,一直到ex10,都会不断完善你对于变量和打印的认识和理解。
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
my_name = "Zed A. Shaw"
my_age = 35 # not a lie
my_height = 74 # inches
my_weight = 180 # lbs
my_eyes = "Blue"
my_teeth = "White"
my_hair = "Brown"
print(f"Let's talk about {my_name}.")
print(f"He's {my_height} inches tall.")
print(f"He's {my_weight} pounds heavy.")
print("Actually that's not too heavy.")
print(f"He's got {my_eyes} eyes and {my_hair} hair.")
print(f"His teeth are usually {my_teeth} depending on the coffee.")
# this line is tricky, try to get it exactly right
total = my_age + my_height + my_weight
print(f"If I add {my_age}, {my_height}, and {my_weight} I get {total}.")
上面这段程序,一眼看过去,发现出现了前面没有见到过的语法,print函数中,出现f,这里的f是format的缩写,即格式化的意思。语法格式为f"Hello {var}", f、引号、{}和变量名称组成的语句告诉Python解释器:“这是一个格式化的字符串,把指定变量放到指定位置”。
运行结果如下:
小结
-
print(f"Hello {var}")
语法。