Цикл Python While с несколькими условиями с использованием вложенных операторов if - PullRequest
0 голосов
/ 15 мая 2018

Следующий цикл 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 голосов
/ 15 мая 2018

Спасибо @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())
0 голосов
/ 15 мая 2018

Ваше предложение 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
0 голосов
/ 15 мая 2018

Вы повторяете ограниченное количество попыток. Я чувствую, что более естественно преобразовать это в стиль поиска 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, что, вероятно, также не то, что вы хотите). Это объясняет, почему вы никогда не видите второе сообщение об успехе; Вы ввели второе предположение, но программа снова проверила первое предположение.

0 голосов
/ 15 мая 2018

Вам не нужно выходить из условия if/elif/else. Это НЕ петли. elif и else будут работать, только если вышеперечисленные условия elif и if не пройдены. Все, что вы делаете со своими операторами break - это выход из цикла while.

...