✏️ 课堂习题
第 3 章 · 分支结构 · 共 8 题 · 内容覆盖讲稿全部知识点
1
输入一个整数,判断它是正数、负数还是零,并输出相应提示。
▼
参考答案
python
n = int(input("请输入一个整数:"))
if n > 0:
print("正数")
elif n < 0:
print("负数")
else:
print("零")
2
输入一个年份,判断是否为闰年。
闰年规则:能被4整除但不能被100整除,或者能被400整除。
闰年规则:能被4整除但不能被100整除,或者能被400整除。
▼
参考答案
python
year = int(input("请输入年份:"))
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print("闰年")
else:
print("平年")
3
输入百分制成绩,输出对应等级:90分以上A,80-89 B,70-79 C,60-69 D,60分以下E。
▼
参考答案
python
score = int(input("请输入百分制成绩:"))
if score >= 90:
print('A')
elif score >= 80:
print('B')
elif score >= 70:
print('C')
elif score >= 60:
print('D')
else:
print('E')
4
输入三条边的长度,判断能否构成三角形,若能则计算并输出周长和面积(海伦公式)。
▼
参考答案
python
a = float(input('a = '))
b = float(input('b = '))
c = float(input('c = '))
if a + b > c and a + c > b and b + c > a:
l = a + b + c
s = l / 2
area = (s * (s - a) * (s - b) * (s - c)) ** 0.5
print(f'周长: {l},面积: {area:.2f}')
else:
print('不能构成三角形')
5
编写一个简易计算器:输入两个数和一个运算符(+、-、*、/),输出结果(注意除数为0的情况)。
▼
参考答案
python
num1 = float(input("请输入第一个运算数: "))
operator = input("请输入运算符(+、-、*、/): ")
num2 = float(input("请输入第二个运算数: "))
if operator == '+':
print(num1 + num2)
elif operator == '-':
print(num1 - num2)
elif operator == '*':
print(num1 * num2)
elif operator == '/':
if num2 == 0:
print("除数不能为0")
else:
print(num1 / num2)
else:
print("不支持的运算符")
6
输入一个小写字母,转换为大写字母输出。若输入的是大写字母,转换为小写输出。(提示:使用
ord() 和 chr())▼
参考答案
python
ch = input("请输入一个字母:")
if 'a' <= ch <= 'z':
print(chr(ord(ch) - 32))
elif 'A' <= ch <= 'Z':
print(chr(ord(ch) + 32))
else:
print("不是字母")
7
输入三个整数,输出其中最大值。
▼
参考答案
python
a, b, c = map(int, input("请输入三个整数(空格分隔):").split())
if a >= b and a >= c:
print(f"最大值是 {a}")
elif b >= a and b >= c:
print(f"最大值是 {b}")
else:
print(f"最大值是 {c}")
8
使用
match-case 编写程序:输入1-7的数字,输出对应的星期几;输入其他数字输出"输入错误"。▼
参考答案
python
day_num = int(input("请输入数字(1-7):"))
match day_num:
case 1: print("星期一")
case 2: print("星期二")
case 3: print("星期三")
case 4: print("星期四")
case 5: print("星期五")
case 6: print("星期六")
case 7: print("星期日")
case _: print("输入错误,请输入1-7的数字")