我正在尝试编写代码来编辑列表并使其成为回文。
一切正常,但我的输入仍然给我一个错误。当我在get_number_2
中输入非int时,它会崩溃。
def get_number():
num = raw_input("Please enter number between 100,000 and 1,000,0000: ")
if not num.isdigit():
print "---------------------------"
print "Invalid input: numbers only"
print "---------------------------"
my_main()
else:
return num
def get_number_2(n):
num = input("Please confirm the number you have entered: ")
if num != int(n):
print "--------------------"
print "Entries do not match"
print "--------------------"
my_main()
else:
return num
我将get_number_2
的输入用于代码的其余部分,因为get_number
在我检查它是否在两个数字之间时不起作用。
有什么方法可以验证输入是否是get_number_2
中的int,以便我可以摆脱get_number
?
答案 0 :(得分:6)
编写处理异常的程序。如果用户输入的是无效的整数,则会抛出ValueError
异常:
try:
a = int(b)
except ValueError:
print "Unable to interpret your input as a number"
你必须像这样更新你的问题:
def get_number_2(n):
num = input("Please confirm the number you have entered: ")
try:
if num != int(n):
print "--------------------"
print "Entries do not match"
print "--------------------"
my_main()
else:
return num
except ValueError:
print "Unable to interpret your input as a number"
答案 1 :(得分:3)
您无法执行int(n)
,因为如果n
实际上不是整数,它将尝试调用try
无效。
执行此操作的正确方法是使用except
和try:
n = int(n)
except ValueError:
print 'Entry is not an integer.'
#handle this in some way
raw_input()
编辑:同样在Python 2.x中,请使用input()
代替input()
。如果您不知道它在做什么,select
q.id, case when Type = 0 then Question else LinkQuestion end, Solution
from
(
select row_number() over (order by newid()) as ORD, *
from tblQuest q
) q
outer apply (
select 0 as Type, 0 as QID, convert(varchar(max), NULL) as LinkQuestion
union all
select 1, QID, l.LinkQuestion
from tblQuestLinked l where q.ID = l.QID
) x
order by q.ORD, x.Type, x.QID
会给出非常奇怪的结果。
答案 2 :(得分:3)
您还应该使用int(num)
和def get_number_2(n):
num = raw_input("Please confirm the number you have entered: ")
if not num.isdigit() or int(num) != n:
print "--------------------"
print "Entries do not match"
print "--------------------"
my_main()
else:
return int(num)
:
n
备注:
if not num.isdigit() or not n.isdigit() or int(num) != int(n)
是一个int,或者为了检查这一点,您可以将if更改为:int
。isdigit
我们会在将其真正转换为{{1}}之前检查它是否为整数。答案 3 :(得分:-1)
from operator import attrgetter
num0 = input()
if not attrgetter('isdigit')(num0)():
print("that's not a number")