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
#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 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:35 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Waiting for input from serial port, then move on KenHorse 3 996 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 398 Mar-09-2024, 12:33 PM
Last Post: Pedroski55
  difference between forms of input a list to function akbarza 6 1,018 Feb-21-2024, 08:02 PM
Last Post: bterwijn
  pyaudio seems to randomly halt input. elpidiovaldez5 2 362 Jan-22-2024, 09:07 AM
Last Post: elpidiovaldez5
  Receive Input on Same Line? johnywhy 8 703 Jan-16-2024, 03:45 AM
Last Post: johnywhy
  manually input data jpatierno 0 340 Nov-10-2023, 02:32 AM
Last Post: jpatierno
  Using string input for boolean tronic72 3 687 Nov-01-2023, 07:48 AM
Last Post: Gribouillis
  problem in using input command akbarza 4 1,102 Oct-19-2023, 03:27 PM
Last Post: popejose
  problem in entering address of a file in input akbarza 0 648 Oct-18-2023, 08:16 AM
Last Post: akbarza
  Input network device connection info from data file edroche3rd 6 1,003 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