Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:将字母等级转换为相应的整数值_Python_If Statement_Comparison - Fatal编程技术网

Python:将字母等级转换为相应的整数值

Python:将字母等级转换为相应的整数值,python,if-statement,comparison,Python,If Statement,Comparison,我正在尝试对此代码中的错误进行故障排除 该程序应该处理用户指示的课堂上的学生数量。收到一封信,每个学生的分数为:a、B、C、D、F。最后,它将计算并显示类平均值 到目前为止,我的代码是: students = int(input('How many students: ')) total_sum = 0 for n in range(students): Letter = input('Enter grades: ') Letter_int = Letter if Letter

我正在尝试对此代码中的错误进行故障排除

该程序应该处理用户指示的课堂上的学生数量。收到一封信,每个学生的分数为:a、B、C、D、F。最后,它将计算并显示类平均值

到目前为止,我的代码是:

students = int(input('How many students: '))
total_sum = 0
for n in range(students):
    Letter = input('Enter grades: ')
    Letter_int = Letter
if Letter == "A":
    Letter_int == int(80)
elif Letter == "B":
    Letter_int == int(70)
elif Letter == "C":
    Letter_int == int(60)
elif Letter == "D":
    Letter_int == int(50)
elif Letter == "F":
    Letter_int == int(40)
    total_sum += Letter_int
avg = total_sum/students
print('Average of this/these', students, 'student(s) is:', avg)

代码未添加字母等级的整数值,总和始终返回为0或TypeError:+=:“int”和“str”的不支持的操作数类型。我是一名python新手,我需要一些帮助。

以下是您的代码改进和使用情况。使用它,但请阅读我提供的评论,并分析我更改了哪些部分。另外,如其他人所提到的,修改Python文档也很好。特别是缩进和它在Python中的含义

students = int(input('How many students: '))
total_sum = 0
for n in range(students):
    Letter = input('Enter grades: ')
    Letter_int = 0 # here you better initialize with integer not string
    if Letter == "A": # this condition needs to be indented - you want it to be executed
                      # in every iteration of for loop
        Letter_int = 80 # the assignment in Python is done by "=" not "==" (that would be comparison) 
    elif Letter == "B": 
        Letter_int = 70 # you do not need to do int(70), 70 is already an integer
    elif Letter == "C":
        Letter_int = 60
    elif Letter == "D":
        Letter_int = 50
    elif Letter == "F":
        Letter_int = 40
    total_sum += Letter_int # this cannot happen inside elif clause - this way it would only be
                            # executed when F grade is provided
    avg = total_sum/students
    print('Average of this/these', students, 'student(s) is:', avg)

你应该重新考虑你的缩进。。。(
if/elif
应该在循环中:
total\u sum+=Letter\u int
应该在循环的末尾-在
elif
子句之外)。在编写循环时,你需要重新阅读你的课堂材料。你的循环贯穿了所有的输入,但是除了最后输入的分数外,其他的都被丢弃了。然后你的代码检查一个字母的等级。只有在最后一个
F
的情况下,您才能在
总计中添加任何内容。请看这个可爱的博客寻求帮助。首先,插入一些
print
语句以跟踪程序流和值。可能重复