习题 5:更多的变量和打印

 


  我们现在要键入更多的变量并且把它们打印出来。这次我们将使用一个叫 “格式化字符串”(format string)的东西。每一次你使用双引号(")把一些文本括起来,就创建了一个字符串。字符串是程序向人展示信息的方式。你可以打印它们,可以将它们存入文件,还可以将它们发送给 Web 服务器,很多事情都是通过字符串交流实现的。

  字符串是非常好用的东西,所以在这个习题中你将学会如何创建嵌入变量内容的字符串。要在字符串里嵌入变量,你需要使用 { } 特殊符号,把变量放到里边。你的字符串还必须以 f引号 } 的组合相当于告诉 Python:“ 嘿,这是一个格式化字符串,把这些变量放到那几个位置。”

  和之前一样,即使你读不懂这些内容,只要一字不差地录入就可以了。


 ex5.py

# 我的名字 'Zed A. Shaw'
my_name = 'Zed A. Shaw'
# 我的年龄 35岁
my_age = 35 # not alie(不真实,假的)
# 我的身高 74英寸
my_height = 74 # inches(英寸)
# 我的体重 180磅
my_weight = 180 # lbs(是英文pounds(磅) )
# 我的眼睛 蓝色
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} my_hair.")
print(f"His teeth are usually {my_teeth} depending on the coffee.")

# this line is tricky, try to get it exactly rigth
total = my_age + my_height + my_weight
print(f"If I add {my_age}, {my_height}, and {my_weight} I get {total}.")

 结果:

  巩固练习

修改所有变量的名字,把他们前面的 my_ 去掉。确认每一个地方都改掉,不只是使用 = 设置的地方。

# 名字 'Zed A. Shaw'
name = 'Zed A. Shaw'
# 年龄 35岁
age = 35 # not alie(不真实,假的)
# 身高 74英寸
height = 74 # inches(英寸)
# 体重 180磅
weight = 180 # lbs(是英文pounds(磅) )
# 眼睛 蓝色
eyes = 'Blue'
# 牙齿 白色
teeth = 'white'
# 头发 棕色
hair = 'Brown'

print(f"Let's talk about {name}.")
print(f"He's {height} inches tall.")
print(f"He's {weight} pounds heavy.")
print("Actually that's not too heavy.")
print(f"He's got {eyes} eyes and {hair} hair.")
print(f"His teeth are usually {teeth} depending on the coffee.")

# this line is tricky, try to get it exactly rigth
# 总计=年龄+身高+体重
total = age + height + weight
# 如果我加上35、74和180,我得到289。
print(f"If I add {age}, {height}, and {weight} I get {total}.")

 结果:

  常见问题

  • 变量名命名规则

Python 需要使用标识符给变量命名,其实标识符就是用于给程序中变量、函数、类、方法命名的符号(简单来说,标识符就是合法的名字)。(注意不要与关键字重名 

#导入keyword 模块
import keyword
#显示所有关键字
keyword.kwlist

 Python 语言的标识符必须以字母、下画线(_)开头,后面可以跟任意数目的字母、数字和下画线(_)。此处的字母并不局限于 26 个英文字母,可以包含中文字符、日文字符等。(注意 Python 中的 标识符 是 区分大小写的,如:Andy !=  andy

如:

合法的:abc,abc_xyz,asd123

不合法:1abc,asd#qaz

  • 如何将浮点数四舍五入

可以使用 round( ) 函数,如round(17.333) 。

posted @ 2019-09-03 11:48  小皮卡  阅读(249)  评论(0编辑  收藏  举报