Simple Python input error

2019-04-23 13:26发布

I'm trying to write a code to edit a list and make it a palindrome.

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

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.

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?

4条回答
Explosion°爆炸
2楼-- · 2019-04-23 14:06
from operator import attrgetter
num0 = input()
if not attrgetter('isdigit')(num0)():
    print("that's not a number")
查看更多
乱世女痞
3楼-- · 2019-04-23 14:17

You can't do num != int(n) because it will attempt to call int(n) which is invalid if n is not in fact an integer.

The proper way to do this is to use try and except

try:
  n = int(n)
except ValueError:
  print 'Entry is not an integer.'
  #handle this in some way

Edit: Also in Python 2.x please use raw_input() instead of input(). input() gives very odd results if you don't know what it's doing.

查看更多
Deceive 欺骗
4楼-- · 2019-04-23 14:21

Write program that handles exception. If user enters not valid integer, it throws ValueError exception:

try:
    a = int(b)
except ValueError:
    print "Unable to interpret your input as a number"

you must update your question like this:

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"
查看更多
手持菜刀,她持情操
5楼-- · 2019-04-23 14:27

You also should use raw_input and 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)

Notes:

  • 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 to int.
查看更多
登录 后发表回答