1. 条件语句
条件语句用于根据条件执行不同 code块. Python3supportif, elif and else语句来implementation条件判断.
1.1 if 语句
if语句用于执行条件 for 真时 code块.
# if语句example
age = 18
if age >= 18:
print("你已经成年了!")
print("可以参加投票. ")
1.2 if-else 语句
if-else语句用于执行条件 for 真时 code块, 否则执行elsecode块.
# if-else语句example
number = 5
if number > 0:
print("这 is a 正数. ")
else:
print("这不 is a 正数. ")
1.3 if-elif-else 语句
if-elif-else语句用于check many 个条件, 执行第一个 for 真 code块.
# if-elif-else语句example
score = 85
if score >= 90:
print("优秀")
elif score >= 80:
print("良 good ")
elif score >= 60:
print("及格")
else:
print("不及格")
1.4 嵌套条件语句
条件语句可以嵌套using, 即 in 一个条件语句inpackage含另一个条件语句.
# 嵌套条件语句example
number = 10
if number > 0:
if number % 2 == 0:
print("这 is a 正偶数. ")
else:
print("这 is a 正奇数. ")
else:
print("这不 is a 正数. ")
2. 循环语句
循环语句用于重复执行一段code. Python3supportfor循环 and while循环.
2.1 while 循环
while循环会一直执行code块, 直 to 条件 for fake.
# while循环example
count = 1
while count <= 5:
print("Count:", count)
count += 1
print("循环结束!")
2.2 for 循环
for循环用于遍历序列 (such aslist, 元组, stringetc.) in 每个元素.
# for循环example
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# 遍历number范围
for i in range(5):
print(i)
# 遍历string
for char in "Python":
print(char)
2.3 range() function
range()function用于生成一个number序列, 常用于for循环in.
# range()functionexample
# range(stop)
for i in range(5):
print(i) # 输出: 0, 1, 2, 3, 4
# range(start, stop)
for i in range(2, 5):
print(i) # 输出: 2, 3, 4
# range(start, stop, step)
for i in range(0, 10, 2):
print(i) # 输出: 0, 2, 4, 6, 8
2.4 break and continue 语句
break语句用于跳出循环, continue语句用于跳过当 before 循环 剩余部分, 继续 under 一次循环.
# break语句example
for i in range(10):
if i == 5:
break
print(i)
print("循环in断!")
# continue语句example
for i in range(10):
if i % 2 == 0:
continue
print(i)
实践case: 猜number游戏
writing一个猜number游戏, 程序应该:
- 生成一个1 to 100之间 随机数
- 让user猜number
- 根据user 猜测给出提示 (太 big , 太 small or 正确)
- 直 to user猜in for 止
# 猜number游戏
import random
# 生成随机数
secret_number = random.randint(1, 100)
# 猜number
while True:
guess = int(input("请猜一个1 to 100之间 number: "))
if guess < secret_number:
print("太 small 了!")
elif guess > secret_number:
print("太 big 了!")
else:
print("恭喜你, 猜 for 了!")
break
3. function
function is 一段 reusable code块, 用于执行specific task. Python3usingdef关键字定义function.
3.1 function定义
usingdef关键字定义function, after 跟function名 and 括号in parameter.
# function定义example
def greet():
"""打印问候语"""
print("Hello, World!")
# 调用function
greet()
# 带parameter function
def greet_name(name):
"""打印带名字 问候语"""
print(f"Hello, {name}!")
# 调用带parameter function
greet_name("Python")
3.2 functionreturn value
usingreturn语句 from functioninreturn value.
# 带return value function
def add(a, b):
"""计算两个数 and """
return a + b
# 调用带return value function
result = add(5, 3)
print("结果 is : ", result)
# 返回 many 个值
def calculate(a, b):
"""计算两个数 and and 差"""
return a + b, a - b
# 接收 many 个return value
sum_result, diff_result = calculate(10, 4)
print(" and : ", sum_result)
print("差: ", diff_result)
3.3 默认parameter
function可以 has 默认parameter, 当调用function时不providing该parameter时, using默认值.
# 默认parameterexample
def greet(name, greeting="Hello"):
"""打印带问候语 message"""
print(f"{greeting}, {name}!")
# using默认parameter
greet("Python") # 输出: Hello, Python!
# 覆盖默认parameter
greet("Python", "Hi") # 输出: Hi, Python!
3.4 关键字parameter
using关键字parameter可以指定parameter名, 这样可以不按顺序传递parameter.
# 关键字parameterexample
def describe_person(name, age, city):
"""describes一个人"""
print(f"Name: {name}")
print(f"Age: {age}")
print(f"City: {city}")
# using关键字parameter
describe_person(name="Alice", age=30, city="New York")
# 混合using位置parameter and 关键字parameter
describe_person("Bob", city="London", age=25)
3.5 可变parameter
using*args接收任意数量 位置parameter, using**kwargs接收任意数量 关键字parameter.
# 可变parameterexample
def sum_numbers(*args):
"""计算任意数量number and """
return sum(args)
# 调用可变parameterfunction
print(sum_numbers(1, 2, 3)) # 输出: 6
print(sum_numbers(1, 2, 3, 4, 5)) # 输出: 15
# 关键字可变parameter
def print_info(**kwargs):
"""打印任意关键字parameter"""
for key, value in kwargs.items():
print(f"{key}: {value}")
# 调用关键字可变parameterfunction
print_info(name="Python", version=3, type="programming language")
互动练习: function练习
4. 递归function
递归function is 调用自身 function, 常用于解决可以分解 for 相同子issues issues.
# 递归functionexample: 计算阶乘
def factorial(n):
"""计算n 阶乘"""
if n == 0:
return 1
else:
return n * factorial(n-1)
# 调用递归function
print(factorial(5)) # 输出: 120
# 递归functionexample: 计算斐波那契数列
def fibonacci(n):
"""计算第n个斐波那契数"""
if n <= 1:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
# 调用递归function
print(fibonacci(10)) # 输出: 55