tip:以下内容学习自:https://github.com/jackfrued/Python-100-Days
1、IF语句的使用。
- 用户身份验证。
username = input("请输入用户名:")
password = input("请输入口令:")
#如果希望输入口令时 终端没有回显 可以使用getpass模块的getpass函数
# import getpass
# password = getpass.getpass("请输入口令:")
if username == "admin" and password == "123456":
print("身份验证成功!")
else:
print("身份验证失败!");
2、if…elif…else…
构建多个分支,分段函数求值:if…elif…else… 或者if…else嵌套分支
x = float(input("x = "))
if x > 1:
y = 3 * x - 5
elif x >= -1:
y = x + 2
else:
y = 5 * x +3
print("f(%.2f) = %.2f" % (x, y))
x = float(input("x = "))
if x > 1:
y = 3 * x - 5
else:
if x >= -1:
y = x + 2
else:
y = 5*x + 3
print("f(%.2f) = %.2f" % (x, y))
练习:
练习1:英制单位与公制单位互换
"""
英制单位英寸和公制单位厘米互换
"""
value = float(input("请输入长度:"))
unit = input("请输入单位:")
if unit == "in" or unit == "英寸":
print("%f英寸 = %f厘米" % (value, value *2.54))
elif unit == "cm" or unit == "厘米":
print("%f厘米 = %f英寸" % (value, value/2.54))
练习2:掷骰子决定做什么
- 使用了random模块的randint函数生成指定范围的随机数来模拟掷骰子。
from random import randint
face = randint(1, 6)
if face == 1:
result = "唱首歌"
elif face == 2:
result = "跳个舞"
elif face == 3:
result = "学狗叫"
elif face == 4:
result = "做俯卧撑"
elif face == 5:
result = "念绕口令"
else:
result = "讲冷笑话"
print(result)
练习3:百分制成绩转等级制
百分制成绩转等级制成绩
90分以上 --> A
80分~89分 --> B
70分~79分 --> C
60分~69分 --> D
60分以下 --> E
score = float(input("请输入成绩:"))
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "E"
print(score,"分对应的等级是:", grade)
练习4:输入三条边长如果能构成三角形就计算周长和面积
- 使用了math模块的sqrt函数来计算平方根。
- 用边长计算三角形面积的公式叫做海伦公式。
"""
判断输入的边长能否构成三角形
如果能则计算出三角形的周长和面积
"""
import math
a = float(input("a = "))
b = float(input("b = "))
c = float(input("c = "))
if a+b > c and a + c >b and b + c >a:
print("周长:%f" % (a + b + c))
p = (a + b + c) / 2
area = math.sqrt(p * (p-a) * (p - b) * (p-c))
print("面积:%f" % (area))
else:
print("不能构成三角形哦!")
练习5:个人所得税计算器。
- 速算扣除:是指工资超过的部分乘以这个税率再减去速算扣除即是要缴纳的税。
- 使用了Python内置的abs()函数取绝对值来处理-0的问题。
salary = float(input("本月收入:"))
insurance = float(input("五险一金:"))
diff = salary - insurance - 5000 - 1500 #5000起征点,1500的租房免税额
if diff <= 0:
rate = 0
deduction = 0
elif diff < 3000:
rate = 0.03
deduction = 0
elif diff < 12000:
rate = 0.1
deduction = 210
elif diff < 25000:
rate = 0.2
deduction = 1410
elif diff < 35000:
rate = 0.25
deduction = 2660
elif diff < 55000:
rate = 0.3
deduction = 4410
elif diff < 80000:
rate = 0.35
deduction = 7160
else:
rate = 0.45
deduction = 15160
tax = abs(diff * rate - deduction)
print("个人所得税:¥%.2f元" % tax)
print("实际到手收入:¥%.2f元" % (diff + 5000 + 1500 - tax))