【问题标题】:How to obtain a random word using function and dictionary? (Python 3)如何使用函数和字典获取随机单词? (Python 3)
【发布时间】:2013-11-17 07:26:22
【问题描述】:

用户必须选择一个类别。从那里,程序必须从类别列表中生成一个随机词。如果用户选择了一个无效的类别,程序会提示用户再次选择一个类别(再次循环 askCat 函数)。

import random

#Make word dictionary
wordDict = {'Animals':['Giraffe','Dog','Dolphin','Rabbit','Butterfly'], \
            'Fruits': ['Apple','Pineapple','Durian','Orange','Rambutan'], \
            'Colours': ['Red','Blue','Yellow','Green','Purple'], \
            'Shapes': ['Heart','Circle','Rectangle','Square','Diamond']}

#Determine word category and random word
def askCat (wordDict):
    category = str( input ("To start the game, please choose a category: \n Animals (a), Fruits (f), Colours (c), Shapes (s) "))
    print()
    if category == 'a':
        print ("You chose the Animals category.")
        cat = (wordDict['Animals'])
    elif category == 'f':
        print ("You chose the Fruits category.")
        cat = (wordDict['Animals'])
    elif category == 'c':
        print ("You chose the Colours category.")
        cat = (wordDict['Animals'])
    elif category == 's':
        print ("You chose the Shapes category.")
        cat = (wordDict['Animals'])
    else:
        print ("You entered an invalid category. Try again!")
        print()
        askCat(wordDict)
    return random.choice(cat)

#Print random word
randWord = askCat(wordDict)
print (randWord)

当第一次尝试时,用户输入了一个有效的类别,程序运行得很好。但是,我面临的问题是,当用户第一次输入无效类别时,当他第二次输入有效类别时,程序不再工作。
请帮忙!谢谢(:

【问题讨论】:

  • 小心,你总是在挑选“动物”,即使是水果、颜色和形状。
  • 您应该使用 while 循环而不是使用递归,这是不好的做法(实际上是错误所在)。

标签: function random python-3.x dictionary


【解决方案1】:

在你的函数askCat中,如果用户第一次输入了错误的类别,你再次调用askCat。但是,您不会返回该调用返回的值。

替换(在函数askCat):

askCat(wordDict)

到:

return askCat(wordDict)

但是,我强烈建议您改用 while 循环。

【讨论】:

    【解决方案2】:
    else:
        print ("You entered an invalid category. Try again!")
        print()
        askCat(wordDict)
    return random.choice(cat)
    

    在 else 分支中,您再次递归调用该函数(这没关系),然后您丢弃它的返回值并返回 cat,而不是在此函数调用中从未设置过。

    相反,您应该从递归调用中返回值:

    else:
        print ("You entered an invalid category. Try again!")
        print()
        return askCat(wordDict)
    return random.choice(cat)
    

    这样,当您递归调用它时,将使用该调用的结果,而不是您尝试从当前 cat 获取的结果。

    此外,在您的每个分支机构中,您都在做cat = (wordDict['Animals']);你可能想改变它,这样你就可以得到f 等的果实。

    最后,虽然使用递归没问题,但这并不是处理这个问题的最佳方式。递归总是有它可以进入的最大深度,所以在最坏的情况下,用户可能会继续回答错误的事情,从而进一步增加递归堆栈,直到程序出错。如果你想避免这种情况,你应该使用标准循环:

    cat = None
    while not cat:
        # You don’t nee to use `str()` here; input always returns a string
        category = input("To start the game, please choose a category: \n Animals (a), Fruits (f), Colours (c), Shapes (s) ")
        print()
        if category == 'a':
            print("You chose the Animals category.")
            cat = wordDict['Animals'] # no need to use parentheses here
        elif category == 'f':
            # ...
            # and so on
        else:
            print("You entered an invalid category. Try again!")
            # the loop will automatically repeat, as `cat` wasn’t set
    
    # when we reach here, `cat` has been set
    return random.choice(cat)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-06
      • 1970-01-01
      • 2020-02-23
      • 1970-01-01
      • 2020-03-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多