First of all, you have the following construct:
if yn == "n":
exit()
else:
lots
of
code
But if yn
equals "n"
, the exit()
will have been executed, and you won't reach any other lines anyway. So you can just write
if yn == "n":
exit()
lots
of
code
This is like an 'early return' (except not in a function, but in the main body of code).
Second, you have
x =int( random.choice(range(1,100)))
...
a = str(x)
...
print "What is " + a + " x " + b + "?"
The spacing on the line with x =
is off. It should be
x = int(random.choice(range(1, 100))
That is: no spaces next to (
and )
. A space on each side of the =
, and a space after the ,
.
Furthermore, you should really use string formatting, allowing you to write
print "What is {} + {}?".format(x, y)
This way you don't need intermediate variables a
and b
.
I assume ua
means user_answer
here:
print "What is " + a + " x " + b + "?"
ua = int(raw_input("What is the answer? "))
Why not just write
problem = "What is {} x {}? ".format(x, y)
user_answer = int(raw_input(problem))
You're basically asking a question, and then "What is the answer to the question?". Better to just ask the question alone.
Instead of writing xy
, you could write solution
or answer
.
Another thing of note: the score (I assume that's what you mean with s
) gets reset to 0
each time you get a new problem statement, but the score (t
) is only printed at the end of the rounds.
That is, you have (pseudo-code)
while play_again:
...
s = 0
answered = ...
while answered != solution:
answered = ...
s -= 1 # You had s = s - 1, that is equivalent to s -= 1
s += 1
t = str(s)
print "Your score is " + t
While instead I think you mean
s = 0
while play_again:
...
answered = ...
while answered != solution:
answered = ...
s -= 1 # You had s = s - 1, that is equivalent to s -= 1
s += 1
t = str(s)
print "Your score is " + t
Note that the last two lines can be replaced with
print "Your score is {}".format(s)
(Also note: if the user inputs something different from y
or n
on the first go, you get a NameError
: t
is referenced before it is assigned because you never enter the while
loop).