寒假打卡17-2月3日
Python 基础语法
在本篇文章中,我们将介绍 Python 的基础语法,包括变量和数据类型、条件判断与循环、列表推导式与字典推导式,以及函数定义与参数传递。这些基础知识将帮助你快速上手 Python 编程。
1. 变量与数据类型
变量
在 Python 中,变量不需要事先声明,直接赋值即可使用。变量名应该具有描述性,并遵循命名规范。
# 变量赋值
name = "Alice"
age = 25
height = 1.68
数据类型
Python 提供了多种内置数据类型,包括字符串、整数、浮点数、列表、字典、元组和集合等。
字符串
# 字符串
greeting = "Hello, World!"
print(greeting)
整数与浮点数
# 整数与浮点数
x = 10
y = 3.14
print(x + y) # 输出: 13.14
列表
# 列表
fruits = ["apple", "banana", "cherry"]
print(fruits[0]) # 输出: apple
字典
# 字典
person = {"name": "Alice", "age": 25}
print(person["name"]) # 输出: Alice
元组
# 元组
coordinates = (10.0, 20.0)
print(coordinates[0]) # 输出: 10.0
集合
# 集合
numbers = {1, 2, 3, 4, 5}
print(3 in numbers) # 输出: True
2. 条件判断与循环
条件判断
使用 if
、elif
和 else
进行条件判断。
age = 25
if age < 18:
print("Minor")
elif 18 <= age < 65:
print("Adult")
else:
print("Senior")
循环
for 循环
# for 循环
for fruit in fruits:
print(fruit)
while 循环
# while 循环
count = 0
while count < 5:
print(count)
count += 1
3. 列表推导式与字典推导式
列表推导式
列表推导式是一种简洁的生成列表的方式。
# 列表推导式
squares = [x**2 for x in range(10)]
print(squares) # 输出: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
字典推导式
字典推导式是一种简洁的生成字典的方式。
# 字典推导式
square_dict = {x: x**2 for x in range(10)}
print(square_dict)
# 输出: {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
4. 函数定义与参数传递
函数定义
使用 def
关键字定义函数。
# 函数定义
def greet(name):
return f"Hello, {name}!"
print(greet("Alice")) # 输出: Hello, Alice!
参数传递
函数支持位置参数、关键字参数和默认参数。
# 位置参数
def add(a, b):
return a + b
print(add(2, 3)) # 输出: 5
# 关键字参数
def introduce(name, age):
return f"My name is {name} and I am {age} years old."
print(introduce(age=25, name="Bob")) # 输出: My name is Bob and I am 25 years old.
# 默认参数
def power(x, n=2):
return x**n
print(power(3)) # 输出: 9
print(power(3, 3)) # 输出: 27
总结
在本篇文章中,我们介绍了 Python 的基础语法,包括变量和数据类型、条件判断与循环、列表推导式与字典推导式,以及函数定义与参数传递。这些基础知识将帮助你快速上手 Python 编程,并为后续的学习打下坚实的基础。接下来,我们将探讨 Python 面向对象编程(OOP)的相关内容,敬请期待!