Python 语法基础:print、变量与类型

☰ 成为合作伙伴

Python 学习笔记

Python 语法基础:print、变量与类型

一篇适合初学者的 Python 笔记,介绍 print()、注释、变量命名、基础类型,以及做数学运算前如何转换输入。

分享这篇文章

复制链接、使用手机分享、用微信扫码,或通过邮件发送。

邮箱

Python 学习笔记

当学生理解了为什么 Python 适合作为第一门语言之后,下一步就是学会阅读一个小型 Python 程序而不迷失。语法不只是标点和格式,它是程序结构的外在表现,告诉我们程序正在做什么。

Start with print()

The first useful Python command is usually print(). It sends a value to the screen so we can see what the program is doing.

print("Hello World")
print("CP Club", "Python", "Practice")

For beginners, print() is more than output. It is also a simple debugging tool. When a program feels confusing, printing intermediate values can help students check what is happening step by step.

用注释解释你的思路

Python ignores anything after # on the same line. That makes comments useful for explaining intent.

# This prints a greeting
print("Hello World")

好的注释应该解释代码为什么存在,而不是简单重复代码本身已经表达的内容。

变量为想法命名

变量用来保存一个值,方便之后重复使用。清晰的变量名会让程序更容易阅读。

student_score = 86
bonus_points = 4
final_score = student_score + bonus_points
print(final_score)

Python variable names are case-sensitive, so score and Score are different names. In student code, it is better to use lowercase words separated by underscores, also called snake case.

Python 会推断类型

Python 是动态类型语言。学生在给变量赋值之前,不需要先声明变量类型。

age = 12
name = "Ava"
is_ready = True

print(type(age))
print(type(name))
print(type(is_ready))

这种灵活性很有帮助,但也意味着学生需要留意每个变量里保存的是什么类型的值。

做数学运算前先转换输入

User input arrives as text. If we want to do arithmetic, we usually need to convert it with int() or float().

first_score = int(input())
second_score = int(input())
average = (first_score + second_score) / 2
print(average)

这是 Python 初学阶段最常见的错误之一:把输入字符串当成数字直接相加。

练习提示

写一个小程序,完成以下任务:

  1. Reads a student’s name.
  2. 读取两次小测成绩。
  3. 把成绩转换为整数。
  4. Prints a sentence with the student’s average score.

关键收获

初学语法应该通过阅读和小实验来掌握。先养成几个可靠习惯:打印值、清晰命名变量、困惑时检查类型、做数学运算前转换输入。

有问题或建议?

如果你对本文有疑问,或希望提出改进建议,请给我们发送私密留言。

发送反馈
返回资源库
滚动至顶部