The goal of the program is for it to multiply two random numbers less than 12 and for the user to guess the answer. So far i have this . . .
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!"
The problem is the input box literally says "What is Variable_1 x Variable_2?". But, i want it to have the value of the variables in the input box. Is there a way to do this?
mechanical_meat
170k25 gold badges238 silver badges231 bronze badges
3 Answers 3
Try this instead:
guess = input("What is %d x %d?" % (variable_1, variable_2))
answered Jun 8, 2012 at 16:35
Maria Zverina
11.2k3 gold badges47 silver badges62 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Maria Zverina
I don't think %i means anything. %d means decimal integer. The list of available types is at docs.python.org/library/string.html#formatspec
jfs
use
int(raw_input(...)) instead of input()Junuxx
@Maria: It does. You aren't using the
format() syntax you linked to, which was introduced in Python 2.6, but the older string formatting syntax, in which %i is a 'signed integer decimal'. So is %d, but IMO that letter is more easily confused with 'double' or 'decimal'. I guess it's a matter of preference.querystr="What is "+str(variable_1)+" x "+str(variable_2)+"?";
Then you can
guess=input(querystr);
Comments
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))
answered Jun 8, 2012 at 16:49
Hugh Bothwell
57k9 gold badges91 silver badges103 bronze badges
Comments
lang-py
randrange(12)to select0 <= x < 12. Your code also selects 12, 13 erroniouslyg. Is this program supposed to loop infinitely?