English· Español· Deutsch· Nederlands· Français· 日本語· ქართული· 繁體中文· 简体中文· Português· Русский· العربية· हिन्दी· Italiano· 한국어· Polski· Svenska· Türkçe· Українська· Tiếng Việt· Bahasa Indonesia

nu

guest
1 / ?
back to lessons

欢迎

Anatomy of a Python print() statement: function name, parentheses, and string argument labeled

欢迎来到你的第一节 Python 课程。

Python 是世界上最受欢迎的编程语言之一。科学家、工程师、艺术家和学生每天都在使用它。

在本课中,你将编写真实的 Python 代码并立即运行它。你的代码在真实服务器上执行——不是模拟。

让我们从计算机中最著名的程序开始。

Hello, World!

你的第一个程序

每个程序员的旅程都从相同的两个词开始:Hello, World!

在 Python 中,你使用 print() 函数将文本打印到屏幕上:

print("Hello, World!")


就这样。一行。引号告诉 Python 这是文本(称为 字符串)。print() 函数将其发送到屏幕。

编写一个 Python 程序,精确打印:Hello, World!

什么是变量?

Variables as labeled boxes in memory: string box labeled name, integer box labeled age

变量:为值赋予名称

变量是一个保存值的名称。把它想象成一个标记的盒子。

name = "Ada"

age = 12

print(name) — 打印:Ada

print(age) — 打印:12


= 号表示赋值——把右边的值放入左边的名称。

文本放在引号中(一个字符串)。数字不需要引号(一个整数)。

创建变量

轮到你了

创建两个变量并打印它们:

1. 一个名为 animal 的变量,设置为你最喜欢的动物

2. 一个名为 count 的变量,设置为它有多少条腿

3. 打印两个变量


示例输出(你的会不同):

cat

4

创建名为 `animal` 和 `count` 的变量,然后打印两者。你的代码应输出两行。

合并字符串

f-string anatomy: f prefix, literal text, and {variable} placeholder each labeled

字符串连接

你可以使用 + 将字符串连接在一起:

greeting = "Hello" + " " + "World"

print(greeting) — 打印:Hello World


f 字符串(格式化字符串)

将变量混合到文本中的更好方式:

name = "Ada"

print(f"My name is {name}") — 打印:My name is Ada


引号前的 f 激活 f 字符串模式。在字符串中,{variable} 被替换为变量的值。

f 字符串练习

轮到你了

创建两个变量:

- food — 你最喜欢的食物(一个字符串)

- rating — 你对它的评分,从 1 到 10(一个整数)


然后使用 f 字符串打印:

I love pizza! I rate it 9 out of 10.

(用你自己的食物和评分)

创建 `food` 和 `rating` 变量,然后使用 f 字符串打印一个句子,其中包括两者。你的输出应为一个句子。

If / Else

if/else control flow diagram: condition diamond with True/False branches, comparison operators table

做出决定

程序可以使用 ifelse 做出选择:


temperature = 35

if temperature > 30:

print("It is hot!")

else:

print("It is not hot.")


if 下的缩进代码仅在条件为 True 时运行。

else 下的代码在条件为 False 时运行。


比较运算符:> (大于)、< (小于)、== (等于)、!= (不等于)、>=<=

If/Else 挑战

轮到你了

编写一个程序,其中:

1. 创建一个名为 score 的变量,设置为任何数字

2. 如果 score 是 60 或以上,打印 Pass

3. 否则,打印 Fail

编写一个 if/else 程序,带有 `score` 变量。如果 score >= 60,打印 `Pass`,否则打印 `Fail`。

综合运用

最终挑战

你现在知道:print()、变量、f 字符串和 if/else

在一个程序中将它们全部结合起来。


编写一个程序,其中:

1. 创建一个名为 name 的变量(一个名字,一个字符串)

2. 创建一个名为 age 的变量(一个年龄,一个整数)

3. 如果 age 是 13 或以上,打印:Welcome, [name]! You may enter.

4. 否则,打印:Sorry, [name]. You must be 13 to enter.


对输出使用 f 字符串。

编写上述完整程序。将变量、f 字符串和 if/else 一起使用。