int vs. float

Chris Angelico rosuav at gmail.com
Thu Feb 9 21:42:20 EST 2017


On Fri, Feb 10, 2017 at 1:33 PM,  <adam14711993 at gmail.com> wrote:
> I understand that because I am starting out by assigning my number_purchases_str to be an int, when the user enters a float that is a conflict and will crash.
>
> My professor apparently believes there is a way to accomplish this.  Any help or advice would be greatly appreciated.

What's actually happening is that you're converting a string to an
integer. You can play with this at the interactive prompt:

>>> int("1")
1
>>> int("9")
9
>>> int("-3")
-3
>>> int("1.5")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '1.5'
>>> int("hello")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'hello'

The user always enters a string. Fundamentally, people don't type
numbers - they type strings. What you're looking for is a way to let
the user type digits that you interpret as an integer.

Fortunately, "crash" in Python really means "raise an exception".
Explore exception handling and you'll find out how you can *catch*
those exceptions you understand. I won't give you the whole solution,
but you should be able to research it from there.

To distinguish between "1.5" and "hello", you could attempt to convert
the digits to a float - if that succeeds, the user entered a
fractional number of packages. Or maybe you don't care about that
difference.

Enjoy Pythonning!

ChrisA



More information about the Python-list mailing list