-1

I have an assignment that requires me to print 10 random sums, then get the user to enter their answers. I know how to randomly generate numbers, but I need to print the whole sum out, without giving the answer, but with the string I am using it adds them automatically.

This is my code below:

for i in range(10):
        number1 = (random.randint(0,20))
        number2 = (random.randint(0,20))
        print (number1 + number2)
    answer = input("Enter your answer: ")

If someone could help me out I would appreciate it, I believe the line

    print (number1 + number2)

is the problem, as it is adding them when I just want the random numbers printed in the sum.

Thanks in advance,

Flynn.

4 Answers4

1

To convert numbers to a string for concatenation use str().

print str(number1) + ", " + str(number2)

or using natural delimiter

print number1, number2

(The , tells python to output them one after the other with space. str() isn't really necessary in that case.)

kb.
  • 1,955
  • 16
  • 22
1

Try this,

print number1, '+', number2   
Ahmad Siavashi
  • 979
  • 1
  • 12
  • 29
  • 1
    Or `print("{0} + {1}".format(number1, number2)` for a better control of the formatting. – Laurent LAPORTE Sep 12 '16 at 11:18
  • How would I randomise the operation in the sum? – FlynnJackson Sep 12 '16 at 11:21
  • @FlynnJackson Didn't get your question; can you explain? – Ahmad Siavashi Sep 12 '16 at 11:28
  • 1
    @FlynnJackson That's a new question! But anyway, there are several ways to randomly choose an operation. There are _many_ questions on SO asking about this kind of arithmetic quiz program in Python, eg [How can I randomly choose a maths operator and ask recurring maths questions with it?](http://stackoverflow.com/a/26261125/4014959) – PM 2Ring Sep 12 '16 at 11:31
  • No worries, I randomised it from a list of +, -, *, /. It doesnt seem to be registering their functions, appears as if the answer is wrong even if it is correct... Attempting a score system but it wont go up when it is correct – FlynnJackson Sep 12 '16 at 11:37
1

Your following line first computes the sum of the two numbers, then prints it

print (number1 + number2)

you have to print a string:

print(str(number1) + " + " + str(number2))

or prefer formating features instead of concatenation:

print("{} + {}".format(number1, number2))

or:

print("%s + %s" % (number1, number2))

Finally, you may want to read some doc:

Tryph
  • 5,946
  • 28
  • 49
0

This should do the job:

from random import randint

for i in range(10):
  num1 = randint(0,20)
  num2 = randint(0,20)
  answer = input('Sum of %i + %i?: ' % (num1,num2)

Perhaps you know what to do with the rest? (e.g. handling the answer section)

Danail Petrov
  • 1,875
  • 10
  • 12