这是我的代码,我不断收到错误。我能够成功识别无效的整数。但是,如果我输入正数,我会收到此错误TypeError:并非在字符串格式化期间转换所有参数。
inter=(input('Enter a positive integer:'))
if not inter.isdigit():
print('You did not enter a valid input!')
else:
if(inter%2==0):
print('You entered an even number')
elif(inter%7==0):
print('You entered an odd number that is a multiple of 7')
else:
print('You entered an odd number that is NOT a multiple of 7')
答案 0 :(得分:0)
inter=(input('Enter a positive integer:'))
if not inter.isdigit():
print('You did not enter a valid input!')
else:
if(int(inter)%2==0):
print('You entered an even number')
elif(int(inter)%7==0):
print('You entered an odd number that is a multiple of 7')
else:
print('You entered an odd number that is NOT a multiple of 7')
答案 1 :(得分:-1)
try:
inter=int((input('Enter a positive integer:')))
if(inter%2==0):
print('You entered an even number')
elif(inter%7==0):
print('You entered an odd number that is a multiple of 7')
else:
print('You entered an odd number that is NOT a multiple of 7')
except:
print('You did not enter a valid input!')
这是查看输入是否为int的更好方法。 try-except
语句处理任何错误。如果尝试遇到错误,那么它将突破该语句并执行except语句。因此,当输入转换为int时,如果输入是字符串,则会引发错误。