Python how to only accept numbers as a input

后端 未结 5 520
野的像风
野的像风 2020-12-18 16:34
mark= eval(raw_input(\"What is your mark?\"))
try:
    int(mark)
except ValueError:
    try:
        float(mark)
    except ValueError:
        print \"This is not a         


        
相关标签:
5条回答
  • 2020-12-18 17:14

    Actually if you going to use eval() you have to define more things.

    acceptables=[1,2,3,4,5,6,7,8,9,0,"+","*","/","-"]
    try:
        mark= eval(int(raw_input("What is your mark?")))
    except ValueError:
        print ("It's not a number!")
    if mark not in acceptables:
        print ("You cant do anything but arithmetical operations!")
    

    It's a basically control mechanism for eval().

    0 讨论(0)
  • 2020-12-18 17:16

    You can simply cae to float or int and catch the exception (if any). Youre using eval which is considered poor and you add a lot of redundant statements.

    try:
        mark= float(raw_input("What is your mark?"))
    except ValueError:
        print "This is not a number"
    

    "Why not use eval?" you ask, well... Try this input from the user: [1 for i in range (100000000)]

    0 讨论(0)
  • 2020-12-18 17:27
    import re
    
    pattern = re.compile("^[0-9][0-9]\*\\.?[0-9]*")
    
    status = re.search(pattern, raw_input("Enter the Mark : "))
    
    if not status:
    
            print "Invalid Input"
    
    0 讨论(0)
  • 2020-12-18 17:33

    remove eval and your code is correct:

    mark = raw_input("What is your mark?")
    try:
        int(mark)
    except ValueError:
        try:
            float(mark)
        except ValueError:
            print "This is not a number"
    

    Just checking for a float will work fine:

    try:
        float(mark)
    except ValueError:
        print "This is not a number"
    
    0 讨论(0)
  • 2020-12-18 17:33

    you can use the String object method called isnumeric. it's more efficient than try- except method. see the below code.

    def getInput(prompt):
        value = input(prompt)
        while not value.isnumeric():
            print("enter a number")
            value = input("enter again")
        return int(value)
    
    0 讨论(0)
提交回复
热议问题