Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
A student wrote a program that asks for the price of an item.
When the user types 49.50, the program stops with a ValueError. Explain why, and fix the program so that it accepts 49.50 and shows 99.0.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. Read the last line of the error message. It says that the text 49.50 is not a valid whole number. The function int() reads only whole numbers. A decimal point makes it fail.
Fix. Use float() for a number that may have a decimal point.
With 49.50 typed, price is 49.5, and price * 2 is 99.0.
Check. 49.5 * 2 = 99. Python shows 99.0, because the answer is a float.
Answer: int() cannot read a decimal point. Use float(input(...)).
Common mistake. Changing the user's answer to a whole number by int() first. int(float("49.50")) would cut off the .50, and the price would be wrong.
Log in to join the discussion.
Loading…