1. 变量与数据类型
1.1 变量
# 变量赋值
x = 5
y = "Hello, World!"
1.2 数据类型
# 整数
num_int = 10
# 浮点数
num_float = 3.14
# 字符串
text = "Python"
# 布尔值
is_true = True
2. 运算符
# 算术运算符
a = 5
b = 2
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Exponentiation:", a ** b)
# 比较运算符
print("Equal:", a == b)
print("Not Equal:", a != b)
print("Greater than:", a > b)
print("Less than:", a < b)
print("Greater than or equal:", a >= b)
print("Less than or equal:", a <= b)
3. 控制流结构
3.1 条件语句
x = 10
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
3.2 循环
# for循环
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# while循环
count = 0
while count < 5:
print(count)
count += 1
4. 函数
# 定义函数
def greet(name):
return "Hello, " + name + "!"
# 调用函数
message = greet("Alice")
print(message)
5. 输入与输出
# 输入
name = input("Enter your name: ")
print("Hello, " + name + "!")
# 格式化输出
age = 25
print("My age is {}".format(age))
6. 列表与字典
6.1 列表
fruits = ["apple", "banana", "cherry"]
print("Fruits:", fruits)
print("First fruit:", fruits[0])
6.2 字典
person = {"name": "Alice", "age": 30, "city": "Wonderland"}
print("Person:", person)
print("Name:", person["name"])
这只是Python基础语法的一个简要介绍。要更深入地学习,请查阅官方文档或相关教程。
转载请注明出处:http://www.pingtaimeng.com/article/detail/193/Python3