1

I want to build a while loop if user gives an input in a incorrect way, it says invalid input and try again. The input from user should be numbers separated by comma then it will be stored in a list. The input is given like:

number = input("input your number? (separated by comma): ")
number_list = number.split(',')
numbers = [int(x.strip()) for x in number_list]
print(numbers)

But the problem I dont know how to check if the input is numbers separated by comma. So for example if user input 0,1 it will be stored in a list like [0,1]. and when user input anything other than number like 'b' it should ask user to give a correct input.

so ideal code would be something like:

# Start a loop that will run until the user a give valid input.
while numbers != 'List of Numbers separated by comma':
   # Ask user for input.
   number = input("input your number? (separated by comma): ")
   number_list = number.split(',')
   numbers = [int(x.strip()) for x in number_list]

   # Add the new name to our list.
   if numbers == 'List of Numbers separated by comma':
       print(numbers)
   else:
       print('Gave an incorrect input, please try again')

Thank you for your help.

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
MNVLEY
  • 47
  • 1
  • 5
  • Doesn't your existing code throw an exception when input _isn't_ conformant? Have you considered handling that exception? – Charles Duffy Sep 09 '20 at 15:28

2 Answers2

3

Adapted from the duplicate flagged by Trenton McKinney.

Please try more test cases , incase i am wrong

For what i have tried , i am getting the resulted output.

while True:
    test=input("Nums sep by comma: ")
    test_list = test.split(',')
    try:
        numbers = [int(x.strip()) for x in test_list]
    except:
        print('please try again, with only numbers separated by commas (e.g. "1, 5, 3")')
        continue
    else:
        print(numbers)
        break
print(numbers)

Testing

Nums sep by comma: 1, asdf
please try again, with only numbers separated by commas (e.g. "1, 5, 3")
Nums sep by comma: 1, 2, 5
[1, 2, 5]
        
RichieV
  • 5,103
  • 2
  • 11
  • 24
Sandrin Joy
  • 1,120
  • 10
  • 28
2

You could use regex to find the value so that only certain characters are accepted.

import re

pattern = re.compile(r"^[0-9\,]*$")
print(pattern.findall("z")
print(pattern.findall("1,2,3,4")

>> []
>> [1,2,3,4]

Break down of ^[0-9\,]*$

^ - Start of string

[ ... ] - one of the character in the brackets

0-9 - Any number between 0 and 9

\, - Include comma, where \ escapes the special comma character

* - Zero or more

$ - End of string

tyleax
  • 1,556
  • 2
  • 17
  • 45