使用嵌套if语句的Python While循环具有多个条件

2024-09-30 05:17:18 发布

您现在位置:Python中文网/ 问答频道 /正文

下面的While循环获取一个随机生成的数字,并将其与用户生成的数字进行比较。如果第一个猜测是正确的,tit允许用户使用他们在另一个模块中输入的名称。但是,如果第一个猜测是错误的,而第二个猜测是错误的,那么它应该输出一个硬编码的名称。如果第二个猜测是错误的,它应该告诉用户所有的猜测都是错误的,他们没有超能力。问题是我可以让程序为if和else语句工作,但不能为elif工作。请帮忙。在

def getUserName():
    print('Welcome to the Superhero Name Game v 2.0')
    print('Copyright \N{COPYRIGHT SIGN}2018. Alex Fraser')

    userName=input('Please enter the superhero name you wish to use. ')
    return userName

def getUserGuess():
    import random
    x = random.randint(1,10)
    userGuess = int(input('Please enter a number between 1 and 10. '))
    return x, userGuess

def superName(n, r, g):
    guessCount = 1
    while guessCount < 3:
        if g == r and guessCount == 1:
            #hooray
            print(f'Congrats! You can use your chosen name. Your superhero name is {n}')
            return
        elif g == r and guessCount == 2:
            #meh good effort
            print('Your superhero name is Captain Marvel.')
            return
        else:
            getUserGuess()
            print(r,g)
        guessCount += 1
    print('All your guesses were incorrect. Sorry you do not have super powers')
    print(f'The number you were looking for was {r}')


n = getUserName()    
r, g = getUserGuess()
print(r,g)
superName(n,r,g)

Tags: and用户name名称youreturnifdef
3条回答

您不需要打破if/elif/else条件。这些不是循环。elif和{}只有在上面的elif和{}条件失败时才会运行。您对break语句所做的就是从while循环中跳出。在

你的else子句没有意义。它在语法上是有效的,但逻辑上没有意义。你写的是:

while you haven't guessed three times:
  check if it's a correct guess on the first try. If so, use the user's choice name
  check if it's a correct guess on the second try. If so, assign the user a name.
  for any other guess, tell the user they've failed and break out of the while.

您希望“告诉用户他们失败了”的逻辑只在while循环结束后触发,因为while循环强制执行“做三次”操作。在

^{pr2}$

你在有限的尝试次数上迭代。我觉得把它转换成search-style ^{}

def superName(n, r):    # Note, we ask for all attempts, no initial guess
    for guessCount in (1,2):
        r,g = getUserGuess()
        print(r,g)
        if g == r:
            if guessCount == 1:
                #hooray
                print(f'Congrats! You can use your chosen name. Your superhero name is {n}')
                return
            elif guessCount == 2:
                #meh good effort
                print('Your superhero name is Captain Marvel.')
                return
            # Note: that could've been an else
            # We have covered every case of guessCount
    else:    # Not necessary since we return instead of break
        print('All your guesses were incorrect. Sorry you do not have super powers')
        print(f'The number you were looking for was {r}')

我们可以更进一步,对消息进行迭代:

^{pr2}$

我注意到getUserGuess调用实际上并没有改变{}。您可能需要重新考虑(此修订版也会更改r,这可能也不是您想要的)。这就解释了为什么你从来没有看到第二个成功消息;你输入了第二个猜测,但是程序再次检查了第一个猜测。在

相关问题 更多 >

    热门问题