Python Forum
Dealing with errors in input
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dealing with errors in input
#3
(Apr-09-2019, 12:08 PM)ichabod801 Wrote: There are a number of ways you can deal with this. You could do two separate inputs to get the different numbers. You could be explicit about needing a space. You could replace other common delimiters with spaces before splitting (input('Enter two numbers: ').replace(',', ' ').split()). You could write a regular expression matching valid numbers, and use findall to get a list of valid numbers in the input.

If you want to give multiple chances to correct the input, a while True loop is often used:

while True:
    values = input('Enter two numbers: ')
    try:
        # to convert to integer
    except ValueError:
        print('Invalid input')
    else:
        break
Instead of (or in addition to) the try/except block, you might check for a valid range or other issues with if/else, again breaking if the input is valid.

thanks for the answer!
could you explain the replace bit to me in a little more detail please showing how it works. ( I am trying to keep both numbers on the same input line). I've done the while true loop before, but I didn't know how to get it to measure both numbers at once without making a separate loop for each one
Reply


Messages In This Thread
Dealing with errors in input - by souprqtpie - Apr-09-2019, 11:55 AM
RE: Dealing with errors in input - by ichabod801 - Apr-09-2019, 12:08 PM
RE: Dealing with errors in input - by souprqtpie - Apr-09-2019, 12:37 PM
RE: Dealing with errors in input - by perfringo - Apr-09-2019, 01:23 PM
RE: Dealing with errors in input - by ichabod801 - Apr-09-2019, 01:54 PM
RE: Dealing with errors in input - by souprqtpie - Apr-09-2019, 02:48 PM
RE: Dealing with errors in input - by ichabod801 - Apr-09-2019, 07:58 PM
RE: Dealing with errors in input - by souprqtpie - Apr-10-2019, 11:04 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Dealing with duplicates to an Excel sheet DistraughtMuffin 6 3,381 Oct-28-2020, 05:16 PM
Last Post: Askic
  Dealing with list coja56 2 2,905 Sep-18-2020, 09:32 PM
Last Post: perfringo

Forum Jump:

User Panel Messages

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