-1

My approach with this function is that it only accepts an integer as an input, otherwise if the person enters a letter or something else it goes back to the while loop and continues asking for the input until it receives the correct input which in this case it can only be 1-9.

import string
string.ascii_letters
def player_choice(board):
    position = 0
    while position not in list(range(1,10)) or space_check(board, position) or position in list[string.ascii_letters]:
        if position in list[string.ascii_letters]:
            pass
        position = int(input("Please enter a position(1-9): "))
    return position

I tried importing ascii_letters from the string library to tell python that if the input is inside of the that list to go back to the while loop, but everytime I run the code i get a syntax error saying that the input only accepts an integer.

  • 1
    Does this answer your question? [How can I limit the user input to only integers in Python](https://stackoverflow.com/questions/23326099/how-can-i-limit-the-user-input-to-only-integers-in-python) – Pranav Hosangadi Nov 20 '22 at 22:39
  • Or this one: https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response – Pranav Hosangadi Nov 20 '22 at 22:40

2 Answers2

1

First solution using simple checkings

def player_choice(board):
    while True:
        position = input("Please enter a position(1-9): ")
        if position.isdecimal() and len(position) == 1 and position != '0':
            position = int(position)
            break
    return position

Second solution using regex

import re

def player_choice(board):
    while True:
        position = input("Please enter a position(1-9): ")
        if re.match('^[1-9]$', position):
            position = int(position)
            break
    return position
puf
  • 359
  • 3
  • 13
-2

Use typing.

def whatever(param: int):

Lucas Vale
  • 19
  • 4
  • 4
    Unless you use an interpreter that enforces them, type **hints** are just that -- _hints!_. Even if you were to use such an interpreter, typing it as an integer does nothing to ensure that the value returned by `input` is actually a numeric value. – Pranav Hosangadi Nov 21 '22 at 06:43