希望有人能帮我解决这个问题。 我认为我需要使用 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/