Python Forum

Full Version: if the input is not number, let user input again
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
(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
thanks alot friends
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.
@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 sorry i will not do it again.. :)
Pages: 1 2