This doesn't refer to a specific code of mine, so I hope this does not defy community standards for asking questions. I'm still learning, so please let me know if this kind of question is inappropriate for future reference!
I am trying to gain a thorough understanding of the utility of certain commands as I embark on learning to use Python 3. I have never coded before, so I do not have background in any other language. I was hoping someone could help me understand this more thoroughly.
Basically, I understand that when prompting for a user input with a numeric value, it is sometimes correct to write float(input())
, and sometimes correct to write int(input())
. I know in mathematics that an integer is a whole number, and a floating point number is any number defined with a whole portion, a radix, and a mantissa (like 4.32). I don't understand the utility of converting a user input to one or the other.
For example, if I write int(input("Input a decimal. "))
and the user inputs 4.3, the program will return a value error. What is the utility in this? So:
input()
to float()
or int()
?EDIT:
Here is an example of a code that I wrote that I think highlights my confusion about if and when to use int()
and float()
:
price=input("How much did the item cost?: $")
if float(price)<0:
print("The price cannot be negative.")
else:
price=int(float(price)*100)
paid=input("How much did the customer pay?: $")
paid=int(float(paid)*100)
Did I do this correctly? The larger program of which this is a part works fine, but I'm not sure if I added unnecessary command or implemented the commands correctly.
Thank you so much for your help!
Naomi
It has nothing about utility, it has to do with what are the possible range of values you're program should/needs to accept.
If it needs to accept both integers and floats as inputs, then you should convert to float
since floats can represent the integers.
But if you're program requires that the input be specifically an integer, then you should be casting to int
.
EDIT:
In your example, you should always be using float
, since money has a decimal value.
If you were asking "How many bananas did you buy?" You'd want to convert to int
since those values are going to be 0, 1, 2, 3, 4, ...
. And then when you ask "How much did you pay for these bananas?" You'd want to convert to float
since those inputs can range from 3.15, .77, 1, 1.00, ...
etc.