简化许多if语句

时间:2019-01-22 03:47:38

标签: python if-statement

我想简化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')

2 个答案:

答案 0 :(得分:1)

通过将斑点组织到列表中并使用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进行编程,则可以进行其他优化(例如完全没有匝数列表)。

答案 1 :(得分:0)

如果我不误解您要做什么,那么我认为使用列表可以更有效地做到这一点。

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']