Python 2.7尝试,但ValueError除外 [英] Python 2.7 try and except ValueError

查看:49
本文介绍了Python 2.7尝试,但ValueError除外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过使用int(raw_input(...))查询预期为int的用户输入

I query user input which is expected to be an int by using int(raw_input(...))

但是,当用户不输入整数时(即仅点击回车键),就会收到ValueError.

However when the user doesn't enter an integer, i.e. just hits return, I get a ValueError.

def inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue):
    rowPos = int(raw_input("Please enter the row, 0 indexed."))
    colPos = int(raw_input("Please enter the column, 0 indexed."))
    while True:
        #Test if valid row col position and position does not have default value
        if rangeRows.count(rowPos) == 1 and rangeCols.count(colPos) == 1 and inputMatrix[rowPos][colPos] == defaultValue:
            inputMatrix[rowPos][colPos] = playerValue
            break
        else:
            print "Either the RowCol Position doesn't exist or it is already filled in."
            rowPos = int(raw_input("Please enter the row, 0 indexed."))
            colPos = int(raw_input("Please enter the column, 0 indexed."))
    return inputMatrix

我试图变得聪明,尝试使用try,除了捕获ValueError之外,向用户显示警告,然后再次调用inputValue().然后,当用户输入返回查询时它起作用,但是当用户正确输入整数后掉落

I tried to be smart and use try and except to catch the ValueError, print a warning to the user and then call the inputValue() again. Then it works when the user enters return to the query but falls over when the user correctly then enters an integer

下面是带有try和的修改代码的一部分,除了:

Below is the part of the amended code with the try and except:

def inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue):
    try:
        rowPos = int(raw_input("Please enter the row, 0 indexed."))
    except ValueError:
        print "Please enter a valid input."
        inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue)   
    try:
        colPos = int(raw_input("Please enter the column, 0 indexed."))
    except ValueError:
        print "Please enter a valid input."
        inputValue(inputMatrix, rangeRows, rangeCols, defaultValue, playerValue)   

推荐答案

一种快速而肮脏的解决方案是:

A quick and dirty solution is:

parsed = False
while not parsed:
    try:
        x = int(raw_input('Enter the value:'))
        parsed = True # we only get here if the previous line didn't throw an exception
    except ValueError:
        print 'Invalid value!'

这将一直提示用户输入,直到 parsed True 为止(只有在没有异常的情况下才会发生).

This will keep prompting the user for input until parsed is True which will only happen if there was no exception.

这篇关于Python 2.7尝试,但ValueError除外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆