Python基础学习(2)——基本数据类型

一、int 整数

# 定义整数变量
num1 = 5
num2 = 3

# 加法运算
result_addition = num1 + num2
print(f"{num1} + {num2} = {result_addition}")

# 乘法运算
result_multiplication = num1 * num2
print(f"{num1} * {num2} = {result_multiplication}")

# 类型转换
string_number = '10'
converted_number = int(string_number)
print(f"将字符串'{string_number}'转换为整数: {converted_number},类型为{type(converted_number)}")

结果为

5 + 3 = 8
5 * 3 = 15
将字符串'10'转换为整数: 10,类型为<class 'int'>

二、float 浮点数

# 定义浮点数变量
float1 = 3.14
float2 = 2.5

# 除法运算,结果为浮点数
result_division = float1 / float2
print(f"{float1} / {float2} = {result_division}")

# 类型转换
int_number = 5
converted_float = float(int_number)
print(f"将整数{int_number}转换为浮点数: {converted_float},类型为{type(converted_float)}")

结果为

3.14 / 2.5 = 1.256
将整数5转换为浮点数: 5.0,类型为<class 'float'>

三、bool 布尔类型

# 定义布尔变量
is_true = True
is_false = False

# 逻辑与运算
result_and = is_true and is_false
print(f"{is_true} and {is_false} = {result_and}")

# 逻辑或运算
result_or = is_true or is_false
print(f"{is_true} or {is_false} = {result_or}")

# 条件判断
if is_true:
    print("这是真的")
else:
    print("这是假的")

结果为

True and False = False
True or False = True
这是真的

四、str 字符串

# 定义字符串变量
string1 = 'Hello'
string2 = 'World'

# 字符串拼接
result_concat = string1 + ', ' + string2
print(result_concat)

# 字符串格式化
name = 'Alice'
age = 30
message = f"My name is {name} and I'm {age} years old."
print(message)

# 字符串方法
print(f"字符串'{string1}'的长度为: {len(string1)}")
print(f"字符串'{string1}'转换为大写: {string1.upper()}")

结果为

Hello, World
My name is Alice and I'm 30 years old.
字符串'Hello'的长度为: 5
字符串'Hello'转换为大写: HELLO

posted @ 2026-03-18 20:36  养鼠的猫  阅读(3)  评论(0)    收藏  举报