简单的Python输入错误 [英] Simple Python input error
本文介绍了简单的Python输入错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写代码来编辑列表并使之成为回文.
I'm trying to write a code to edit a list and make it a palindrome.
一切正常,除了我的输入仍然给我一个错误.当我在get_number_2
中输入非整数时,它将崩溃.
Everything is working except my input still gives me one error. When I enter a non-int into get_number_2
, it crashes.
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
在检查两个数字之间是否不起作用时不起作用.
I use the input from get_number_2
for the rest of the code as get_number
doesn't work when I check if its between two numbers.
有什么方法可以验证输入是否为get_number_2
中的int,以便摆脱get_number
?
Is there any way i can validate if input is an int in get_number_2
so that I can get rid of get_number
?
推荐答案
您还应该使用raw_input
和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更改为:if not num.isdigit() or not n.isdigit() or int(num) != int(n)
. - 通过使用
isdigit
来检查是否真正转换为int
之前的整数.
- I assume that the parameter
n
is an int, or to check this you could change the if to:if not num.isdigit() or not n.isdigit() or int(num) != int(n)
. - By using
isdigit
we check if it is an integer before really converting it toint
.
这篇关于简单的Python输入错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文