Python:无法阻止这个程序的哨兵循环

时间:2015-01-16 04:15:05

标签: python python-3.x

所以我正在制作关于曲棍球运动员比赛的节目,我将记录他们的目标。

以下是应该发生的事情:

Who scored? 4
Who scored? 5
Who scored? 6
Who scored? 4
Who scored? 3
Game still going?(y/n) y
Who scored? 3
Who scored? 2
Who scored? 5
Who scored? 2
Who scored? 3
Game still going?(y/n) n

Creating a histogram from values: 
Element Goals Histogram
      1     0 
      2     2 **
      3     2 ***
      4     2 **
      5     2 **
      6     1 *
      7     1 *
      8     0 
      9     0 
     10     0 

这是我的代码:

def info():
    ranking = [0,0,0,0,0,0,0,0,0,0,0]
    survey = []
    return ranking,survey
def info2(survey):   
    x = ''
    for i in range(0,5):
        x = int(input("Who scored?"))           
        survey.append(x)
    again(x)
    return survey
def info3(ranking,survey):
    for i in range(len(survey)):
        ranking[survey[i]]+=1
    return ranking, survey

def again(x):
    y = input("Game still on? y/n").lower()
    if y == "yes" or y == "y":
        info()
    elif y == "n" or y =="no":
        hg(x)


#create histogram
def hg():
    print("\nCreating a histogram from values: ")
    print("%3s %5s %7s"%("Element", "Goals", "Histogram"))

#start from element 1 instead of 0
    for i in range(len(ranking)-1):
        print("%7d %5d %-s"%(i+1, ranking[i+1], "*" * ranking[i+1]))

def main():
    x,y = info()
    a = info2(y)
    d = again(x)
    b,c = info3(x,a)
    z = hg(x)
main()

当我按原样运行时,我会得到Who得分的东西,然后我进入' y'在y / n上它可以工作,但当我输入y / n并且我放n时,它会打印"元素目标直方图"然后抛出以下内容:

Traceback (most recent call last):
 line 48, in <module>
    main()
 line 44, in main
    a = info2(y)
 line 17, in info2
    again(x)
 line 29, in again
    hg(x)
 line 39, in hg
    for i in range(len(ranking)-1):
NameError: name 'ranking' is not defined

4 个答案:

答案 0 :(得分:2)

x = input("Game still on? y/n").lower

应该是:

x = input("Game still on? y/n").lower()

答案 1 :(得分:1)

我在代码中看到了几个问题...

首先,您的lower函数中有lower()而不是again()。这会将函数本身绑定到x,而不是调用它并指定其返回值。

此外,您的hg()函数需要一个参数,但是您没有在此处传递一个参数。 ranking中定义的info()是该函数的本地,hg()无法显示。

根据上述评论更新OP代码后编辑以响应OP:

此外,您在again()中处理退出案例时也存在问题。我认为你不应该在那里拨打hg(),而是将答案返回到info2()中的单独变量。

因此,这两个函数的代码看起来像这样:

def info2(survey):
    x = ''
    ans = 'y'

    while ans in ('y', 'yes'):
        for i in range(0,5):
            x = int(input("Who scored?"))
            survey.append(x)
        ans = again()
    return survey

def again():
    x = input("Game still on? y/n").lower()
    if x == "yes" or x == "y":
        info()

    return x

请注意使用附加变量和pass

根据OP的第二条评论进行编辑:

info3()没有变化。我添加了again()info2()以及我的更改。您将保留info3()(至少就此特定问题而言)。

另外,由于我的更改在 No 情况下只有pass,因此实际上可以完全删除它。只需检查情况,否则返回(在这种特殊情况下甚至不需要else。)

当我使用我提到的更改运行代码时,它似乎按要求工作。这是示例输出:

Who scored?1
Who scored?1
Who scored?1
Who scored?2
Who scored?2
Game still on? y/ny
Who scored?3
Who scored?3
Who scored?3
Who scored?2
Who scored?2
Game still on? y/nn

Creating a histogram from values: 
Element Goals Histogram
      1     3 ***
      2     4 ****
      3     3 ***
      4     0 
      5     0 
      6     0 
      7     0 
      8     0 
      9     0 
     10     0 

答案 2 :(得分:0)

我至少让它成功了,我会试着弄清楚如何让它“正确”:

def CreateParameters():
    newRanking = [0,0,0,0,0,0,0,0,0,0,0]
    newSurvey = []
    return newRanking, newSurvey
def StartProgram(sameRanking, sameSurvey):   
    Working = True
    while Working:
        for i in range(0,5):
            x = int(input("Who scored?"))           
            sameSurvey.append(x)        
        Working = AgainQuestion(sameRanking, sameSurvey)
def SaveRanking(ranking,survey):
    for i in range(len(survey)):
        ranking[survey[i]]+=1
    return ranking, survey

def AgainQuestion(againRanking, againSurvey):
    againRanking, againSurvey = SaveRanking(againRanking, againSurvey) # Saving values
    y = input("Game still on? y/n").lower()
    if y == "yes" or y == "y":
        StartProgram(againRanking, againSurvey)
        return True
    elif y == "n" or y =="no":
        Final(againRanking)
        return False


#create histogram
def Final(FinalRanking):
    print("\nCreating a histogram from values: ")
    print("%3s %5s %7s"%("Element", "Goals", "Histogram"))

#start from element 1 instead of 0
    for i in range(len(FinalRanking)-1):
        print("%7d %5d %-s"%(i+1, FinalRanking[i+1], "*" * FinalRanking[i+1]))

def main():
    mainRanking, mainSurvey = CreateParameters()
    StartProgram(mainRanking, mainSurvey)
main()

我注意到的问题:  *排名从未被赋予secundary函数(我的意思是:函数调用的函数)。  *主要功能称为信息的方法,即使你应该关闭cicle,因为你再次打电话给他们(这就是为什么我要改变它)

答案 3 :(得分:0)

我不确定所有的功能和变量应该做什么。如果对函数和变量使用合理的名称,则更容易调试和理解代码。

from collections import OrderedDict

def main():
    list_of_players = [str(number) for number in range(1, 11)]
    ranking = play(list_of_players)
    print_histogram(ranking)

def play(list_of_players):
    ranking = OrderedDict([(player, 0) for player in list_of_players])
    while True:
        for i in range(5):
            player = input('Who scored? ')
            try:
                ranking[player] += 1
            except KeyError:
                print('Not a player')
        if input('Game still going?(y/n) ').lower() in ['n', 'no']:
            return ranking

def print_histogram(ranking):
    template = '{player:^7} {goals:^7} {stars}'
    print('\nCreating a histogram from values: ')
    print(template.format(player='Element', goals='Goals', stars='Histogram'))
    for player, goals in ranking.items():
        print(template.format(player=player, goals=goals, stars='*' * goals))

if __name__ == '__main__':
    main()