Python Forum
Division calcuation with answers to 1decimal place. - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Division calcuation with answers to 1decimal place. (/thread-34283.html)



Division calcuation with answers to 1decimal place. - sik - Jul-14-2021

I'm trying to write a program that takes two random integers from 0-10 and divides them by each other and have the user enter the answer to one decimal place.

I keep on getting incorrect even though I think I'm trying in the correct answer.

The code is below. Please help.

import random

first = random.randint(0,10)
second = random.randint(0,10)

symbol = " / "
print(first, symbol, second, "=")

answer = first / second
answer = ("{:.1f}".format(answer)) # division answer to 1 decimal place

print(answer) # The print is for testing purposes.

user_answer = float(input("enter you answer to one decimal place"))
  # mark answer
if user_answer == answer:
    # correct
    print("Correct!")
else:
    # incorrect
    print("Incorrect!")



RE: Division calcuation with answers to 1decimal place. - deanhystad - Jul-14-2021

You are comparing a str (answer) and a float (user_answer). They will never be equal. Leave the user input as a str and compare the strings.


RE: Division calcuation with answers to 1decimal place. - sik - Jul-14-2021

(Jul-14-2021, 03:57 PM)deanhystad Wrote: You are comparing a str (answer) and a float (user_answer). They will never be equal. Leave the user input as a str and compare the strings.

Thank you so much!


RE: Division calcuation with answers to 1decimal place. - DeaD_EyE - Jul-15-2021

some_value = 1.337
guessed_value = 1.3

# round(value, decimal_places)

if round(some_value, 1) == round(guessed_value, 1):
    print("Rounded values are equal")
If you made a calculation and want to compare if the two values are equal, you should use math.isclose.

import math


value_a = 1337 * 1.3 / 42
value_b = 1337 / 42 * 1.3

print("Value_a:", value_a)
print("Value_b:", value_b)

if value_a != value_b:
    print("The values are not equal")
    
if math.isclose(value_a, value_b):
    print("But the values are close enough")
Quote:Value_a: 41.38333333333334
Value_b: 41.38333333333333
The values are not equal
But the values are close enough

Just changing the order of calculation, will result in a different value.