我的python脚本突然停止

时间:2018-08-23 10:46:42

标签: python python-3.x

我的python脚本在执行某段代码时突然停止运行,并且在此之前运行良好,但是现在执行时就像崩溃一样 这是我的代码:

import random; from time import sleep
while True:
    if 'playerName' in locals() or 'playerName' in globals():
        continue
    else:
        print('What is your name?')
        playerName = input()
    print(f'Hi there, {playerName}, welcome to this math game.')
    sleep(2)
    print('This game can make yourself custom equations to test your math. (only addition.)')
    sleep(2)
    print('Set the limit for numbers. (example. 1000 and 1234)')
    limit1 = int(input())
    limit2 = int(input())
    number1 = random.randint(limit1, limit2)
    number2 = random.randint(limit1, limit2)
    answer = number1 + number2
    print(f'Here is the question: {number1} + {number2}')
    sleep(1.5)
    print('Do you know the answer for this?')
    playerAnswer = input()
    if int(str(playerAnswer)) == answer:
        print(f'Good job, {playerName} You answered correctly!')
    elif int(str(playerAnswer)) != answer:
        print('Nope the answer is ' + str(int(answer)) + '.')
    print('Do you want to restart? (y/n)')
    restart = input()
    if restart == 'y':
        continue
    else:
        print('Goodbye')
        break

完成一轮后,它会在最后停止。有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

if 'playerName' in locals() or 'playerName' in globals():
    continue

只有在玩家选择“是”并且不允许您进入下一个“打印”语句后,该语句才会执行,因为“ playerName”将在第一轮游戏后始终位于locals()中。

简单修复可能如下所示:

if not ('playerName' in locals() or 'playerName' in globals()):
    print('What is your name?')
    playerName = input()