Python Forum
if the input is not number, let user input again - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: if the input is not number, let user input again (/thread-27227.html)

Pages: 1 2


RE: if the input is not number, let user input again - GOTO10 - May-31-2020

(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



RE: if the input is not number, let user input again - ibutun - May-31-2020

thanks alot friends


RE: if the input is not number, let user input again - BitPythoner - May-31-2020

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.


RE: if the input is not number, let user input again - pyzyx3qwerty - Jun-01-2020

@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


RE: if the input is not number, let user input again - ibutun - Jun-02-2020

@pyzyx3qwerty sorry i will not do it again.. :)