In this code i am trying to randomly create division questions for primary school age (10 years) so I don't want any remainders when it dividies. This is the code I have, but I am unsure on how to do the divide thing.
for i in range (0,2) :
import random
number1 = random.randint (20,30)
number2 = random.randint (2,5)
answer4 = (number1 / number2)
question4 = int(input('What is %d / %d?: ' %(number1, number2)))
if question4 == answer4:
print ('Well done')
score += 1
else:
print ('Wrong! The answer is %d' %(answer4))
print ('You have finished the quiz! Well done!')
print ('Your overall score is %d out of 10' %score)
This is part of a part of a bigger quiz with other questions, but I was unsure of this part, so any help would be welcomed.
In Python, there are two types of division operators: / : Divides the number on its left by the number on its right and returns a floating point value. // : Divides the number on its left by the number on its right, rounds down the answer, and returns a whole number.
You can't divide by zero! If you don't specify an exception type on the except line, it will cheerfully catch all exceptions. This is generally a bad idea in production code, since it means your program will blissfully ignore unexpected errors as well as ones which the except block is actually prepared to handle.
In Python, you use the double slash // operator to perform floor division. This // operator divides the first number by the second number and rounds the result down to the nearest integer (or whole number).
you can do 2//5 and get 2 instead of the 2.5 you'd get with 2/5
As long as you're in Python 3
you can also use floor(2/5).
Both ways of doing it give you the floor-rounded answer
In python 3, the standard division operator /
will do "real" division, while the //
operator will do integer division.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With