分别用 if 和 switch 编程,输入0-100分成绩,输出相应的成绩档次。设:90分以上为' A ';80~89分为' B ';70~79分为' C ';60~69分为' D ';60分以下为' E '。
时间: 2023-09-27 14:05:57 浏览: 85
### 回答1:
使用 if 编程:
```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")
```
使用 switch 编程:
在 Python 中没有 switch 语句,可以使用字典来模拟:
```python
score = int(input("请输入成绩:"))
grade = {
10: "A",
9: "A",
8: "B",
7: "C",
6: "D",
5: "E",
4: "E",
3: "E",
2: "E",
1: "E",
0: "E"
}
level = grade.get(score // 10, "输入错误")
print("成绩等级为", level)
```
### 回答2:
使用if编程:
```python
score = int(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(f"成绩档次为: {grade}")
```
使用switch编程:
(由于Python没有原生的switch语句,可以使用字典来模拟switch)
```python
def get_grade(score):
switcher = {
10: 'A',
9: 'A',
8: 'B',
7: 'C',
6: 'D',
}
# 判断分数范围
if score in range(0, 60):
return 'E'
# 获取整数部分
integer = score // 10
# 判断分数所在档次
if integer <= 5:
return switcher.get(integer, 'E')
return 'A'
score = int(input("请输入分数: "))
grade = get_grade(score)
print(f"成绩档次为: {grade}")
```
这两种方法都可以根据输入的分数输出相应的成绩档次。使用if比较灵活,可以根据条件进行分支判断,适用性较广。而switch模拟使用字典的方式可以减少代码量,比较简洁。
### 回答3:
使用if编程,可以按照如下方式实现:
```python
score = int(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("成绩档次为:", grade)
```
使用switch编程,在Python中没有内置的switch语句,可以使用字典来模拟switch的功能,按照如下方式实现:
```python
score = int(input("请输入成绩:"))
def switch_case(score):
return {
range(90, 101): 'A',
range(80, 90): 'B',
range(70, 80): 'C',
range(60, 70): 'D'
}.get(score, 'E')
grade = switch_case(score)
print("成绩档次为:", grade)
```
以上两种方式都可以根据输入的成绩输出对应的成绩档次,其中利用if来判断分数范围,或者利用字典模拟switch语句来进行判断。
相关推荐
![c](https://img-home.csdnimg.cn/images/20210720083646.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)