在python中创建一个基本的乘法程序

时间:2012-06-08 16:22:51

标签: python input python-2.7

该程序的目标是将两个小于12的随机数相乘,并让用户猜出答案。到目前为止我有这个。 。

import random

g=0
while g<10:
    variable_1 = random.randint (0,13)
    variable_2 = random.randint (0,13)

    answer = variable_1 * variable_2
    guess = input("What is 'variable_1' x 'variable_2'?")

    if guess == answer:
        print "Correct!"
    else:
        print "Incorrect!"

问题是输入框字面上写着“什么是Variable_1 x Variable_2?”。但是,我希望它在输入框中具有变量的值。有没有办法做到这一点?

3 个答案:

答案 0 :(得分:6)

请改为尝试:

guess = input("What is %d x %d?" % (variable_1, variable_2))

答案 1 :(得分:1)

querystr="What is "+str(variable_1)+" x "+str(variable_2)+"?";

然后你可以

guess=input(querystr);

答案 2 :(得分:1)

from random import randint

def val(lo=1, hi=12):
    return randint(lo, hi)

def main():
    right = 0
    reps = 10
    for rep in range(reps):
        v1, v2 = val(), val()
        target = v1 * v2

        guess = int(raw_input("What is {} * {}?".format(v1, v2)))

        if guess==target:
            print("Very good!")
            right += 1
        else:
            print("Sorry - it was {}".format(target))

    print("You got {} / {} correct.".format(right, reps))