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
Your missing except for the first try statement
I welcome all feedback.
The only dumb question, is one that doesn't get asked.
My Github
How to post code using bbtags
Download my project scripts


Reply
#6
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 Github
How to post code using bbtags
Download my project scripts


Reply
#7
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 Github
How to post code using bbtags
Download my project scripts


Reply
#8
(May-31-2020, 03:17 PM)ibutun Wrote: 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 ?

The isdigit() method only returns True if every character in the string is a digit. The '.' in a float value is not a digit, so isdigit() returns False for a float. You can use isalpha() to make sure all of the characters are letters, or you could use isalpha() and istitle() together to ensure the first letter is capitalized. (You could also just use istitle() in your print statement like menator01 does.)

while True: my_name = input('What is your name? ') if not my_name.isalpha(): print('Please use only letters for your name.') continue else: print(f'Your name is {my_name}.') print('The length of your name is', len(my_name), 'characters.') break while True: try: my_age = int(input(f'What is your age, {my_name}? ')) print('Your age is ' + str(my_age) + '.') print('You will be ' + str(my_age + 1) + ' in one year.') break except ValueError: print('Please use only whole numbers for your age.') continue
Reply
#9
Use try and except in the following manner.

try:
Code to be ran if user entered int
except:
Code to be ran if user did not enter integer.
Reply
#10
@ibutun also remember, if you have a question, please do not post it in a thread start by another person - start your own thread. Please do that in the future
pyzyx3qwerty
"The greatest glory in living lies not in never falling, but in rising every time we fall." - Nelson Mandela
Need help on the forum? Visit help @ python forum
For learning more and more about python, visit Python docs
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
Question Two arguments in input function Alfredd 4 736 Nov-09-2025, 12:56 AM
Last Post: Pedroski55
  Using a For Loop to subtract numbers from an input function. Anunderling 9 2,656 Sep-22-2025, 08:56 PM
Last Post: deanhystad
  data input while debugging causes unwanted code completion fred1232 2 2,588 Sep-14-2025, 03:32 PM
Last Post: deanhystad
Question Call CLI app with input? Winfried 5 1,227 May-23-2025, 07:52 PM
Last Post: snippsat
  Βad Input on line 12 Azdaghost 5 2,161 Apr-19-2025, 10:22 PM
Last Post: Azdaghost
  interactive process for input and output maiya 1 2,081 Mar-27-2025, 08:40 AM
Last Post: Gribouillis
  How to revert back to a previous line from user input Sharkenn64u 2 2,990 Dec-28-2024, 08:02 AM
Last Post: Pedroski55
  How to make it so whatever I input into a script gets outputted on a different file spermatozwario 4 1,873 Nov-24-2024, 12:58 PM
Last Post: deanhystad
Question [SOLVED] Same input different output antarling 2 1,519 Oct-25-2024, 11:28 PM
Last Post: antarling
  I think I need to delete input data because returning to start fails thelad 2 1,676 Sep-24-2024, 10:12 AM
Last Post: thelad

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020
This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.