nebulator0
nebulator0

Reputation: 85

Python simple float division: not accurate

So I'm very new to programming but i was working on just a simple calculator. As I launched the program and tried out the division part (tried to divide 5 by 2), the output was 3.0 . The 2 numbers are floats, so I don't really understand why this doesn't work. Second, multiplication gives wrong answer aswell.

from math import *

while True:

print("Options:")
print("Enter 'add' to add two numbers")
print("Enter 'subtract' or '-' to subtract two numbers")
print("Enter 'multiply' to multiply two numbers")
print("Enter 'divide' to divide two numbers")
print("Enter 'quit' to end the program")
user_input = input(": ")

if user_input == "quit":
    print ("Calculator stopped.")
    break
elif user_input == "subtract" or "-":
    num1 = float(input("num1: "))
    num2 = float(input("num1: "))
    print(num1 - num2)
elif user_input == "multiply" or "*":
    num1 = float(input("num1: "))
    num2 = float(input("num1: "))
    print(">> ", num1 * num2," <<")
elif user_input == "divide" or "/":
    num1 = float(input("num1: "))
    num2 = float(input("num1: "))
    sum = num1 / num2
    print(str(float(num1)/num2))
else:
    print("Unknown command")

BTW I use Python 3.6.1 .

Upvotes: 2

Views: 142

Answers (1)

John1024
John1024

Reputation: 113814

This doesn't do what you think:

elif user_input == "subtract" or "-":

It works as if it was grouped as follows:

elif (user_input == "subtract") or "-":

Regardless of the value of user_input, this condition will evaluate to True (because "-" is nonempty and therefore True) and subtraction will be performed.

(tried to divide 5 by 2), the output was 3.0

That is because 5 minus 2 is 3. The code is subtracting.

You want something more like:

from math import *

while True:

    print("Options:")
    print("Enter 'subtract' or '-' to subtract two numbers")
    print("Enter 'multiply' to multiply two numbers")
    print("Enter 'divide' to divide two numbers")
    print("Enter 'quit' to end the program")
    user_input = input(": ")

    if user_input == "quit":
        print ("Calculator stopped.")
        break
    elif user_input in ( "subtract", "-"):
        num1 = float(input("num1: "))
        num2 = float(input("num1: "))
        print(num1 - num2)
    elif user_input in ("multiply", "*"):
        num1 = float(input("num1: "))
        num2 = float(input("num1: "))
        print(">> ", num1 * num2," <<")
    elif user_input in ("divide", "/"):
        num1 = float(input("num1: "))
        num2 = float(input("num1: "))
        print(num1/num2)
    else:
        print("Unknown command")

Upvotes: 7

Related Questions