Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python3中遇到错误(异常、循环)_Python_Exception_Loops_While Loop - Fatal编程技术网

在Python3中遇到错误(异常、循环)

在Python3中遇到错误(异常、循环),python,exception,loops,while-loop,Python,Exception,Loops,While Loop,所以我在这里要做的是,如果你输入一个字符串而不是一个整数,你就回到起点 但是由于某种原因,当你输入一个字符串时,程序就停止了 while True: try: print("Will select a random number between selected limits: 'x' and 'y'") x = int(input("x = ")) except ValueError: print("Please enter a

所以我在这里要做的是,如果你输入一个字符串而不是一个整数,你就回到起点

但是由于某种原因,当你输入一个字符串时,程序就停止了

while True:
    try:
        print("Will select a random number between selected limits: 'x' and 'y'")
        x = int(input("x = "))
    except ValueError:
        print("Please enter a number")
        break

甚至更短,一行;):


中断
放在
其他:
块中,而不是放在
尝试:
块的末尾,有什么意义呢?@chen这只是个人风格的问题,我认为这样做感觉更有条理我的程序实际上完成了,我只是稍微润色了一下。我已经完成了y=int(input())的所有操作,但您只是为我简化了10-20行,现在一切都正常了,谢谢!
while True:
    try:
        print("Will select a random number between selected limits: 'x' and 'y'")
        x = int(input("x = "))
        y = int(input("y = "))
    except ValueError:
        print("Please enter a number") # don't break here, let loop repeat
    else:
        break # only break when there is no error
while True:
    try:
        print("Will select a random number between selected limits: 'x' and 'y'")
        x = int(input("x = "))
        y = int(input("y = "))
        break # only break when there is no error
    except ValueError:
        print("Please enter a number") # don't break here, let loop repeat