【问题标题】:Python maths quiz random number [closed]Python数学测验随机数[关闭]
【发布时间】:2015-05-08 06:02:14
【问题描述】:

你好,我正在尝试为随机数学测验生成器编写代码,我有它,所以它随机数字和操作,但我不能让它重复 10 次,因为我希望它问 10 个问题,有人可以在这里帮忙吗是我的代码

import random
import time

name=input("What is your name?")
print ("Alright",name,"Welcome to your maths quiz")
score=0
question=0
finish= False
ops = ['+', '-', '*']
rand=random.randint(1,10)
rand2=random.randint(1,10)
operation = random.choice(ops)
maths = eval(str(rand) + operation + str(rand2))
print ("Your first question is",rand,operation,rand2)
question=question+1
d=int(input ("What is your answer:"))
if d==maths:
    print ("Correct")
    score=score+1
else:
    print ("Incorrect. The actual answer is",maths)

【问题讨论】:

  • 我尝试了一个 while 循环,但我不知道我在做什么,因为我对 python 很陌生
  • 你在开玩笑吗?你写了这个,但你不知道如何重复它 10 次??
  • 你可以使用while循环。 while question <= 10: 然后是您的其余代码,然后是您已经完成的 question=question+1
  • for _ in range(5): print('hi').

标签: python loops math random


【解决方案1】:

使用带有条件的 while 循环。

算法:

  1. counter 设置为0
  2. 使用while 循环并检查counter 是否小于10
  3. 向用户提问。
  4. 计算一下。
  5. counter 加一。
  6. counter 等于10 时,那个时候condition 将是False

演示:

>>> counter = 0
>>> while counter<10:
...    que = raw_input("Enter que:")
...    print que
...    counter += 1
... 
Enter que:1
1
Enter que:2
2
Enter que:3
3
Enter que:4
4
Enter que:5
5
Enter que:6
6
Enter que:7
7
Enter que:8
8
Enter que:9
9
Enter que:10
10
>>> 

【讨论】:

    【解决方案2】:

    使用for 循环:

    for num in range(5): 
        # Replace "print" below, with the code you want to repeat.
        print(num)
    

    要重复所有问题,不包括"whats your name..",请在循环中包含您需要的代码部分:

    import random
    
    name=input("What is your name?")
    print ("Alright",name,"Welcome to your maths quiz")
    score=0
    
    for question_num in range(1, 11):
        ops = ['+', '-', '*']
        rand=random.randint(1,10)
        rand2=random.randint(1,10)
        operation = random.choice(ops)
        maths = eval(str(rand) + operation + str(rand2))
        print('\nQuestion number: {}'.format(question_num))
        print ("The question is",rand,operation,rand2)
    
        d=int(input ("What is your answer:"))
        if d==maths:
            print ("Correct")
            score=score+1
        else:
            print ("Incorrect. The actual answer is",maths)
    

    【讨论】:

    • for question_num in range(1, 10): 会运行多少次? 10 还是 9?
    • @VivekSable 你是对的,固定的。
    猜你喜欢
    • 2011-11-30
    • 1970-01-01
    • 2015-04-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-29
    • 1970-01-01
    相关资源
    最近更新 更多