变量是存储数据的容器。在Python中,不需要提前声明变量类型,直接赋值即可。
# 变量赋值
name = "张三"
age = 25
height = 1.75
is_student = True
print(name) # 输出: 张三
print(age) # 输出: 25
# 正确的变量名
user_name = "李四"
age2 = 30
_private = "私有变量"
# 错误的变量名
# 2age = 30 # 不能以数字开头
# user-name = "" # 不能包含连字符
# class = "A" # 不能使用关键字
x = 10
y = -5
big_number = 1000000
print(type(x)) #
pi = 3.14
price = 99.99
temperature = -5.5
print(type(pi)) #
# 单引号或双引号都可以
message = "Hello"
name = 'Python'
# 多行字符串
text = """这是
多行
字符串"""
# 字符串拼接
greeting = "Hello" + " " + "World"
print(greeting) # Hello World
# 字符串格式化(推荐使用f-string)
name = "张三"
age = 25
print(f"我叫{name},今年{age}岁")
is_active = True
is_deleted = False
# 布尔运算
print(True and False) # False
print(True or False) # True
print(not True) # False
result = None
print(result) # None
print(type(result)) #
# 转换为整数
x = int("10") # 10
y = int(3.14) # 3
# 转换为浮点数
a = float("3.14") # 3.14
b = float(5) # 5.0
# 转换为字符串
s = str(100) # "100"
t = str(3.14) # "3.14"
# 转换为布尔值
print(bool(1)) # True
print(bool(0)) # False
print(bool("")) # False
print(bool("Hi")) # True
x = 10
print(type(x)) #
y = "Hello"
print(type(y)) #
z = 3.14
print(type(z)) #
name = "你的名字"
age = 20
height = 1.70
intro = f"大家好,我叫{name},今年{age}岁,身高{height}米"
print(intro)