Почему это просто останавливается после запуска функции и почему эта переменная не увеличивается?

#python-3.x

#python-3.x

Вопрос:

 deathcounter, r, n, deaths=0, 0, 0, 0
def gamestart():
    print("Enter the cheese world?")
    print("(1) Yes (2) No")
    n=int(input(""))
def gameover():
    print("GAME OVER")
    deathcounter=deaths 1
    n=0
    r=0
    gamestart()
print("Deaths :", deathcounter)
gamestart()
if n == 1:
    print("You enter the cheese world. It's full of cheese.")
    print("(1) Eat the cheese (2) Banish the cheese")
    r=int(input(""))
if n == 2:
    print("You reject the cheese world. What is the point anymore.")
    gameover()
if r == 1:
    print("You eat the cheese. You die from an artery blockage.")
    gameover()
if r == 2:
    print("You attempt to banish the cheese. The cheese's power is incomprehensible to you, and you lose your mind.")
    gameover()
  

Я не понимаю, почему это печатается gamestart() , а затем просто останавливается, и почему deathcounter не повышается после запуска gameover() .

Я только начал программировать, поэтому критика очень ценится.

Ответ №1:

Переменные deathcounter n и r внутренние функции gamestart и gameover являются локальными для этих функций, они не совпадают с переменными, которые вы определили в первой строке. Итак, изменения, внесенные в любую из этих переменных внутри gamestart и gameover , не отразятся на глобальных переменных. Если вы хотите, чтобы изменения отражались в глобальной области видимости, вам следует использовать global ключевое слово.

Вы можете прочитать о глобальных переменных здесь: https://www.geeksforgeeks.org/global-local-variables-python /

Ваш код после использования global ключевого слова:

 deathcounter, r, n, deaths=0, 0, 0, 0

def gamestart():
    global n
    print("Enter the cheese world?")
    print("(1) Yes (2) No")
    n=int(input(""))

def gameover():
    global n, r, deathcounter
    print("GAME OVER")
    deathcounter=deaths 1
    n=0
    r=0
    gamestart()

print("Deaths :", deathcounter)
gamestart()
if n == 1:
    print("You enter the cheese world. It's full of cheese.")
    print("(1) Eat the cheese (2) Banish the cheese")
    r=int(input(""))
if n == 2:
    print("You reject the cheese world. What is the point anymore.")
    gameover()
if r == 1:
    print("You eat the cheese. You die from an artery blockage.")
    gameover()
if r == 2:
    print("You attempt to banish the cheese. The cheese's power is incomprehensible to you, and you lose your mind.")
    gameover()
  

Комментарии:

1. сработало, но перестает печатать текст после ввода n во второй раз. 1

2. @jorma да, в программе есть некоторые логические ошибки. Вы можете обнаружить эти проблемы за несколько минут. Я не упоминал об этих проблемах в своем ответе, потому что я только отвечал на ваш вопрос

3. @jorma подсказка: используйте цикл while

Ответ №2:

вам нужно указать эти переменные как глобальные внутренние функции.

например

 global n
# then
n=int(input(""))
  

Комментарии:

1. Помогло, но останавливается после n повторного ввода.