因此,我有一个条件,只接受一个变量的负值,而且它也不应该引起值错误。我的代码是这样的->
try:
x = int(input("Enter -ve value : "))
while x >= 0:
print("Error wrong value!")
x = int(input("Enter -ve value : " )
except ValueError:
print("Error wrong value!")
x = int(input("Enter -ve value : "))
while x >= 0:
print("Error wrong value!")
x=int(input("Enter -ve value : " )这种方法的唯一问题是,假设我第一次按enter而没有输入一个值。它带我进入“除”条件,它工作良好,但如果我再次输入一个空白值,我的代码会因为值错误而停止。我怎么才能阻止这一切的发生?是否有一种更有效的方法来编写这段代码而不导入任何模块?
感谢您的时间和努力!我在移动应用程序上写了这个问题,如果给你带来不便的话,我很抱歉!
发布于 2018-07-05 09:06:01
你可以这样做:
x = 0
while x >= 0:
try:
x = int(input("Enter -ve value : "))
except ValueError:
print("Error wrong value!")
x = 0这将实现您所要求的,因为它将不断地提示您输入一个数字while x >= 0,并且还将确保每次输入都执行异常处理。
https://stackoverflow.com/questions/51187169
复制相似问题