如何修改Python代码实现连续随机数学题出题、计分及答题次数统计
Python数学答题程序修改方案
核心修改点
- 新增
while True无限循环包裹出题逻辑,支持连续出题 - 新增
total_attempts变量统计总答题次数,和累计得分同步更新 - 新增主动终止逻辑:每次答题完成后用户输入
q即可退出程序,输入其他内容继续出题 - 新增输入容错处理:避免用户输入非整数内容时程序崩溃
- 修复原代码乘法题输入提示的符号错误(原误将乘号写为减号)
完整可运行代码
#-Importation des modules import random #Define operations Operation = ("Addition", "Soustraction", "Multiplication", "Division", "Exposant", "Pente", "Point de Millieu") score = 0 # 累计得分 total_attempts = 0 # 总答题次数 while True: Question = random.choice(Operation) # 每次循环随机选择运算类型 #Les questions #Addition if Question == "Addition": num1 = random.randint(10,100) num2 = random.randint(50,200) BnReponse = num1 + num2 #Right answer print(f"Trouve la somme de {num1}+{num2}") # 输入容错处理 while True: try: ReponseUs = int(input(f"C'est quoi la somme de {num1}+{num2} est: ")) #User's answer break except ValueError: print("Veuillez entrer un nombre valide !") total_attempts += 1 if ReponseUs == BnReponse: print("Correct") score+=1 else: print(f"Incorrect, la reponse est {BnReponse}") #Soustraction elif Question == "Soustraction": num1 = random.randint(100,200) num2 = random.randint(10,80) BnReponse = num1 - num2 #La bonne reponse print(f"Trouve la difference de {num1}-{num2}") while True: try: ReponseUs = int(input(f"C'est quoi la difference de {num1}-{num2} est: ")) break except ValueError: print("Veuillez entrer un nombre valide !") total_attempts += 1 if ReponseUs == BnReponse: print("Correct") score+=1 else: print(f"Incorrect, la reponse est {BnReponse}") #Multiplication elif Question == "Multiplication": num1 = random.randint(10,20) num2 = random.randint(10,20) BnReponse = num1 * num2 #La bonne reponse print(f"Trouve le quotient de {num1}*{num2}") while True: try: ReponseUs = int(input(f"C'est quoi le quotient de {num1}*{num2} est: ")) break except ValueError: print("Veuillez entrer un nombre valide !") total_attempts += 1 if ReponseUs == BnReponse: print("Correct") score+=1 else: print(f"Incorrect, la reponse est {BnReponse}") # 打印当前统计数据 print(f"\nStatistiques actuelles :") print(f"Score total : {score}") print(f"Nombre total de réponses : {total_attempts}") # 退出判断 exit_choice = input("\nEntrez q pour quitter, appuyez sur Entrée pour continuer : ") if exit_choice.lower() == 'q': print(f"\nSession terminée ! Score final : {score}/{total_attempts}") break
内容的提问来源于stack exchange,提问作者imti
相关产品推荐
相关产品推荐

