python - 简化许多 if 语句

标签 python if-statement

我想简化 if 语句,而不是输入 fifth_turn == every_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')

最佳答案

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

如果您正在尝试对井字棋进行编程,则可以进行其他优化(例如根本没有回合列表)。

关于python - 简化许多 if 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54300978/

相关文章:

python - Python:最准确的播放时间播放声音样本的方式

python - 如何在 Python 中为 Discord 服务器创建只能使用一次的特定数量的邀请链接

c# - “if(condition) int+ +"and int += "Convert.Toint32(condition)”之间的区别

java - 检查字符串中的一组特定字符(密码)

python - 我怎样才能记住函数中的参数?

python - 如何拆分值并在 pandas 数据框中插入新行?

Python 字符串字节到字节

java - if 语句中 x 可以等于一系列数字/数字范围?

python - 如何测试多个变量与单个值的相等性?

c++ - 简单的 if 语句在应该评估时未评估为真