判断语句
- 单分支判断语句
# 单分支判断语句
num1 = 30
num2 = 10
if num1 > num2:
print("num1 > num2")
- 双分支判断语句
# 双分支判断语句
num1 = 30
num2 = 10
if num1 < num2:
print("num1 < num2")
else:
print("num1 > num2")
例:
# 例
num1 = 40
num2 = 80
num3 = 60
maxnum = num1 # 存储三个数值当中最大的值,变量在前面一次性引入,和下面的表达式分离,
if num1 > num2:
maxnum = num1
else:
maxnum = num2
if maxnum > num3:
print("The max num is: ", maxnum)
else:
maxnum = num3
print("The max num is: ", maxnum)
- 多分支判断语句
# 多分支判断语句
score = int(input("please input your score:" ))
if score < 60:
print("Then you need to work harder!")
elif score < 80:
print("just so so!")
elif score <90:
print("well done!")
else:
print("awesome!!!")
- 取值范围多且有限
score = str(input("please input your score:" ))
if score in ["A","B","C","D"]:
if score == "A":
print("优秀")
if score == "B":
print("良好")
if score == "C":
print("及格")
if score == "D":
print("不及格")
- 三元运算符
num1 = 30
num2 = 20
print("num1 大于 num2" if num1 > num2 else "num1 小于 num2")
- 练习
# 练习一:输入三个浮点数,输出最小数
# a = float(input("请输入第一个数:"))
# b = float(input("请输入第二个数:"))
# c = float(input("请输入第三个数:"))
# if a < b:
# min = a
# else:
# min = b
# if min < c:
# min = min
# else:
# min = c
# print("The min num is:", min)
# 练习二:输入数字判断时候大于10小于20
# a = int(input("请输入一个数:"))
# if a < 10:
# print("这个数小于10")
# elif a > 20:
# print("这个数大于20")
# else:
# print("That num is what i want")
# 练习三:输入一个百分制成绩,转为A,B,C,C,其中90-100为A,80-99为B,70-79为C,其他为D。
# a = int(input("请输入一个数:"))
# if a > 100 or a < 0:
# print("请输入正确的分数")
# elif 90<= a <= 100:
# print("His score is A")
# elif 80 <= a <= 89:
# print("His score is B")
# elif 70 <=a <= 79:
# print("His score is C")
# else:
# print("His score is D")
# 练习四:掷骰子猜数字
# import random
# guess = random.randint(2, 12)
# while True:
# num = int(input("请输入一个2-12之间的整数: "))
# if num == guess:
# print("恭喜你,猜对了")
# exit(0)
# elif num > guess:
# print("猜大了,请重新猜")
# else:
# print("猜小了,请重新猜")