1

Hi I have a question...

As a Python beginner I want to ask how do I make my code to check is input from a user a number or a letter ?


if age == int or float:
    print("Ok, zavrsili smo sa osnovnim informacijama! Da li zelite da ih uklopimo i pokazemo Vase osnovne informacije? DA ili NE ?")

elif age == False:
    print("Hej, to nije broj... Pokusaj ponovo")

This is part of my code that I'm having issues with. I want to make statement if user inputs his age as number, the code continues. But, if user inputs something that is not a number, code tells him to start all over( all print statements are written in Serbian, I hope you don't mind :D)

  • 4
    You can use function [isnumeric](https://www.w3schools.com/python/ref_string_isnumeric.asp) to check if input is a integer. [This answer](https://stackoverflow.com/questions/67432467/how-to-print-the-input-as-an-integer-float-or-string-in-python/67432634#67432634) shows how this can be used to create a function to check if a string is int, float or non-numeric string. – DarrylG May 08 '21 at 22:10
  • Does this answer your question? [Checking if a string can be converted to float in Python](https://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float-in-python) – duckboycool May 08 '21 at 22:11
  • 2
    Welcome to Stack Overflow! This site is meant for specific questions you've already [tried to find the answer yourself](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users). It's a good idea to [Google](https://www.google.com/search?q=python+string+is+number) your question first to see if answers are easy to find. – CrazyChucky May 08 '21 at 22:12
  • What is the range of acceptable numeric values, i.e. positive real numbers, all real numbers, any sequence consisting of only digits? – Michael Ruth May 08 '21 at 22:13
  • I'm not sure did I expressed myself correctly. I need my code to print an error message when user types something that isn't a number like eg. letters... – AkaMadafaka May 08 '21 at 22:19
  • @AkaMadafaka--did you check out get_type in my link above? It shows how to check if input is an int or float. If it's still not clear I can post some code. – DarrylG May 08 '21 at 22:22
  • You can use 'type' or 'isinstance' functions [Check This Link](https://stackoverflow.com/a/402704/8289026) – EmreAydin May 08 '21 at 22:29
  • @DarrylG If you can post code sure, I would love to check it out. – AkaMadafaka May 08 '21 at 22:29
  • Does this answer your question? [How to determine a Python variable's type?](https://stackoverflow.com/questions/402504/how-to-determine-a-python-variables-type) – Nouman May 08 '21 at 22:40

4 Answers4

1

Assuming that you are getting the value 'age' from the user via an input(..) call then to check if the age is a number then:

age = input('Provide age >')
if age.isnumeric():
    age = int(age)
    print("Ok, zavrsili smo sa osnovnim informacijama! Da li zelite da ih uklopimo i pokazemo Vase osnovne informacije? DA ili NE ?")
else:
     print("Hej, to nije broj... Pokusaj ponovo")
Tony Suffolk 66
  • 9,358
  • 3
  • 30
  • 33
1

The easiest way to do this is to prompt the user for input in a while loop, try to convert it to a float, and break if you're successful.

while True:
    try:
        age = float(input("Please enter your age as a number: "))
        break
    except ValueError:
        print("That's not a number, please try again!")

# age is guaranteed to be a numeric value (float) -- proceed!
Samwise
  • 68,105
  • 3
  • 30
  • 44
0
isinstance(x, int) # True

Or you can try

Use assert statement

assert <condition>,<error message>

for example

assert type(x) == int, "error"
Yafaa
  • 307
  • 1
  • 14
  • 1
    since this should be a logic check, then I think most developers would say that `assert` is the wrong thing here. – Tony Suffolk 66 May 08 '21 at 22:29
  • Not sure cause the custom message is specified here – Yafaa May 08 '21 at 22:30
  • Nothing to do with having a message - asserts are meant for debugging and maybe unit testing - asserts are very easy to disable, which is why they shouldn't be used for what is actually end user reporting or program logic. – Tony Suffolk 66 May 08 '21 at 22:31
  • He could use isinstance(x, int) than , the requirement is clear thought – Yafaa May 08 '21 at 22:34
  • it depends how the code is collecting the variable - if the variable is coming from input(...) it will be a string - so prossibly better to use `.isnumeric()` method (since that isinstance check will fail on a string, and the only way to make it work would be to pass the string to `int()` - and then you have to worry about exceptions. `isnumeric()` avoids that. – Tony Suffolk 66 May 08 '21 at 22:37
  • While this work, it seems that the OP is about result from `input()`. Which is always a string, so I think `isnumeric` or `isdigit` may be the better way to check whether the input is convertable to a number. – astrochun May 08 '21 at 22:55
0

Using function to check type of string

def get_type(s):
    ''' Detects type of string s
    
       Return int if int, float if float, or None for non-numeric string '''
    if s.isnumeric():
        return int      # only digits
    elif s.replace('.', '', 1).isnumeric():
        return float    # single decimal
    else:
        return None     # returns None for non-numeric string


# Using function
age = input("What is your age?")
if not get_type(age) is None:
    print(f'Valid age {age}')
else:
    print(f'Value {age} is not a valid age')

Example runs

What is your age?25
Valid age 25

What is your age?12.5
Valid age 12.5

What is your age?12.3.5
Value 12.3.5 is not a valid age
DarrylG
  • 16,732
  • 2
  • 17
  • 23