-2

I want the program to be able to input a name and input age then the program will put you in an appropriate age group based on the age you inputted and I want it to not show error when a string is inputted in the space for age

enter image description here this is the program I tried

  • 3
    Don't post a link to a screenshot of code. Instead, include the revelent code directly in your post. Show an example input and show the exact error you get when you supply your code with that example input. Ideally, review https://stackoverflow.com/help/how-to-ask to see how you can ask questions that will attract good answers and won't be downvoted or removed. – Metropolis Jul 10 '23 at 13:49
  • Did you notice that your code will **never** output "wrong input"? – DarkKnight Jul 10 '23 at 13:56

3 Answers3

0

What you want to do is checking if the string from the user input can be converted to int. A way to do this is to use a try and catch statement. In which you do the conversion, if it goes into the exception you can comunicate to the user that it needs to input a valid integer. You could also check if the number is above 0

Check out this other question in which a similar problem is presented

Converting String to Int using try/except in Python

0

Using an exception handler is ideal for this. Also, in this case, you probably want to check that the age is greater than 0 (although I doubt if any one-year-olds will be using your program).

Nevertheless:

def app() -> tuple[str, int]:
    name = input('What is your name? ')
    while True:
        age = input('What is your age? ')
        try:
            if (_age := int(age)) < 1:
                raise ValueError('Age must be >= 1')
            return name, _age
        except ValueError as e:
            print(e)

name, age = app()

aorc = 'a child' if age <= 17 else 'an adult'

print(f'{name} you are {age} which means you are {aorc}')
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
-1

I fixed your code, it is very simple:

def app():
    while True:
        name = input('What is your name: ')
        age = input('How old are you?: ')
    
        try:
            if float(age) < 18: 
                print(f'{name}, you are a child')
            else:
                print(f'{name}, you are an adult') 
            break
        
        except ValueError:
            print('Please enter your age as a number')

Number can be either integer or fraction, use float so we can handle numbers with decimal points.

A number can only be less than 18 or not less than 18, so use else instead of a second conditional checking (elif).

Trying to cast a non-numeric string to a float ('two') will raise ValueError, we can use try-except block to catch the error and validate the input.

Finally we can use a while loop to keep asking for input and only stop we valid input is entered.

Ξένη Γήινος
  • 2,181
  • 1
  • 9
  • 35