我需要一些幫助使代碼更經濟 - 我相信,我可以削減很多行。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