1. 变量
在 Python 中,创建变量不需要声明其类型,直接赋值即可。Python 是动态类型语言,这意味着你可以在运行时更改变量的类型。
创建变量
x = 5 # 整数
y = "Hello" # 字符串
z = 3.14 # 浮点数
AI助手
打印变量
print(x, y, z) # 输出: 5 Hello 3.14
AI助手
2. 数据类型
Python 支持多种内置的数据类型,包括但不限于以下几种:
数字(Numbers):整型 int、浮点型 float 和复数 complex。
字符串(Strings):用单引号 ’ 或双引号 " 包围的一系列字符。
列表(Lists):有序且可变的集合,允许重复成员。
元组(Tuples):有序但不可变的集合。
字典(Dictionaries):无序的键值对集合。
集合(Sets):无序且不重复的元素集合。
数字类型
a = 10 # int
b = 3.14 # float
c = 1 + 2j # complex
AI助手
字符串
name = "Alice"
AI助手
列表
fruits = ["apple", "banana", "cherry"]
AI助手
元组
coordinates = (10.0, 20.0)
AI助手
字典
person = {"name": "Bob", "age": 30}
AI助手
集合
colors = {"red", "green", "blue"}
AI助手
3. 条件语句
使用 if、elif 和 else 关键字来实现条件逻辑。
x = 10
if x > 0:
print("x 是正数")
elif x == 0:
print("x 是零")
else:
print("x 是负数")
AI助手
4. 循环
Python 提供了两种主要的循环结构:for 和 while。
for 循环
用于遍历序列(如列表、元组、字符串等)或其他可迭代对象。
使用 for 循环遍历列表
for fruit in fruits:
print(fruit)
AI助手
使用 range() 函数生成整数序列
for i in range(5): # 从 0 到 4
print(i)
while 循环
AI助手
当给定条件为真时重复执行代码块。
count = 0
while count < 5:
print(count)
count += 1
AI助手
5. 函数
函数是组织好的、可重用的代码块,用来实现单一或相关联的功能。
定义函数
使用 def 关键字定义函数,并可以指定参数和返回值。
def greet(name):
"""打印问候信息"""
print(f"Hello, {name}!")
greet("Alice") # 调用函数
AI助手
返回值
函数可以通过 return 语句返回一个值。
def add(a, b):
"""返回两个数相加的结果"""
return a + b
result = add(3, 5)
print(result) # 输出: 8
AI助手
默认参数
你可以为函数参数设置默认值,这样调用时如果未提供该参数,则使用默认值。
def greet(name="World"):
print(f"Hello, {name}!")
greet() # 使用默认值
greet("Alice") # 提供参数
AI助手
关键字参数
调用函数时可以使用关键字参数来明确指定参数名及其对应的值。
def describe_pet(animal_type, pet_name):
print(f"I have a {animal_type}, and its name is {pet_name}.")
describe_pet(animal_type="hamster", pet_name="Harry")
AI助手
可变参数
使用 *args 接受任意数量的位置参数,使用 **kwargs 接受任意数量的关键字参数。
def make_pizza(*toppings):
print("制作披萨,添加配料:")
for topping in toppings:
print(f"- {topping}")
make_pizza("pepperoni", "mushrooms", "extra cheese")
def build_profile(first, last, **user_info):
profile = {'first_name': first, 'last_name': last}
profile.update(user_info)
return profile
user_profile = build_profile('albert', 'einstein', location='princeton', field='physics')
print(user_profile)
AI助手
总结
以上内容涵盖了 Python 编程的基础语法要素。通过理解和掌握这些概念,你可以开始编写简单的 Python 程序,并逐步构建更复杂的应用程序。如果你有更多具体的问题或需要进一步的帮助,请随时提问!
【推荐自动化测试教程】:
【软件测试教程】从零开始学自动化测试(2024实用版)自动化测试2024最全面教程!!!_哔哩哔哩_bilibili
如果我的博客对你有帮助、如果你喜欢我的博客内容,请 “点赞” “评论” “收藏” 一键三连哦!
最后: 下方这份完整的软件测试视频教程已经整理上传完成,需要的朋友们可以自行领取【保证100%免费】