Python While While循环使用嵌套if语句

时间:2018-05-15 04:30:03

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

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

4 个答案:

答案 0 :(得分:0)

您无需突破if/elif/else条件。这些是非循环。 elifelse只有在上面的elifif条件失败时才会运行。你正在用break语句做的就是打破你的while循环。

答案 1 :(得分:0)

你的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循环强制执行“三次”操作。

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

答案 2 :(得分:0)

你在有限次的尝试中进行迭代。我认为将其转换为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,这可能也不是你想要的)。这可以解释为什么你永远不会看到第二个成功的信息;你输入了第二个猜测,但程序再次检查了第一个猜测。

答案 3 :(得分:0)

感谢@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())