这一章我们不做太多「高深」的事,只做三件最基础、却最关键的事:搞清楚 为什么 选 Python、把运行环境装好、写下第一行能跑起来的代码,并理解变量与数据类型。
一句话:Python 让你把注意力放在「解决问题」上,而不是「和语法较劲」上。这正是码上问学想要的——先理解思路,再写代码。
print("你好,码上问学")
print("我要开始学 Python 了")
name = "张三" # 字符串,用引号包起来
age = 20 # 整数
height = 1.78 # 浮点数(带小数)
is_student = True # 布尔值:真 / 假
print(name, "今年", age, "岁,身高", height, "米")
Python 看到不同“长相”的数据,会自动归到不同的类型。类型决定了“它能做什么运算”。分清类型,是后面不出 bug 的关键。
print(type("文字")) # <class 'str'> 字符串
print(type(10)) # <class 'int'> 整数
print(type(3.14)) # <class 'float'> 浮点数
print(type(True)) # <class 'bool'> 布尔值
print(type([1, 2, 3])) # <class 'list'> 列表(后面第2章细讲)
print(type({"a": 1})) # <class 'dict'> 字典(后面第2章细讲)
# 类型之间可以“变身”
print(int("10") + 5) # 字符串 "10" 转成整数 10,结果 15
print(str(3.14)) # 数字转字符串 "3.14"
price = "12" # 从网页或文件读来的价格,常常是字符串
qty = 3
# 想算总价,必须先把字符串转成数字
total = int(price) * qty
print("单价", price, "元,买了", qty, "件,共", total, "元")
# 经典坑:字符串和数字不能直接相加,会被拦下来
try:
print("年龄:" + 20)
except TypeError as e:
print("报错:", e)
把前面零散的知识合成一个小程序:用一组变量描述一个人,再整齐地打印出来。
name = "李华"
city = "北京"
age = 22
skills = ["Python", "Excel", "写作"]
print("=== 个人信息卡 ===")
print("姓名:", name)
print("城市:", city)
print("年龄:", age)
print("技能:", "、".join(skills)) # 用顿号把列表拼成一句话
1定义变量 city 存你的城市、temp 存一个温度数字,用一行 print 输出“城市 + 今天 + 温度 + 度”。
2下面这行会报错还是正常?print("2" + 3) 想正确输出 23,改一行就行。
提示:练习 1 用逗号分隔多项最省心;练习 2 把数字用 str() 转成字符串再拼接。先自己写,再点开下面参考。
city = "北京"
temp = 26
print(city, "今天", temp, "度")
# 练习 2:先把数字转成字符串再拼
print("2" + str(3))