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
#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 Github
How to post code using bbtags


Reply


Messages In This Thread
RE: if the input is not number, let user input again - by menator01 - May-31-2020, 03:09 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Waiting for input from serial port, then move on KenHorse 3 1,106 Apr-17-2024, 07:21 AM
Last Post: DeaD_EyE
  Help with to check an Input list data with a data read from an external source sacharyya 3 422 Mar-09-2024, 12:33 PM
Last Post: Pedroski55
  difference between forms of input a list to function akbarza 6 1,047 Feb-21-2024, 08:02 PM
Last Post: bterwijn
  pyaudio seems to randomly halt input. elpidiovaldez5 2 397 Jan-22-2024, 09:07 AM
Last Post: elpidiovaldez5
  Receive Input on Same Line? johnywhy 8 736 Jan-16-2024, 03:45 AM
Last Post: johnywhy
  manually input data jpatierno 0 349 Nov-10-2023, 02:32 AM
Last Post: jpatierno
  Using string input for boolean tronic72 3 714 Nov-01-2023, 07:48 AM
Last Post: Gribouillis
  problem in using input command akbarza 4 1,156 Oct-19-2023, 03:27 PM
Last Post: popejose
  problem in entering address of a file in input akbarza 0 661 Oct-18-2023, 08:16 AM
Last Post: akbarza
  Input network device connection info from data file edroche3rd 6 1,070 Oct-12-2023, 02:18 AM
Last Post: edroche3rd

Forum Jump:

User Panel Messages

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