Как получить доступ к переменной delcared внутри функции вне функции в Python 3? - PullRequest
0 голосов
/ 02 апреля 2020

Я пытаюсь сделать простое предположение о числовой программе в python. Когда я запускаю этот код, генерируется ошибка, в которой говорится, что «локальная переменная« шанс »указана перед присвоением». Я искал решение для inte rnet, но я не мог исправить свою ошибку. Пожалуйста, помогите с этой проблемой. Как я могу использовать переменную глобально, которая объявлена ​​внутри функции? Я новичок в программировании, поэтому прошу объяснить простыми словами. Вот код ..

Поскольку я новичок, я буду рад, если мой код будет исправлен

import random
def Random():
    chance = 3
    number = random.randint(0,20)
    return chance
    return number


def main():
    while chance > 0:
        UserInput = int(input('Guess the number: '))
        if UserInput == number:
            print('You have guesses the secret number!')
        elif UserInput > 20 and  UserInput < 0:
                    print('Your guess is out of range!\n Try again!')
        else:
                    chance -= 1
                    if chance == 1:
                            print('You are out of chances!')
                    print('Wrong Guess!\nTry again!')
                    print(f'You have {chance} chances left!')



Random()
main()

playAgain = input('Want to play again? ')
if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':
    Random()
    main()
else:
    print('Thanks for playing!')

Ответы [ 2 ]

1 голос
/ 02 апреля 2020

Вы можете вернуть список или кортеж к внешнему слову:

import random

def example():
    chance = 3
    number = random.randint(0,20)
    return (chance, number)  # return both numbers as a tuple


chance, randNr = example()  # decomposes the returned tuple
print(chance, randNr)

печатает:

3, 17

В вашей программе больше ошибок, например:

if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':

всегда True, и вы никогда не сможете выйти из игры. Лучше было бы

if playAgain.lower() in {'yes', 'yeah'}:

et c.

Вот рабочий пример для ваших программных целей:

import random

while True:
    chances = 3

    number = random.randint(0,20)
    while chances > 0:
        guess = int(input("Guess number: "))
        if guess == number:
            print("Correct")
            break
        else:
            chances -= 1
            print("Wrong, ", chances, " more tries to get it right.")

    if chances == 0:
        print ("You failed")
    if not input("Play again? ")[:1].lower() == "y":
        break
print("Bye.")

Читать о кортежах

Вывод:

Guess number: 1
Wrong,  2  more tries to get it right.
Guess number: 4
Correct
Play again? y
Guess number: 1
Wrong,  2  more tries to get it right.
Guess number: 2
Wrong,  1  more tries to get it right.
Guess number: 3
Wrong,  0  more tries to get it right.
You failed
Play again? n
Bye.
0 голосов
/ 02 апреля 2020
import random
def Random():
    chance = 3
    number = random.randint(0,20)
    main(chance,number)


def main(chance,number):
    while chance > 0:
        UserInput = int(input('Guess the number: '))
        if UserInput == number:
            print('You have guesses the secret number!')
        elif UserInput > 20 and  UserInput < 0:
            print('Your guess is out of range!\n Try again!')
        else:
            chance -= 1
            if chance == 1:
                    print('You are out of chances!')
            print('Wrong Guess!\nTry again!')
            print('You have',chance,'chances left!')
Random()
playAgain = input('Want to play again? ')
if playAgain == 'yes' or 'YES' or 'Yeah' or 'yeah':
    Random()
else:
    print('Thanks for playing!')
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...