Python基础教程
学习Python编程基础,掌握变量、数据类型、条件语句和循环知识。这些是游玩《The Farmer Was Replaced》编程农场游戏的必备基础知识。
1. 变量 (Variables)
变量是用来存储数据的容器。在Python中,你可以直接给变量赋值,无需声明类型。
# Variable assignment examples
name = "John"
age = 25
height = 1.75
Python会自动识别数据类型:字符串、整数、浮点数等。
2. 数据类型 (Data Types)
Python有以下基本数据类型:
# Data type examples
text = "Hello World" # String
number = 42 # Integer
decimal = 3.14 # Float
is_true = True # Boolean
items = [1, 2, 3] # List
3. 基本运算 (Basic Operations)
Python支持各种数学和逻辑运算:
# Arithmetic operations
a = 10 + 5 # Addition
b = 10 - 3 # Subtraction
c = 10 * 2 # Multiplication
d = 10 / 3 # Division
# Comparison operations
x = 5 > 3 # True
y = 5 < 3 # False
z = 5 == 5 # True
4. 条件语句 (Conditional Statements)
使用if、elif、else来根据条件执行不同的代码块:
age = 18
if age < 18:
print("Underage")
elif age == 18:
print("Just turned adult")
else:
print("Adult")
5. 列表 (Lists)
列表是存储多个项目的有序集合:
# Create a list
fruits = ["Apple", "Banana", "Orange"]
# Access element
first_fruit = fruits[0] # "Apple"
# Add element
fruits.append("Grape")
# Iterate over list
for fruit in fruits:
print(fruit)
6. For循环 (For Loops)
For循环用于遍历序列中的每个元素:
# Iterate over list
animals = ["Dog", "Cat", "Bird"]
for animal in animals:
print("I like", animal)
# Numeric loop
for i in range(5):
print("Number:", i)
7. While循环 (While Loops)
While循环在条件为真时重复执行代码块。这是《The Farmer Was Replaced》中最重要的循环结构:
# Basic while loop
count = 0
while count < 5:
print("Count:", count)
count = count + 1
# Infinite loop (common in games)
while True:
# Get the next action
action = get_next_action()
if action == "Stop":
break
execute_action(action)
8. 函数 (Functions)
函数是可重用的代码块,用于执行特定任务:
# Define function
def greet(name):
return "Hello, " + name + "!"
# Call function
message = greet("Xiao Ming")
print(message)
# Function with multiple parameters
def calculate_area(length, width):
return length * width
area = calculate_area(5, 3)
print("Area:", area)
游戏要求
要开始游玩《The Farmer Was Replaced》,你需要掌握以下核心概念:
- 变量的创建和使用
- 基本数据类型(字符串、数字、布尔值)
- 条件判断(if语句)
- 列表的基本操作
- While循环的使用
- 函数的定义和调用