简化许多if语句

2024-04-25 02:21:49 发布

您现在位置:Python中文网/ 问答频道 /正文

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

Tags: orinput键入iftable语句selectturn
2条回答

如果我没有误解你的意图,我认为使用列表可以更有效地完成。你知道吗

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

通过将点组织到一个列表中并使用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')

顺便说一句,打印“错误”是非常缺乏信息的,因为它没有告诉用户实际发生了什么以及如何修复它。你知道吗

你也应该考虑有一个轮次列表,而不是五个(或更多?)转向变量:

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,其他的优化是可能的(比如根本没有转弯列表)。你知道吗

相关问题 更多 >