如何修复ValueError?

2024-10-02 12:31:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用Python for Kids这本书来学习Python2.7.14的基础知识,其中有一个Python编写的游戏。这是一个数字猜测游戏,但在代码的第40行,ValueError不断出现。我该如何解决这个问题

第40行:if comnum == int(players_guess):

全部代码:

# New constants
QUIT = -1
quit_text = 'q'
quit_message = 'Thanks for playing'
comfirm_quit_message = 'Are you sure you want to quit (Y/N)?'

# New comfirm_quit funtion


def comfirm_quit():
    """Ask user to comfirm that they want to quit
    default to yes
    Return True (yes, quit) or False (no, don't quit) """
    spam = raw_input(comfirm_quit_message)
    if spam == 'n':
        return False
    else:
        return True


def do_guess_round():
    """Choose a random number, ask the user for a guess
    check wether the guess is true
    and repeat until the user is correct"""
    comnum = random.randint(1, 100)
    numofguess = 0
    while True:
        players_guess = raw_input('Input your choice:')
        # new if clause to test against quit
        if players_guess == quit_text:
            if comfirm_quit():
                QUIT
            else:
                continue  # that is, do next round of loop
        numofguess = numofguess + 1
        if comnum == int(players_guess):
            print('Correct!')
        elif comnum > int(players_guess):
            print('Too low')
        else:
            print('Too high')

    totalrounds = 0
    totalguesses = 0

    while True:
        totalrounds = totalrounds + 1
        print('Starting round number: ' + str(total_rounds))
        print('Let the guessing begin!!!')
        thisround = do_guess_round()

        # new if condition (and clode block) to test against quit
        if thisround == 0:
            totalrounds = totalrounds - 1
            avg = str(totalguesses / float(totalrounds))
            if totalrounds == 0:
                statsmsg = 'You completed no rounds. ' +\
                           'Please try again later.'
            else:
                statsmsg = 'You played ' + str(totalrounds) +\
                           ' rounds, with an averave of ' +\
                           str(avg)
            break

            totalguesses = totalguesses + thisround
            avg = str(totalguesses / float(totalrounds))
            print("You took " + str(thisround) + " guesses")
            print("Your guessing average = " + str(avg))
            print("")

        # Added exit messages
        print(statsmsg)

(我已经更改了代码中变量的名称,因此变量与书中的不同。)

错误消息:Traceback (most recent call last): File "C:\Users\26benk\Desktop\Programming\PY 2\Programs\Number_guess_game.py", line 40, in <module> if comnum == int(players_guess): ValueError: invalid literal for int() with base 10: '0.1'


Tags: totrueforifelsequitintprint
2条回答

请删除行中的类型转换,如if comnum==int(players\u guess):to if comnum==players\u guess:并将这些行添加到原始输入旁边

players_guess = raw_input(prompt)
try:
    players_guess = int(players_guess)
except ValueError:
    players_guess = str(players_guess)

这肯定会解决这个问题

这是因为你没有一个break语句来把你从循环中拉出来,在循环中你要检查用户是否正确地猜到了数字

在这个循环中,

while True: 
    players_guess = raw_input(prompt)
    # new if clause to test against quit
    if players_guess == quit_text:
        if comfirm_quit():
            QUIT
        else:
            continue # that is, do next round of loop
    numofguess = numofguess+1
    if comnum == int(players_guess):
        print('Correct!')
    elif comnum > int(players_guess):
        print('Too low')
    else:
        print('Too high')

即使用户猜对了,也会要求他输入一个raw_input,因为循环仍然处于活动状态。如果按enter键,将得到ValueError,因为您正在对空字符串尝试int函数。要避免这种情况,请将循环更改为

while True: 
    players_guess = raw_input(prompt)
    # new if clause to test against quit
    if players_guess == quit_text:
        if comfirm_quit():
            QUIT
        else:
            continue # that is, do next round of loop
    numofguess = numofguess+1
    if comnum == int(players_guess):
        print('Correct!')
        break
    elif comnum > int(players_guess):
        print('Too low')
    else:
        print('Too high')

这段代码还有其他问题。第一个while循环必须是do_guess_round函数的函数

相关问题 更多 >

    热门问题