How can I fix a bug using modulo (%) in Python?

Question:

I am making a converting program in Python, and in this case it’s from feet to yards. I have having trouble with a specific line of code that is not showing an error message, yet refuses to actually work.

When I run the program and put the following numbers in the input (3, 2, 4, 1) the Yards should be 8, and the feet should be 0, but it stays on 7 yards, and doesn’t add the 3 extra feet into the yard amount.

firstYard = int(input("Enter the Yards: "))
firstFeet = int(input("Enter the Feet: "))
secondYard = int(input("Enter the Yards: "))
secondFeet = int(input("Enter the Feet: "))

print("Yards: ")
print(int(firstYard + secondYard))
print(" Feet: ")
print(int(firstFeet + secondFeet) % 3)

if ((firstFeet + secondFeet) % 3) > 2:
**    firstYard += 1
**
 

The last line is what I’m having trouble with.

Asked By: Boss

||

Answers:

This line is causing your problem:

if ((firstFeet + secondFeet) % 3) > 2:

The remainder of division by three cannot be greater than 2, maybe you mean to see if three fits more than twice? Try division instead of modulo if that’s the case.

Answered By: Zack Walton

Your test

if ((firstFeet + secondFeet) % 3) > 2:

will always be false, because you’re taking the modulo of that sum and any number module 3 cannot be greater than 2.

What you need to add to your yard total is the integer division of the feet total:

firstYard += (firstFeet + secondFeet) // 3

I would structure your code differently:

totalYard = firstYard + secondYard + (firstFeet + secondFeet) // 3
totalFeet = (firstFeel + secondFeet) % 3
Answered By: someone
Yards = int(input("Enter the Yards: "))
Feet = int(input("Enter the Feet: "))
Yards_2 = int(input("Enter the Yards: "))
Feet_2 = int(input("Enter the Feet: "))





print("nYards:",(Yards * 3 + Yards_2 * 3 + Feet + Feet_2) // 3, "Feet:",(Yards * 3 + Yards_2 * 3  + Feet + Feet_2) % 3)

You have to scroll to the right more.
The feet should not exceed 2 because 3 feet would be a yard.

Answered By: Mouse
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.