字母输入使我的游戏在python中崩溃

时间:2018-08-11 03:07:41

标签: python

以下是我的第一个python游戏,它工作正常。麻烦来自调试它。目前输入int以外的任何内容都会返回此错误。

Please guess a number between 1 & 10:
d ##"d" is my input into the terminal
Traceback (most recent call last):
  File "GuessingGamev1.0.py", line 35, in <module>
    startGame()
  File "GuessingGamev1.0.py", line 22, in startGame
    guess = int(input())
ValueError: invalid literal for int() with base 10: 'd'

下面是游戏的完整脚本

import random
import time
import sys

def restart():
    user_input = input("Would you like to play again? ")

    if user_input.lower() == "no":
        print("Goodbye")
        sys.exit(0)
    elif user_input.lower() == "yes":
        return True

def startGame():
    while True:
        randNum = random.randint(1, 10)
        tries = 0
        win = False

        print("Please guess a number between 1 & 10: ")
        while not win:
            guess = int(input())
            tries = tries + 1
            if guess == randNum:
                win = True
            elif guess < randNum:
                print("Guess Higher..")
            elif guess > randNum:
                print("Guess Lower..")
        if win:
            print("You guessed correctly!")
            time.sleep(1)
            print("Number of tries: " + str(tries) + " ")
            restart()
startGame()

我知道第22行猜测= int(input())是问题所在,但我不确定如何将输入限制为仅int

0 个答案:

没有答案