我想简化if语句,而不是输入fifth_turn == each_turn_before
table()
fifth_turn = int(input('Player #1, select the spot you desire: '))
if fifth_turn == first_turn or fifth_turn == second_turn or fifth_turn == third_turn or fifth_turn == fourth_turn:
print('Spot Taken')
elif fifth_turn == 1:
spot1 = 'x'
elif fifth_turn == 2:
spot2 = 'x'
elif fifth_turn == 3:
spot3 = 'x'
elif fifth_turn == 4:
spot4 = 'x'
elif fifth_turn == 5:
spot5 = 'x'
elif fifth_turn == 6:
spot6 = 'x'
elif fifth_turn == 7:
spot7 = 'x'
elif fifth_turn == 8:
spot8 = 'x'
elif fifth_turn == 9:
spot9 = 'x'
else:
print('ERROR')发布于 2019-01-22 12:02:31
通过将spots组织到一个列表中并使用in运算符,可以在代码中进行很多改进:
spots = [spot1, spot2, spot3, ... spot9] # Initialize the list
fifth_turn = int(input('Player #1, select the spot you desire: '))
if fifth_turn in first_turn, second_turn, third_turn, fourth_turn:
print('Spot Taken')
elif 1 <= fifth_turn <= 9:
spots[fifth_turn - 1] = 'x'
else:
print('ERROR')顺便说一句,打印"ERROR“是非常缺乏信息的,因为它不会告诉用户实际发生了什么以及如何修复它。
你还应该考虑有一个轮换列表,而不是五个(或者更多?)转换变量:
spots = [spot1, spot2, spot3, ... spot9] # Initialize the list
turns = [...] # Initialize the list
turns[4] = int(input('Player #1, select the spot you desire: '))
if turns[4] in turns[:4]:
print('Spot Taken')
elif 1 <= turns[4] <= 9:
spots[turns[4] - 1] = 'x'
else:
print('ERROR')如果您正在尝试编写tic-tac-toe程序,还可以进行其他优化(比如根本没有转弯列表)。
发布于 2019-01-22 13:44:20
如果我没有误解您正在尝试做的事情,我认为使用列表可以更有效地完成它。
spot = ['O' for i in range(9)] # ['O', 'O', 'O', 'O', 'O', 'O', 'O', 'O', 'O']
turn = int(input('Player #1, select the spot you desire: '))
if spot[turn - 1] == 'X': # Zero-indexed list
print("Spot taken")
else:
spot[turn - 1] = 'X' # e.g. ['O', 'O', 'O', 'X', 'O', 'O', 'O', 'O', 'O']https://stackoverflow.com/questions/54300978
复制相似问题