python - 将 string 转换为 int 导致程序崩溃

标签 python

我在我编写的一个猜数字游戏中运行了这段代码,如果玩家遵循说明,它就可以完美运行,但众所周知,用户从来不这样做。如果用户只输入一个空格或任何不是单词提示的字符串,那么当尝试将猜测的值转换为整数时,它会崩溃,并提示以 10 为基数的 int() 的文字无效。有什么办法可以解决这个问题,还是我只能忍受崩溃?

while repeat==1:
    repeat=0
    level1number=str(level1number)
    guess=input("What is your guess? ")
    guess=guess.lower()
    if guess==level1number:
        print("Well done, You have guessed my number!")
    elif guess=="hint":
        print("Hints are not available until level 3")
        repeat=1
    elif guess!=level1number:
        print("Sorry that is not my number, you have lost a life. :(")
        lives=lives-1
        repeat=1
        if lives<=0:
            print("You have lost all your lives, so this means I win")
            print("The program will now end")
            exit()
            input("")
        level1number=int(level1number)
        guess=int(guess)
        if guess<level1number:
            print("The target number is higher")
        else:
            print("The target number is lower")

最佳答案

使用某些东西

if guess.isdigit() ...

(当且仅当给定字符串的所有字符都是数字(即 0 到 9)时,方法 isdigit() 返回 true。

关于python - 将 string 转换为 int 导致程序崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40150219/

相关文章:

python - 从列表中删除以特定字符开头的元素

python - 使用 YouTube API 检查 YouTube Music 上是否提供视频

python - 在 'while True' 循环中线程化

python - 如何从链接列表中删除节点?

python - 列表列表的最小值

python - 如果表单在 django for 循环中,如何检索 html 表单的输入值

python - boto3 ec2.instances.filter 是否与 AWS CLI --query 等效?

python - 在python中使用math模块的sqrt函数处理长数

python - 现在无法获取 key 代码,使用 python 和 opencv

Python 简单 HTTP 服务器