-1
name = input("Whats your name?")
age = input("Whats your age?")
print("You are " + name + " and you are " + age + " years old")
if name == int():
    print("Invalid Numeric")

This is what my code is, I am a beginner, I just wanna know how I can make python give out an error code if the user enter a number/integer. I am struggling with the if statement. Am I forgetting something?

I tried moving the if statement a little bit and indenting where I needed to but it didnt work

  • `if not isinstance(name, str): raise ValueError`? – Fractalism Mar 24 '23 at 20:30
  • 3
    @Fractalism It will always be a string, that's what `input()` returns. – Barmar Mar 24 '23 at 20:31
  • 1
    use `name.isdigit()` to test if `name` is all digits. – Barmar Mar 24 '23 at 20:32
  • `name`, or `age`? (Who are you to say that the user's name isn't `92478`?) – chepner Mar 24 '23 at 20:35
  • just a note, there is currently a baby out there named "X Æ A-12" - so you'll have to account for weird cases such as this as well. – rv.kvetch Mar 24 '23 at 20:38
  • Welcome to Stack Overflow. There are multiple problems with this approach. `==` means **only** "is equal to", **not** "is an example of". `int()` means the number `0`, **not** the integer type. A string **is not** an integer, **even if** it contains all digit symbols. Please see the linked duplicate to understand how to do it properly. – Karl Knechtel Mar 24 '23 at 20:42
  • For future questions: please do not talk about yourself or your skill level or your motivations - we care about **the problem**. Please [try to look for](https://meta.stackoverflow.com/questions/261592) existing questions before asking, for example by [using a search engine](https://duckduckgo.com/?q=How+can+I+make+python+give+out+an+error+code+if+the+user+enters+an+integer) (even copying and pasting your question title is good enough to get useful results). – Karl Knechtel Mar 24 '23 at 20:44
  • 1
    When you *do* care about the conversion, `int` already knows about all the corner cases. Typically, you'll just try `int(x)`, and take the appropriate action depending on whether or not you catch an exception. – chepner Mar 24 '23 at 20:47

2 Answers2

0

Create a helper function, input_as:

from typing import TypeVar, Type

_T = TypeVar('_T')


def input_as(prompt: str, tp: Type[_T], reprompt=True) -> _T:
    if '?' not in prompt:
        prompt += '? '
    elif not prompt.endswith(' '):
        prompt += ' '

    while True:
        ans = input(prompt)

        try:
            if tp is str:
                if ans.lstrip('-').replace('.', '', 1).isnumeric():
                    raise ValueError('Invalid Numeric') from None
                return ans

            elif tp in (int, float):
                try:
                    return tp(ans)
                except ValueError:
                    raise ValueError('Invalid String, need a Number') from None

            elif tp is not None:
                raise NotImplementedError(f"[{tp.__qualname__}] I don't know that type!")

        except ValueError as e:
            if reprompt:
                print(f'{e}, please re-enter.')
            else:
                raise

Usage:

name = input_as("What's your name", str)
age = input_as("What's your age", int)

print(f'You are {name} and you are {age} years old')

Examples:

What's your name? 123
Invalid Numeric, please re-enter.
What's your name? -1.23
Invalid Numeric, please re-enter.
What's your name? 
What's your name? someone
What's your age? idk
Invalid String, need a Number, please re-enter.
What's your age? 

(Happy Path)

What's your name? Jimmy
What's your age? 3
You are Jimmy and you are 3 years old
rv.kvetch
  • 9,940
  • 3
  • 24
  • 53
-2

You could use the .isdigit() method which returns True if all the digits are digits. It will return False otherwise. So you can have an if statement checking if name.isdigit() == True which prints print("Invalid Numeric")