变量的输入输出
输入函数 input(x)
输出函数 print(x) 将x输入到控制台
type(x) 查看x的变量类型
例子:
类型转换函数
int(x) 将x转换为整数
float(x) 将x转换为浮点数/小数
案例练习:
买苹果
# 输入苹果单价
price = int(input("请输入苹果价格:"))
# 输入苹果数量
amount = int(input("苹果的数量:"))
# 计算总金额
total_price = price * amount
print(total_price)
格式化输出
格式化字符串 : %
%s 字符串
%d 整数
%f 小数
%% 输出%
语法格式:
print(“格式化字符串” % 变量1)
print(“格式化字符串” % (变量1,变量2))
name = '小喵'
print("我的名字叫 %s" % name)
student_id = 1
print('我的学号是 %d' % student_id)
student_id = 1
print('我的学号是', student_id)
对比
student_id = 1
print('我的学号是 %06d' % student_id)
student_id = 100
print('我的学号是 %06d' % student_id)
student_id = 100
print('我的学号是 %6d' % student_id)
买苹果案例:
price = 8.5
weight = 7.5
money = price * weight
print("苹果单价 %f,购买了 %f 个,总共 %f元" % (price, weight, money))
进阶: 控制小数位
price = 8.5
weight = 7.5
money = price * weight
print("苹果单价 %.2f,购买了 %.2f 个,总共 %.2f元" % (price, weight, money))
进阶:输出为百分号
scale = 0.25
print("数据的比例是%.2f%%" % (scale * 100))