# 变量赋值
x = 10
y = "Hello, World!"
# 打印变量
print(x) # 输出10
print(y) # 输出Hello, World!
# 数据类型
a = 1 # 整数
b = 3.14 # 浮点数
c = "Python" # 字符串
d = [1, 2, 3] # 列表
e = (4, 5, 6) # 元组
f = {"name": "Alice", "age": 20} # 字典
g = {1, 2, 3} # 集合
# 打印数据类型
print(type(a)) # 输出
print(type(b)) # 输出
print(type(c)) # 输出
print(type(d)) # 输出
print(type(e)) # 输出
print(type(f)) # 输出
print(type(g)) # 输出
x = 5
if x > 0:
print("x is positive")
elif x == 0:
print("x is zero")
else:
print("x is negative")
# for循环
for i in range(5):
print(i) # 输出0, 1, 2, 3, 4
# while循环
x = 0
while x < 5:
print(x) # 输出0, 1, 2, 3, 4
x += 1
# 函数定义
def greet(name):
print("Hello,", name)
# 函数调用
greet("Alice") # 输出Hello, Alice
Python提供了多种内置的数据类型,下面是一些常用的数据类型及其案例代码:
x = 10
print(x) # 输出10
print(type(x)) # 输出
y = 3.14
print(y) # 输出3.14
print(type(y)) # 输出
name = "Alice"
print(name) # 输出Alice
print(type(name)) # 输出
numbers = [1, 2, 3, 4, 5]
print(numbers) # 输出[1, 2, 3, 4, 5]
print(type(numbers)) # 输出
point = (3, 4)
print(point) # 输出(3, 4)
print(type(point)) # 输出
person = {"name": "Alice", "age": 20}
print(person) # 输出{'name': 'Alice', 'age': 20}
print(type(person)) # 输出
numbers = {1, 2, 3, 4, 5}
print(numbers) # 输出{1, 2, 3, 4, 5}
print(type(numbers)) # 输出
Python提供了一些内置函数,可以用于数据类型之间的转换。下面是一些常见的数据类型转换及其案例代码:
x = 10
y = float(x)
print(y) # 输出10.0
x = 3.14
y = int(x)
print(y) # 输出3
x = 10
y = str(x)
print(y) # 输出'10'
x = (1, 2, 3, 4, 5)
y = list(x)
print(y) # 输出[1, 2, 3, 4, 5]
x = [1, 2, 3, 4, 5]
y = tuple(x)
print(y) # 输出(1, 2, 3, 4, 5)
x = [("name", "Alice"), ("age", 20)]
y = dict(x)
print(y) # 输出{'name': 'Alice', 'age': 20}
x = [1, 2, 3, 4, 5]
y = set(x)
print(y) # 输出{1, 2, 3, 4, 5}
#
来注释一行。# 这是一个注释
=
进行赋值。a = 10 # 将10赋值给变量a
123
。123.456
。3.14j
。"Hello, World!"
。[1, 2, 3]
。(1, 2, 3)
。{'key': 'value'}
。def say_hello(name):
print(f"Hello, {name}!")
import math # 导入math模块
try:
x = 1 / 0 # 这将引发一个ZeroDivisionError异常
except ZeroDivisionError:
print("You can't divide by zero!")