Python Forum
if the input is not number, let user input again
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
if the input is not number, let user input again
#1
hi :) i am starting to learn python, and learning from Automating Boring Stuff With Python, then i tried to implement the knowledge and do something by myself.

i am creating this program that asks user for the age. when i tested the program, i realised if i didn't enter the number correctly as integer, the program would not continue.

so i tried to create a condition for the program to check whether it is integer or not, if not, the user can type again, and then the program would print 'thank you', and continue to print the calculated value, and continue until the end.

however, i am caught up for a lengthy period, so i think i should post a question to ask someone knowledgeable, here are my codes :

 
print('hello there')
print('what is your name?')

myName = input()
print('your name is ' + myName + ', it is nice to meet you')
print('the length of your name is composed of ' + str(len(myName)) + ' letters.')

print('what is your age?')
myAge = input(int())

if myAge == input(int()):
    print('thank you')
else:
    print('please enter the number only')

while myAge != int():
    print('please enter the number only')
    myAge = input(int())
print('thank you')

print('you will be ' + str(int(myAge) + 1) + ' next year')
print('this is the end of this program')
thank you :)
Reply
#2
This is a very common question. At the same time, the answer is not obvious because it forces you to use the exceptions mechanism.
Here is one way to do it
while True:
    try:
        age = int(input("How old are you? "))
    except ValueError:
        print("Invalid value. Please enter an integer! Let's try again...")
    else:
        break

print("You are {} years old.".format(age))
Reply
#3
if you do
input('What is your age? ')
You will get a string.
To test if this string is a number with int(),you might look into try / except / finally clauses.
This way you program will not crash when int() fails.

(But there are many other ways)
Paul
Reply
#4
thank you so much!!!

i am loving the program :) feels so good that it finally runs!!!
Reply
#5
print('hello there')
print('what is your name?')

while True:
    myName = input()
    try:
        if str(myName) == True:
            print('your name is ' + myName + ', it is nice to meet you')
            print('the length of your name is composed of ' + str(len(myName)) + ' letters.')
        else:
            print('Please use the alphabet instead of the number')
        
        continue
        print('what is your age?')

        while True:
            myAge = input()
            try:
                myAge = int(myAge)
                print('thank you')
        
            except ValueError:
                print(f"{myAge} isn't a number. Please enter a number!")
        pass
print('thank you') 
print('you will be ' + str(int(myAge) + 1) + ' next year')
print('this is the end of this program')
Error:
print('thank you') ^ IndentationError: unexpected unindent
Help me how can i solved it?
Reply
#6
Your missing except for the first try statement
I welcome all feedback.
The only dumb question, is one that doesn't get asked.

My Scripts
CookBook - Shmup - PyQt5 Music Player


Reply
#7
print('hello there')
print('what is your name?')
while True:
    myName = input()
    try:
        if str(myName) == True:
            print('your name is ' + myName + ', it is nice to meet you')
            print('the length of your name is composed of ' + str(len(myName)) + ' letters.')
        else:
            print('Please use the alphabet instead of the number')
         
        continue
        print('what is your age?')
 
        while True:
            myAge = input()
            try:
                myAge = int(myAge)
                print('thank you')
            except ValueError:
                print(f"{myAge} isn't a number. Please enter a number!")
        pass
    except:
        print('thank you') 
        print('you will be ' + str(int(myAge) + 1) + ' next year')
        print('this is the end of this program')
it works but it ends first loop and print wrong sentences and don't ask second question also...
Output:
hello there [b]what is your name?[/b] Samuel [b]Please use the alphabet instead of the number[/b]
Reply
#8
Another way. Modified code a little.
#! /usr/bin/env python3.8

while True:
    try:
        my_name = input('What is your name: ')
        if my_name.isdigit():
            print(f'{my_name} is a number. Please use letters for a name.')
            continue
        else:
            print(f'Your name is {my_name}. It\'s nice to meet you')
            print(f'The length of your name is {len(my_name)} letters.')
            break
    except ValueError as error:
        print(f'Error: {error}')
        break

while True:
    try:
        my_age = input(f'{my_name.title()}, what is your age: ')
        if my_age.isalpha():
            print(f'{my_age} is not allowed in age')
            continue
        else:
            age = int(my_age) + 1
            print(f'{my_name.title()} will be {age} next year.')
            break
    except ValueError as error:
        print(f'Error: {error}')
        break
Output:
What is your name: john Your name is john. It's nice to meet you The length of your name is 4 letters. John, what is your age: p p is not allowed in age John is your age: 15 John will be 16 next year.
I welcome all feedback.
The only dumb question, is one that doesn't get asked.

My Scripts
CookBook - Shmup - PyQt5 Music Player


Reply
#9
(May-31-2020, 02:52 PM)menator01 Wrote: Another way. Modified code a little.
#! /usr/bin/env python3.8

while True:
    try:
        my_name = input('What is your name: ')
        if my_name.isdigit():
            print(f'{my_name} is a number. Please use letters for a name.')
            continue
        else:
            print(f'Your name is {my_name}. It\'s nice to meet you')
            print(f'The length of your name is {len(my_name)} letters.')
            break
    except ValueError as error:
        print(f'Error: {error}')
        break

while True:
    try:
        my_age = input('What is your age: ')
        if my_age.isalpha():
            print(f'{my_age} is not allowed in age')
            continue
        else:
            age = int(my_age) + 1
            print(f'You will be {age} next year.')
            break
    except ValueError as error:
        print(f'Error: {error}')
        break
print(f'{my_name.title()} will be {age} next year.')

Friend i want to do like this... Thank you I understood the working logic of some codes like x.isalpha(): , y.isdigit():, while loop must be end with except code, and also When the application is finished, we have to use the "break" command to switch to the other application.

But i ask another question LOL
this programme work perfect but when i enter my name like 15.1 (float) is says:
Output:
What is your name: 15.1 Your name is 15.1. It's nice to meet you The length of your name is 4 letters.
is this float is not a digit ?
Reply
#10
Updated code to check for floats May not be best method but, works
#! /usr/bin/env python3.8

while True:
    try:
        my_name = input('What is your name?: ')
        if my_name.replace('.','').isdigit():
            print(f'{my_name} is a number. Please use letters for a name.')
            continue
        else:
            print(f'It\'s nice to meet you {my_name.title()}')
            print(f'{my_name.title()}, your name is {len(my_name)} letters long.')
            break
    except ValueError as error:
        print(f'Error: {error}')
        break

while True:
    try:
        my_age = input(f'{my_name.title()}, what is your age?: ')
        if my_age.isalpha():
            print(f'{my_name.title()}, {my_age} is not a number.')
            continue
        else:
            age = int(my_age) + 1
            print(f'{my_name.title()}, you will be {age} next year.')
            break
    except ValueError as error:
        print(f'Error: {my_name.title()}, please only use whole numbers for age.')
        continue
Output:
What is your name?: 15.3 15.3 is a number. Please use letters for a name. What is your name?: john It's nice to meet you John John, your name is 4 letters long. John, what is your age?: pop John, pop is not a number. John, what is your age?: 15 John, you will be 16 next year.
I welcome all feedback.
The only dumb question, is one that doesn't get asked.

My Scripts
CookBook - Shmup - PyQt5 Music Player


Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Exit function from nested function based on user input Turtle 5 324 Oct-10-2021, 12:55 AM
Last Post: Turtle
Star I'm getting syntax error while using input function in def. yecktmpmbyrv 1 195 Oct-06-2021, 09:39 AM
Last Post: menator01
  How to include input as part of variable name Mark17 4 409 Oct-01-2021, 06:45 PM
Last Post: Mark17
Exclamation question about input, while loop, then print jamie_01 5 385 Sep-30-2021, 12:46 PM
Last Post: Underscore
  Found input variables with inconsistent numbers of samples: [1000, 200] jenya56 2 229 Sep-15-2021, 12:48 PM
Last Post: jenya56
  [SOLVED] Input parameter: Single file or glob? Winfried 0 208 Sep-10-2021, 11:54 AM
Last Post: Winfried
  input data validation plumberpy 2 410 Aug-11-2021, 12:04 PM
Last Post: plumberpy
Big Grin Newbie to Python - input and branching issue Sherine 3 670 Jul-31-2021, 01:09 AM
Last Post: Pedroski55
  Unable to access the user input value given to daterangepicker klllmmm 1 704 May-26-2021, 09:16 PM
Last Post: nilamo
  [SOLVED] Good way to handle input args? Winfried 2 541 May-18-2021, 07:33 PM
Last Post: Winfried

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020