我试图强制用户在python中使用try-except输入一个数字,但它似乎没有效果。
while count>0:
count=count - 1
while (length != 8):
GTIN=input("Please enter a product code ")
length= len(str(GTIN))
if length!= 8:
print("That is not an eight digit number")
count=count + 1
while valid == False:
try:
GTIN/5
valid = True
except ValueError:
print("That is an invalid number")
count=count + 1
答案 0 :(得分:1)
实际上,如果用户输入了一个字符串,"hello"/5
会产生一个TypeError
,而不是一个ValueError
,所以要抓住它而不是
答案 1 :(得分:0)
您可以尝试将输入值设为int int(value)
,如果无法转换,则会引发ValueError
。
这是一个应该通过一些评论做你想做的事情:
def get_product_code():
value = ""
while True: # this will be escaped by the return
# get input from user and strip any extra whitespace: " input "
value = raw_input("Please enter a product code ").strip()
#if not value: # escape from input if nothing is entered
# return None
try:
int(value) # test if value is a number
except ValueError: # raised if cannot convert to an int
print("Input value is not a number")
value = ""
else: # an Exception was not raised
if len(value) == 8: # looks like a valid product code!
return value
else:
print("Input is not an eight digit number")
定义后,调用该函数以获取用户的输入
product_code = get_product_code()
您还应确保在您希望用户输入时随时处理KeyboardInterrupt
,因为他们可能会使用^C
或其他内容来破坏您的程序。
product code = None # prevent reference before assignment bugs
try:
product_code = get_product_code() # get code from the user
except KeyboardInterrupt: # catch user attempts to quit
print("^C\nInterrupted by user")
if product_code:
pass # do whatever you want with your product code
else:
print("no product code available!")
# perhaps exit here