我需要一些帮助使代码更经济 - 我相信,我可以削减很多行。Python - 使我的代码更经济
该代码是关于一个测验,将问10个问题,你的分数将在最后输出。
import random
studentname=input("what is your name?:")
score=0
trueanswer=0
def question():
global operation
global number1
global number2
global studentanswer
global score
number1=random.randrange(1,10)
number2=random.randrange(1,10)
operation=random.choice(["*","-","+"])
print("what is", number1,operation,number2,"?:")
studentanswer=int(input("insert answer:"))
def checking():
global score
if operation == "*":
trueanswer = number1*number2
if studentanswer == trueanswer:
print("correct")
score=score+1
else:
print("incorrect")
score=score
elif operation == "-":
trueanswer = number1-number2
if studentanswer == trueanswer:
print("correct")
score=score+1
else:
print("incorrect")
score=score
elif operation == "+":
trueanswer = number1+number2
if studentanswer == trueanswer:
print("correct")
score = score+1
else:
print("incorrect")
score=score
def main():
for i in range (10):
question()
checking()
print("your score is", score)
main()
先消除明显的重复代码,然后https://docs.python.org/2/library/operator.html –
工作代码应该在codereview.stackexchange.com上提出这样的建议。 – chepner