Python 如何减少多个if elif块中的冗余?
我正在使用一个名为Draw.py的GUI包编写一个“问答游戏”。 我是新手,我真的不知道如何减少代码的冗余 代码运行得非常完美,但我知道它并不完全整洁。Python 如何减少多个if elif块中的冗余?,python,dictionary,if-statement,redundancy,Python,Dictionary,If Statement,Redundancy,我正在使用一个名为Draw.py的GUI包编写一个“问答游戏”。 我是新手,我真的不知道如何减少代码的冗余 代码运行得非常完美,但我知道它并不完全整洁。 以下是我想减少的: def question1(): question("Which device would \n you most want to have?") #draws #question answer1() #draws the answer boxes. mouseclicks = 0 wh
以下是我想减少的:
def question1():
question("Which device would \n you most want to have?") #draws #question
answer1() #draws the answer boxes.
mouseclicks = 0
while mouseclicks != 1:
if Draw.mousePressed(): #checks if the user clicks.
xCoord= Draw.mouseX() #check x-y coordinates
yCoord= Draw.mouseY()
if xCoord >= 91 and xCoord <= 390 and yCoord >= 400 \
and yCoord <= 552:
ChooseAnswer(88,400,300,150) #Chosen answer, turns green #when user clicks
characters["question 1"]["PC"] += 1
mouseclicks += 1
answer1()
elif xCoord >= 601 and xCoord <= 900 and yCoord >= 402 \
and yCoord <= 550:
ChooseAnswer(600,400,300,150)
characters["question 1"]["BJ"] += 1
mouseclicks += 1
answer1()
elif xCoord >= 92 and xCoord <= 388 and yCoord >= 602 \
and yCoord <= 750:
ChooseAnswer(88,600,300,150)
characters["question 1"]["Mr.P"] += 1
mouseclicks += 1
answer1()
elif xCoord >= 602 and xCoord <= 902 and yCoord >= 603 \
and yCoord <= 750:
ChooseAnswer(600,600,300,150)
characters["question 1"]["Diane"] += 1
mouseclicks += 1
answer1()
def question1():
问题(“您最想要什么设备?”)#吸引#问题
answer1()#绘制答案框。
mouseclicks=0
当鼠标点击时!=1:
if Draw.mousePressed():#检查用户是否单击。
xCoord=Draw.mouseX()#检查x-y坐标
yCoord=Draw.mouseY()
如果xCoord>=91且xCoord=400\
yCoord=601,xCoord=402\
yCoord=92,xCoord=602\
yCoord=602,xCoord=603\
而yCoord您可以做的是创建坐标列表,为ChooseAnswer
和字符的键创建参数,如下所示:
coordinates = [(91, 390, 400, 552),
(601, 900, 402, 550),
(92, 388, 602, 750),
(602, 902, 603, 750)]
answers = [(88, 400, 300, 150),
(600, 400, 300, 150),
(88, 600, 300, 150),
(600, 600, 300, 150)]
keys = ["PC", "BJ", "Mr.P", "Diane"]
然后迭代坐标
,检查哪些坐标满足您的条件,最后使用相应的参数调用选择拒绝
,并为相应的键增加字符的值
:
for index, coordinate in enumerate(coordinates):
if (coordinate[0] <= xCoord <= coordinate[1]
and coordinate[2] <= yCoord <= coordinate[3]):
ChooseAnswer(*answers[index])
characters["question 1"][keys[index]] += 1
mouseclicks += 1
answer1()
对于索引,枚举中的坐标(坐标):
if(coordinate[0]Esther,你是否尝试过为你的代码实现一些单元测试?如果你认为有帮助的话,我建议尝试使用一些测试驱动的开发技术来提高你的编码技能。你可以为参数化函数重构代码,删除这些函数中重复的coed。为更改创建参数。