未输入坐标时的验证

时间:2016-03-17 19:02:18

标签: python

我有一个python程序,我不太清楚如何让它工作,每次我尝试时都会出现错误。基本上,提示用户输入一组坐标,当我没有输入坐标时按空格键时会抛出错误。我尝试使用try:except ValueError:,但没有成功。我也尝试添加if (Coordinates == ""):但也没有成功。

以下是代码:

def GetHumanPlayerMove(PlayerName):
  print(PlayerName, "enter the coodinates of the square where you want to place your piece: ", end="")
  Coordinates = int(input())
return Coordinates

知道如何解决这个问题吗?

编辑:try and except commands

def GetHumanPlayerMove(PlayerName):
  try:
    Coordinates = int(input(str(PlayerName), "enter the coodinates of the square where you want to place your piece: ", str(end="")))
  except ValueError:
    print(Coordinates)
  return Coordinates

此外,end=""末尾的print位代码有什么作用?

2 个答案:

答案 0 :(得分:3)

您可以在将输入更改为int之前验证输入。

def GetHumanPlayerMove(player_name):
  print(player_name, "enter the coodinates of the square where you want to place your piece: ", end="")
  inp = input()
  if inp and inp.isdigit():
     coordinates = int(inp)
  else:
    return 0
  return coordinates
如果接收到无效输入,

函数返回0,否则返回结果本身 end=""使打印件保持在同一行并且不发送\n(新行)

答案 1 :(得分:1)

你做错了:

def get_human_player_move(player_name):
    while True:
        coordinates = input("{} enter the coordinates of the square where you want to place your piece: ".format(player_name))
        try:
            return int(coordinates)
        except TypeError:
            print "coordinates must be a number"

为什么我这么自由地修改你的代码?

  1. 永远不要将CamelCase用于变量或函数,仅用于类
  2. PY2中不需要打印然后输入/ raw_input
  3. 强制用户给你一个正确的号码,直到他做(循环)