0

I need to be able to accept entries as 3,4 , basically 2 integers seperated by a comma. I need a while loop to keep asking for input until they input it in correct format as 2 numbers. this is my code so far

def main():
    try:
        move = [int(s) for s in input("Select a cell (row,col) > ").split(",")]
    except:
        while move != []#stuck here

    x = move[0]
    y = move[1]



main()
Lamar
  • 217
  • 2
  • 10
  • 1
    I assume you are getting an error. Share it. – Tarik Apr 07 '20 at 14:58
  • Does this answer your question? [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Tomerikoo Apr 07 '20 at 15:01

3 Answers3

4

You can do it by this way:

def main():
  print('Enter the two points as comma seperated, e.g. 3,4')
  while True:
    try:
      x, y = map(int, input().split(','))
    except ValueError:
      print('Enter the two points as comma seperated, e.g. 3,4')
      continue
    else:
      break


main()
Ambitions
  • 2,369
  • 3
  • 13
  • 24
  • 1
    BTW the `strip` is not necessary. `int()` will do it alone. For example, `int(" 3 ")` works just fine and returns the `int` 3 – Tomerikoo Apr 07 '20 at 15:09
  • @Tomerikoo Thank you, I edited it. I did this mistake because I am used to read from files so that I wrote `strip()` – Ambitions Apr 07 '20 at 15:11
  • 1
    I don't think it's a mistake anyway... Just redundant and this way the code is just a bit more easy to read :) – Tomerikoo Apr 07 '20 at 15:12
3

You almost have it. You just need to straighten out a few details. First, if the input fails, you want an empty input:

try:
    move = [int(s) for s in input("Select a cell (row,col) > ").split(",")]
except:
    move = []

Now you want to repeat the input until it is valid. You first need the syntax for a while loop:

while <condition>:
   <body>

Where condition evaluates to a boolean and <body> is the lines to repeat. In this case, you want to repeat the try...except.

def main():
    while move != []:
        try:
            move = [int(s) for s in input("Select a cell (row,col) > ").split(",")]
        except:
            move = []

    x = move[0]
    y = move[1]

When you get stuck on syntax issues like this, I suggest you read the documentation and tutorials at https://python.org. They explain how to correctly write a while loop or try...except and more.

Code-Apprentice
  • 81,660
  • 23
  • 145
  • 268
2

You could do this with a nested function and a recursive call if the input doesn't conform to expectations.

import re


def main():

    def prompt():
        digits = input("Select a cell (row,col) > ")
        if not re.match(r'\d+,\d+', digits):
            print('Error message')
            prompt()
        return digits.split(',')

    move = prompt()

    x = move[0]
    y = move[1]


main()
Badgy
  • 819
  • 4
  • 14