Python Forum
Dealing with errors in input
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Dealing with errors in input
#5
(Apr-09-2019, 12:37 PM)souprqtpie Wrote: 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

>>> value = '2, 3'                   # user enters with a comma
>>> value.split()                    # comma is retained by split()
['2,', '3']
>>> [int(v) for v in value.split()]  # comma prevents converting to integer
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '2,'
>>> value.replace(',', ' ')                            # replace gets rid of the comma
'2  3'
>>> value.replace(',', ' ').split()                    # you can chain it with split, to get the two numbers entered
['2', '3']
>>> [int(v) for v in value.replace(',', ' ').split()]  # now you can convert to integer
[2, 3]
In terms of measuring two numbers at once, it depends on what you are measuring. If you are just checking a range, you can use min and max:

if min(values) < low or max(values) > high:
    print('Please enter numbers in the range {} to {}.'.format(low, high))
If you are checking them with a function that returns True if the number is valid, you can use map and all:

if all(map(check_function, valid)):
    print('All numbers are valid')
Map will pass each number in valid as a parameter to check_function, and return a list of all the return values. All will return true if all the values in a sequence evaluate to True, and False if any of them don't.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
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