Oiral
Oiral

Reputation: 23

Integer in a string python

so I am trying to get a small little addition game working. I have a random number generator working.

    import random


    num1 = gen(10)
    num2 = gen(10)
    answer = int(input('What is', num1, '+', num2))
    print(answer)

I just want the input line to ask the program to ask "what is (random number)+(random number)"

Upvotes: 1

Views: 158

Answers (5)

W --
W --

Reputation: 314

import random

num1 = gen(10)
num2 = gen(10)

sum = num1    #The sum of your 2 random numbers

correct = False

while not correct:  
    #If they haven't answered correctly, keep asking the question, otherwise move on.
    answer = int(input('What is', num1, '+', num2))

    if answer == sum:
        print("Correct! The answer was: ", answer)
        correct = True
    else:
        print("Incorrect, try again!")

Upvotes: 1

Xeomorpher
Xeomorpher

Reputation: 141

Is this python 3 or python 2?

Regardless of which version of python you are using, input requires a single argument - In this case a string.

You thus need to create a string which contains the numbers. There are several ways to do this:

"What is %s + %s"%(num1, num2)

or

"What is "+str(num1)+" + "+str(num2)

or

"What is {} + {}".format(num1, num2)

Earlier versions of python may not work with the last example, but at least one should be okay.

I would also advise that you enclose your conversion of an input to an int in a try, to prevent users creating exceptions by entering something that isn't an int.

while 1:
    try:
        answer = int(input("What is {} + {}".format(num1, num2))
        break
    except ValueError:
        print "Try again.."

For example with something like that

Upvotes: 4

rurouni88
rurouni88

Reputation: 1173

Try:

answer = raw_input(print("what is %d + %d" (num1, num2))

Upvotes: 2

thiagowfx
thiagowfx

Reputation: 5770

answer = int(input('What is %d + %d? ' % (num1, num2)))

Upvotes: 2

R Sahu
R Sahu

Reputation: 206717

answer = int(input('What is ' + str(num1) + '+' + str(num2)))

Upvotes: 2

Related Questions