int vs. float

Amit Yaron amit at phpandmore.net
Fri Feb 10 06:59:45 EST 2017


On 10/02/17 04:33, adam14711993 at gmail.com wrote:
> Hello,
>
> My computer programming professor challenged me to figure out a way to manipulate my program to display one error message if the user input is a zero or a negative number, and a separate error message if the user input is a decimal number.  My program starts out:
>
> number_purchases_str = int(input("Enter the number of packages you're buying:"))
> number_purchases = int(number_purchases_str)
> format(number_purchases, "12,")
>
> So if the user input is, for example, -9 or 0, the program will result with: Sorry, you must order at least one package."
>
> What I cannot figure out is how to write it so that if my user input is, for example, 1.5, the program will result with: Sorry, you can only order whole packages.
>
> 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.
>
> Thank you.
>
The function int(str) raises the exception ValueError if the input 
string does not represent an integer.

Use:

try:
   num=int(str)
except ValueError e:
   print "Error: not an integer"






More information about the Python-list mailing list