DojKMGg55
DojKMGg55

Reputation: 37

Input failing when user inputs a letter. I want to check to make sure they have put in a number

Hi I am trying to check if the user has put in a letter and then let them know it is a letter and they need to put in a number.

it keeps giving me a error whenever this happens, I understand it may be because I am trying to convert a int to a string but I am at a lose to trying to figure this out.

I thought the below code would check to see if its a number input and fail it or pass it depending on what they put. however it doesn't seem to work.

is there anyway around this.

def weapons_(numguns,numknifes,numbombs,numswords):
    print(numguns)

aaa = int(str(input("""Enter you're number accordinly to the list above:""")))
while True:
    try:
        number = int(aaa)
        print("this is a num, thank you")
        break
    except ValueError:
        print("this is not a number, please try again")
   
        if aaa <= 50:
            print (x)
        elif aaa <= 100:
            print (y)
        elif 101 <= 150:
            print (m + p)
        elif 151 <= 200:
            print (z)
    
weapons_("numguns","numknifes","numbombs","numswords")

Upvotes: 0

Views: 221

Answers (3)

user12171726
user12171726

Reputation:

Try using regex

import re
def checkInt(string):
    ex = re.compile(r'[1-9][0-9]*')
    return bool(ex.match(string))

You can use this function like this

aaa = input("""Enter you're number accordinly to the list above:""")
if checkInt(aaa): aaa = int(aaa)
else:
    print('Not a Integer')
    exit()
# the code you posted on the question

Upvotes: 0

Pouria Chalangari
Pouria Chalangari

Reputation: 11

Try this function:

def isNum (var): 
  flag = True
  while (flag):
    try:
      val = int(var)
      flag = False
    except ValueError:    
      var = input("No.. input is not a number! Please enter a number: ")
  return int(var)

It keeps asking for a number until the input value is an int. It finally returns the value as output.

Here is a sample screenshot of the output: sample

Upvotes: 1

florex
florex

Reputation: 963

Try this code. I put the variables x, y, m, p, z into quotes since they were not defined. Since you've casted aaa into a number, You should not use aaa anymore to compare with (50, 100, etc.) but the variable number instead. In addition, if the cast fails, the code will show the exception message and ask the use for a new number.

while True:
    try:
        aaa = input("""Enter you're number accordinly to the list above:""")
        number = int(aaa)
        print("this is a num, thank you")
        if number <= 50:
            print ("x")
        elif number <= 100:
            print ("y")
        elif 101 <= 150:
            print ("m + p")
        elif 151 <= 200:
            print ("z")
            break
    except ValueError:
        print("this is not a number, please try again")

Upvotes: 0

Related Questions