简体   繁体   English

定义一个 function 只接受一个 integer 作为输入

[英]Defining a function that only accepts an integer as an input

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.我对这个 function 的处理方法是它只接受一个 integer 作为输入,否则如果这个人输入一个字母或其他东西它会回到 while 循环并继续询问输入直到它收到正确的输入,在这种情况下它只能是 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.我尝试从字符串库中导入 ascii_letters 以告诉 python 如果输入在该列表内到 go 回到 while 循环,但每次运行代码时我都会收到语法错误,指出输入只接受 integer。

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

Use typing.使用打字。

def whatever(param: int):定义什么(参数:int):

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM