python - 我可以使用 try except 吗?

标签 python python-2.7 while-loop try-except

希望有人能帮我解决这个问题。 我认为我需要使用 try 和 except 函数来执行我需要的操作,但我不会为发生异常而创建错误。

当用户输入 a1 时,它查看 a1 字典并找到一个 x,因此它不满足 while 循环为真。所以它移动到其他地方。我需要再次提出问题并从 while 循环的顶部重新开始。是否有可能仅仅因为某些东西是假的就触发异常?

这是我正在做的事情

board = {'a1':'x','a2':'_','a3':'_','b1':'_','b2':'_','b3':'_','c1':' ','c2':' ','c3':' '}


def o_move():
    print 'im over at o now'



def x_move():

    ans = raw_input('Player x please Enter a location: ') #ask user for location
    f = board[ans] #current value of dictionary location selected

    while f is '_' or f is ' ':
        board[ans] == 'x' #writes the user location selected to the dictionary
        o_move() #everything was good, move on
        break #break the loop 
    else:

        print 'space not available Try again'   
        ans = raw_input('Player x please Enter a location: ') #ask again



x_move()

最佳答案

一个更简单的方法是让函数 x_move() 在第一次没有选择有效的移动时调用它自己。这样,您就不必编写两个 raw_input() 语句。

这是一种可以简化代码的方法:

board = {'a1':'x','a2':'_','a3':'_','b1':'_','b2':'_','b3':'_','c1':' ','c2':' ','c3':' '}

def o_move():
    print 'im over at o now'

def x_move():
    ans = raw_input('Player x please Enter a location: ')
    open_positions = ['_', ' ']

    if board[ans] in open_positions:
        board[ans] = 'x'
        o_move()
    else:
        print 'space not available Try again'   
        x_move()

x_move()

关于python - 我可以使用 try except 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35135053/

相关文章:

python - 为什么 PyTorch 自定义模块中需要 super 构造函数?

python - PySpark:使用 isin 过滤返回空数据帧

python - 替换字符串中的所有非字母数字字符

python - 如何使用 Selenium 和 Python 2.7 单击表单中的按钮?

python - 使用 beautifulsoup 从多个 url 中抓取

python - 如何让我的 while 循环在 Python 中工作?

python - 从头到尾循环

python - Keras 中 TimeDistributed 层的作用是什么?

python - 使用 WebKitGTK+ 等待网站完全加载

c++ - std::cout 中的递归打印