You haven't called the function!
def test(foundN):
if foundN%2 == 0:
print "The number ", foundN, "is ok."
else:
print "Try another number. "
foundN = input("Enter number: ")
test(foundN)
Answer from Ry- on Stack Overflowprint(-6 % 8) returns 2, not 6. What's the reason for this? Apparently, the operator doesn't produce the remainder. Can someone explain?
python - Find the division remainder of a number - Stack Overflow
Please help me with this code.
How does 'if (number % 2 == 0)' work in this example?
How to divide without remainders on Python - Stack Overflow
you are looking for the modulo operator:
a % b
for example:
>>> 26 % 7
5
Of course, maybe they wanted you to implement it yourself, which wouldn't be too difficult either.
The remainder of a division can be discovered using the operator %:
>>> 26%7
5
In case you need both the quotient and the modulo, there's the builtin divmod function:
>>> seconds= 137
>>> minutes, seconds= divmod(seconds, 60)
I have been trying to make a code for divisions that outputs if your 2 numbers are divisible or if they have a remainder. I need to add an error system to make it output "ERROR" if the user inputs 0 but whenever i input zero for the 1 number the code malfunctions, this is the code: i use python in visual studio code.
def division (num_1, num_2):
num_1 = int(input("Please enter the number to divide by: "))
num_2 = int(input("Please enter the number to divide: "))
division = num_2 / num_1
remainder = num_2 % num_1
if num_2 == (0):
print("ERROR!")
elif num_1 == (0):
print("ERROR!")
elif remainder:
print(f"{num_2} is not divisable by {num_1}, there is a remainder of {remainder}.")
else:
print(f"{num_2} is divisable by {num_1}")You can do 5//2 and get 2 instead of the 2.5 you'd get with 5/2.
As long as you're in Python 3
, you can also use floor(5/2).
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.
You'd have to implement it yourself. Obvious approach would be:
def divspecial(n, d):
q, r = divmod(n, d) # Get quotient and remainder of division (both int)
if not r:
return q # If no remainder, return quotient
return n / d # Otherwise, compute float result as accurately as possible
Of course, if you're just trying to check if division would be exact or not, don't use nonsense like the function above to check:
if isinstance(divspecial(x, n), int):
Just test the remainder directly:
if x % n == 0: # If remainder is 0, division was exact
I don't think there is a way to make it automatic, but you could always do a quick check afterwards to convert it:
r = 4/2
if r%1==0:
r=int(r)