首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >简化许多if语句

简化许多if语句
EN

Stack Overflow用户
提问于 2019-01-22 11:47:38
回答 2查看 57关注 0票数 1

我想简化if语句,而不是输入fifth_turn == each_turn_before

代码语言:javascript
复制
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')
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2019-01-22 12:02:31

通过将spots组织到一个列表中并使用in运算符,可以在代码中进行很多改进:

代码语言:javascript
复制
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“是非常缺乏信息的,因为它不会告诉用户实际发生了什么以及如何修复它。

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

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2019-01-22 13:44:20

如果我没有误解您正在尝试做的事情,我认为使用列表可以更有效地完成它。

代码语言:javascript
复制
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']
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/54300978

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档