Python Basics: Variables, Data Types, Control Flow, Functions, and More
This guide introduces Python fundamentals, covering variable declaration, common data types, conditional statements, loops, functions, list comprehensions, exception handling, classes, generators, decorators, and module imports, each illustrated with clear code examples for beginners.
1️⃣ Variable Declaration and Assignment
Python variables are created by simple assignment without prior declaration.
# Python中变量无需提前声明,直接赋值即可
age = 25 # 声明并初始化整型变量
name = "Alice" # 声明并初始化字符串变量
is_student = True # 声明并初始化布尔型变量2️⃣ Data Types
Python supports lists, tuples, and dictionaries among other built‑in types.
# Python支持多种数据类型,如列表、元组、字典
fruits = ['apple', 'banana', 'cherry'] # 列表
coordinates = (40.7128, -74.0060) # 元组
person_info = {'name': 'Tom', 'age': 30, 'city': 'New York'} # 字典3️⃣ Conditional Statements and Loops
Use if…elif…else for branching and for / while for iteration.
# if...elif...else...
score = 85
if score >= 90:
print("优秀")
elif score >= 80:
print("良好")
else:
print("需加油")
# for loop over a list
for fruit in fruits:
print(fruit)
# while loop
i = 0
while i < len(fruits):
print(fruits[i])
i += 14️⃣ Function Definition and Call
# 定义一个函数
def greet(name):
return f"Hello, {name}!"
# 调用函数
print(greet("World")) # 输出: Hello, World!5️⃣ List Comprehension
# 列表推导式快速生成新列表
squares = [x**2 for x in range(1, 6)]
print(squares) # 输出: [1, 4, 9, 16, 25]6️⃣ Exception Handling
try:
age = int(input("请输入您的年龄:"))
print(age)
except ValueError:
print("输入错误,请确保输入的是数字!")7️⃣ Classes and Objects
# 定义一个简单的Person类
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
# 创建Person对象并访问属性
p = Person("Bob", 30)
print(p.name) # 输出: Bob
print(p.age) # 输出: 308️⃣ Iterators and Generator Expressions
# 生成器表达式
gen_numbers = (x for x in range(1, 6))
for num in gen_numbers:
print(num)
# 使用next()获取生成器的下一个值
gen = (x for x in range(10))
print(next(gen)) # 输出: 09️⃣ Decorators
# 定义一个装饰器,用于计算函数执行时间
import time
def timer_decorator(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
print(f"{func.__name__}执行耗时:{end_time - start_time}秒")
return result
return wrapper
@timer_decorator
def long_running_task():
time.sleep(2)
long_running_task()🔟 Module Import and Package Management
# 导入标准库math模块
import math
print(math.sqrt(16)) # 输出: 4.0
# 导入模块中特定函数或变量
from math import sqrt
print(sqrt(16)) # 输出: 4.0By practicing these snippets, readers can solidify their understanding of Python's core concepts and build a strong foundation for more advanced programming tasks.
Test Development Learning Exchange
Test Development Learning Exchange
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.