我的成绩计划正在计算错误的平均值

时间:2015-02-02 04:59:16

标签: python loops

Hiiii,谢谢你的所有答案!我已经弄清楚了!我不能删除此消息,我不知道如何使其无效。基本上我是一团糟。但是谢谢大家!!!

好吧,我实际上有456344个问题,但这是我现在的问题 这是我的代码:

def averages():
    grade = 0
    x = eval(input("How many grades will you be entering? "))
    if type(x) != type(int(x)):
        x = eval(input("You can't enter that many grades. How many grades will you be entering? "))
     for i in range(x):
         y = eval(input("Please enter a grade between 0 and 100: "))
     if 0 <= y <= 100:
         grade = grade + y
     else:
         print("Your number is out of range!")
         y = eval(input("Please enter a grade between 0 and 100: "))
    average = grade/x
            print (y)
            print (x)
            print (grade)
            print (average)

    averages()

基本上每当我运行代码时,这部分都不起作用:

if 0 <= y <= 100:
    grade = grade + y

它只计算平均值中输入的最后一个数字。 另外,如果用户输入的数字超出范围(不在0到100之间),我应该让它给出错误信息,但错误信息没有出现?我不确定发生了什么。请帮忙,谢谢。

2 个答案:

答案 0 :(得分:0)

由于成绩增加在for之外,因此仅考虑最后一项输入。

存在一些缩进问题和eval问题。最重要的是,不要在Python 2上使用input()或在Python 3上使用eval()。如果需要整数,请改用int()。试试这段代码:

def averages():
    grade = 0
    while True:
        try:
            x = int(raw_input("How many grades will you be entering? "))
        except:
            print "Input limit exceeds"
            continue
        else:
            break
    for i in range(x):
        y = int(raw_input("Please enter a grade between 0 and 100: "))
        if 0 <= y and y <= 100:
            grade = grade + y
        else:
            print("Your number is out of range!")
            y = int(input("Please enter a grade between 0 and 100: "))
    average = grade/x
    print (y)
    print (x)
    print (grade)
    print (average)

averages()

答案 1 :(得分:0)

我做了一些改变......

1)用while

替换if-else语句

2)此条件检查确保发出错误消息

def averages():
    grade = 0
    x = int(input("How many grades will you be entering? "))
    if type(x) != type(int(x)):
        x = int(input("You can't enter that many grades. How many grades will you be entering? "))
    for i in range(x):
        y = int(input("Please enter a grade between 0 and 100: "))
        while not (0 <= y <= 100):
            print("Your number is out of range!")
            y = int(input("Please enter a grade between 0 and 100: "))
        grade = grade + y

    average = grade/x
    print (y)
    print (x)
    print (grade)
    print (average)

averages()