【问题标题】:Python While Loop with multiple conditions using nested if statements使用嵌套 if 语句的具有多个条件的 Python While 循环
【发布时间】:2018-05-15 04:30:03
【问题描述】:

以下 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)

【问题讨论】:

  • 编辑,对 getUserGuess 的调用返回 2 个值。因为我没有使用这些值,所以我可以删除调用,但是它会中断循环。
  • 请修正缩进
  • 您显示的代码没有任何意义,因为在if/elif/else 的每个分支中都有一个break,因此循环永远不会重复。恐怕我不知道您实际上希望这段代码从问题中做什么,所以我真的无法帮助您解决问题。
  • 黑。我正在尝试重新设计 while 循环,以便如果第二次猜测正确,则硬代码名称会打印到屏幕上。与下面获得的输出不同。版权所有 ©2018。 Alex Fraser 请输入您希望使用的超级英雄名称。随机 请输入一个介于 1 和 10 之间的数字。 4 请输入一个介于 1 和 10 之间的数字。 5 您所有的猜测都是错误的。对不起,你没有超能力你要找的数字是 5
  • 你肯定要发布你是怎么称呼这个的以及getUserGuess做什么

标签: python python-3.x while-loop


【解决方案1】:

您不需要打破if/elif/else 条件。这些不是循环。 elifelse 只会在它们上面的 elifif 条件失败时运行。您对 break 语句所做的一切就是打破您的 while 循环。

【讨论】:

  • 感谢@ytpillai。条件语句在上面的代码块中可能没有缩进,但它们在我的编辑器中
  • 我会从我的答案中删除。
  • @AdamSmith 偷走了我的接受,这让我很痛苦。 :(
【解决方案2】:

您的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 循环正在执行“执行 3 次”的事情。

while guess_count < 3:
    if g == r and guess_count == 1:
        # hooray
        return
    elif g == r and guess_count == 2:
        # meh
        return
    else:
        # this is just one incorrect guess -- you should probably
        # prompt the user to guess another number to change the value of g
    guess_count += 1
# boo, you failed to guess

【讨论】:

  • 感谢@AdamSmith。我试试看
  • 我已经实施了您建议的更改,但是遇到了同样的问题。循环正确迭代,但第二次猜测输出从未打印?
  • 编辑:当第一次猜测正确时执行所有输出语句。
  • @AlexanderFraser 听起来您没有在子句末尾返回。
  • 你能不能把 if 和 elif from.the while.loop 去掉,放在最上面?使代码更干净。
【解决方案3】:

您正在迭代有限次数的尝试。我觉得把这个转成search-style for比较自然:

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}')

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

def superName(n, r):    # Note, we ask for all attempts, no initial guess
    for successmessage in (
            f'Congrats! You can use your chosen name. Your superhero name is {n}',
            'Your superhero name is Captain Marvel.' ):
        r,g = getUserGuess()
        print(r,g)
        if g == r:
            print(successmessage)
            break   # We've found the appropriate message
    else:    # Not necessary if 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}')

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

【讨论】:

  • @YannVemier 你说得对,我不想让 r 改变
  • 那你还有一件事要重新考虑:getUserGuess为什么会生成一个随机数?
  • 我通过这个论坛和我的讲师咨询意识到我只需要调用一次随机数。
【解决方案4】:

感谢@ytpillai 的解决方案。稍作修改,将猜测次数限制为 3。无论猜测 3 是否正确,用户都会得到相同的消息。

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

GUESS_COUNT_LIMIT = 2
def getUserGuess():
    return int(input('What is your guess? '))
def superName(n, r, g):
    guessCount = 1
    if g == r:
        print(f'Congrats! You can use your hero name. Your superhero name is {n}')
        return
    g = getUserGuess()
    if g == r:
        print('Your superhero name is Captain Marvel')
        return

    while g != r and guessCount < GUESS_COUNT_LIMIT:
        g = getUserGuess()

        if g == r:
            print('All your guesses were incorrect. Sorry you do not have super powers')
            return
        guessCount +=1 



    print('All your guesses were incorrect. Sorry you do not have super powers')


import random
superName(getUserName(), random.randint(1, 10),getUserGuess())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-10-30
    • 1970-01-01
    • 2012-03-12
    • 2018-05-27
    • 2018-03-15
    • 2017-02-06
    • 2023-03-30
    • 1970-01-01
    相关资源
    最近更新 更多