Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to divide without remainders on Python

Tags:

python

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.

like image 744
clare.python Avatar asked Jan 20 '16 17:01

clare.python


People also ask

How do you divide on Python?

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.

How do you use zero division in Python?

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.

What does slash slash do Python?

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


2 Answers

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

like image 63
Tyler Kaminsky Avatar answered Oct 12 '22 22:10

Tyler Kaminsky


In python 3, the standard division operator / will do "real" division, while the // operator will do integer division.

like image 31
Chad S. Avatar answered Oct 12 '22 22:10

Chad S.