int()的基数为10的文字无效:'q'

时间:2015-11-15 04:50:10

标签: python casting while-loop int

   ValueError:invalid literal for int() with base 10: 'q'

我是Python的新手(顺便说一下Python3),我对这个问题感到困惑。我明白错误显示的原因(这是因为我在使用整数时试图得到一个字符串)但是我对如何解决这个问题毫无头绪。我希望我的程序根据条件读取整数,并在读取字符串'q'时退出。这可能是一个简单的修复,但我真的需要另一组眼睛看我的代码。我一直在努力解决这个问题的时间超过了我的骄傲。

def main():
    aliveRow = []
    aliveCol = []
    rowAlive =''
    colAlive = -1
    row = 5
    column = 5
    while rowAlive != 'q':
        rowAlive = input("Please enter the row of a cell to turn on (or 'q' to exit:) ")
        if rowAlive != 'q' and int(rowAlive) < 0 or int(rowAlive) > row - 1:
            print('that is no a valid value; please enter a number \n \t between 0 and ', row - 1, 'inclusive....')
        elif rowAlive != 'q' and int(rowAlive) >= 0 and int(rowAlive) <= row - 1:
            aliveRow.append(rowAlive)
        else:
            print()

1 个答案:

答案 0 :(得分:1)

让我们看看当您输入q时会发生什么。

  • if条件的第一部分未得到满足 - rowAlive != 'q'返回False
  • 这意味着由int(rowAlive) < 0连接的表达式(and)的下一部分不需要进行评估; and运算符在第一个假值后中止。
  • 但是,and的优先级高于orif a and b or cif (a and b) or c相同。 因此,需要对表达式的最后一部分进行测试:int(rowAlive) > row - 1,Python无法计算int('q')

使用

if rowAlive != 'q' and (int(rowAlive) < 0 or int(rowAlive) > row - 1):

解决问题。最好不要重复自己:

while True:
    rowAlive = input("Please enter the row of a cell to turn on (or 'q' to exit:) ")
    if rowAlive == 'q':
        break
    elif int(rowAlive) < 0 or int(rowAlive) > row - 1:
        print('that is not a valid value; please enter a number \n \t between 0 and ', row-1, 'inclusive....')
    else:
        aliveRow.append(rowAlive)