(Python) Generating Numbers then Printing them on One Line - python

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.

Try this,
print number1, '+', number2

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:
str.format
string formatting with the % operator
Python tutorial

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.)

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)

Related

Answer appears as a float and I don't know why in python

I am doing a programming project. It gives a user (aimed for primary school students) a randomly generated question. When I do my division code the answer is a real/float variable meaning that unless the user has a .0 at the end of a whole number, their answer is processed as incorrect. My code is:
while True:
num1 = str((random.randint(0,12)))
num2 = str((random.randint(0,12)))
if num1 >= num2:
question = (num1 + " " + "/" + " " + num2)
print(question)
answer = str((int(num1) / int(num2)))
reply = str(input())
if reply == answer:
score = score + 1
print("Correct")
break
else:
print("Incorrect")
print("The answer was", answer)
break
else:
print("")
I understand that sometimes the answer will have a decimal point in it but is there a way of allowing a whole number to not have a .0 at the end. If not then how can I improve the code so I don't get this issue. Any help is appreciated. My python-idle version is 3.8
/ is float division in Python. If you want to get an int with the line answer = str((int(num1) / int(num2))) then you should be using // instead, which is integer division.

TypeError trying to create a maths quiz in Python

The line
question = str(input("What is",randomNumber1,"+",randomNumber2,"x",randomNumber3,"?\n"))
in my code is giving me trouble.
This is the error I get:
question = str(input("What is",randomNumber1,"+",randomNumber2,"x",randomNumber3,"?\n"))
TypeError: input expected at most 1 arguments, got 7
If you could help it would be much appreciated as I don't know what I have done wrong.
You are using , in your parentheses for your strings. So Python thinks, these are parameters for your called function. You need to append your strings together (via + as already mentioned).
Furthermore, you should consider raw_input in Python2, because input is interpreted as Python code: look here
Like the output already says.
question = str(input("What is"+randomNumber1+"+"+randomNumber2+"x"+randomNumber3+"?\n"))
You are using , while calling the function input(). As a result, python interprets it to be 7 different arguments.
I guess, the following code will do what you require.
question = str(input("What is " + str(randomNumber1) + " + " + str(randomNumber2) + " x " + str(randomNumber3) + " ?\n"))
Do note, this will store the answer provided by the user as a string in the variable question.
If you require to accept the answer as an integer (number) use the following instead.
question = input("What is " + str(randomNumber1) + " + " + str(randomNumber2) + " x " + str(randomNumber3) + " ?\n")
Are you Python 3? If you are Python 2 then you should use raw_input() instead of input(). If you are using Python 3 then please try to use that tag (most will assume "Python" means Python 2).
input() and raw_input() both return strings (no need to force it), and they only take one argument, as the error message said. Also your comparison for the correct answer uses different types, you are comparing a string with an int.
Best to construct the question first as a string:
question = "What is %d + %d x %d? " % (randomNumber1,randomNumber2,randomNumber3)
users_answer = input(question)
answer = randomNumber1 + randomNumber2 * randomNumber3
# users_answer and answer are different types
if int(users_answer) == answer:
print("\n[ Correct ]\n")
playerScore = playerScore + 1
print("Your score is",playerScore)
questionNumber = questionNumber + 1
else:
print("\n[ Incorrect ]\n")
questionNumber = questionNumber + 1

Taking apart strings in Python

So I am making a quick calculator script in Python, and I need to take apart a short string. The program first displays a short welcome message, then a prompt asks What they want to do calculate, and shows them the correct format. The functionality is there to do the calculation but unfortunately, I can not get the string dissecting bit working.
Here's my code
print ("--------------------------------------")
print (" ")
print ("Advanced Quick Calculator")
print ("By Max M, licenced under GPLv3")
print (" ")
print ("--------------------------------------")
statement = raw_input ("Please enter your mathematical statement [3 3 plus minus times divide]: ")
strnum1 = statement[:1]
print ("strnum1 : " + strnum1)
#num1 = int (strnum1)
strnum2 = statement[:4]
print ("strnum2 : " + strnum2)
#num2 = int (strnum2)
operation = statement[5:11]
print ("operation : " + operation)
#if operation == "+":
# ans = num1 + num2
#if operation == "-":
# ans = num1 - num2
#if operation == "*":
# ans = num1 * num2
#if operation == "/":
# ans = num1 / num2
#print ("The answer is : "), ans
This looks like a job for regular expressions:
>>> import re
>>> match = re.search(r'(\d+)\s*([+*/-])\s*(\d+)', '42 + 7')
>>> match.group(1) # <-- num1
'42'
>>> match.group(2) # <-- operation
'+'
>>> match.group(3) # <-- num2
'7'
Slicing the input like you're currently doing is probably not a good idea as it greatly restricts the allowed formats. For instance, what if the user accidentally precedes his input with a couple of spaces? Regular expressions can handle such cases well.
I'm not going to do your homework for you, but I will point you to the answer to your question (hint: it looks like you're trying to split on spaces instead of comma's like in the link, so adjust the code accordingly).
How to read formatted input in python?

How to improve on my Division program? (Easy Python)

I am currently trying to make a division program which asks random division questions. There are 2 things blocking me from doing so: 1)My program thinks that everything divided by something is always 0. e.g. 8 divided by 2 = 0. 2) I need to make division without a floating point, like 144/5. So here it is:
import sys
import random
guessRight=0
guessWrong=0
while True:
num1 = random.randint(0,12) #probably messed up here
num2 = random.randint(12,144) #and here
print "To exit this game type 'exit'"
theyputinstuffhere = raw_input("What is " + str(num2) + " divided by " + str(num1) + "? ") #maybe messed up here
if theyputinstuffhere == "exit":
print "Now exiting game!"
sys.exit()
elif int(theyputinstuffhere) == num1/num2: #maybe messed this whole elif too
print num1/num2
print "Correct!"
guessRight=guessRight+1
print "You have gotten " + str(guessRight) + " answer(s) right and you got " + str(guessWrong) + " wrong"
else:
print "Wrong! The correct answer is: " + str(num1/num2)
guessWrong=guessWrong+1
print "You have gotten " + str(guessRight) + " answer(s) right and you got " + str(guessWrong) + " wrong"
This is what it currently prints:
To exit this game type 'exit'
What is 34 divided by 11? #I type any number (e.g. 3)
Wrong! The correct answer is: 0
You have gotten 0 answer(s) right and you got 1 wrong
If you are asking for num2 divided by num1, then you need to use num2/num1 in your code, not num1/num2. This is also why you are always getting 0, num1 will always be less than num2 so num1/num2 will be 0 when integer division is used (which is the default for dividing ints on Python 2.x).
To avoid questions like 144/5 and eliminate the division by zero issue you can use the following:
num1 = random.randint(1,12)
num2 = random.randint(1,12) * num1

Display number int in Python

How to display numbers integer in python ?
For example:
number1 = raw_input('Write one number: ')
number2 = raw_input('Write other number: ')
result = number1 + number2
print "The sum of the numbers is: %d" % result # here, display the result of the operatio n.
You want
result = int(number1) + int(number2)
raw_input returns strings.
raw_input returns strings. If you mean for them to be integers, then use int(x) to convert them to ints.
You have to convert the inputted strings into numbers:
result = int(number1) + int(number2)
Like this;
In [1]: numstr="5"
In [2]: int(numstr)
Out[2]: 5
So in your code result = int(number1) + int(number2)
You'd want to do some input sanitation check though. Users have a bad habit of making mistakes.

Categories

Resources