int() vs float() inputs in Python 3 and their utility? - python

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:
What is the utility in converting an input() to float() or int()?
I understand when I would want an integer (e.g; if I want the user to input how many times to multiply a particular number by itself), but why would I want a floating point input?
In general, when do I need to implement either, and how can I recognize which one a program needs?
Aside from user input, in what other general cases would I want to implement either command?
If anyone has any additional reading on how and when to convert certain defined variables or inputs, please send them my way!
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.

So that you can work with numbers. You can't very well multiply '3' by '2' in Python.
So that you can work with floating-point numbers. Some things in life can come in bits and pieces, like kilograms, seconds, or grade point averages.
If your program needs to work with the numbers between consecutive integers, you should probably use float.
If you use strings in your program, you may want them to be numbers, regardless of where the strings came from.
You'll need to evaluate this on a case-by-case basis.

You can implement error checking using the try function. The only reason to use an int vs a float, would be if you are trying to save memory, in the case of embedded ROM where you are severly limited.

In my opinion, you should always use float whenever you're not sure because it accepts more values so it will less likely return an error.
Unless your code expects a rounded number (you can round the number if it's a float but can cause confusion if done incorrectly) from a users input.
Bad example:
username_input = float(input("Enter your username: "))
pincode_input = int(input("Enter pincode: "))
pincode = 1234
if pincode == pincode_input:
print("Good")
else:
print("Bad")
In this case, the code expects the user to input a rounded number so I like to use int() so that if the user inputs a decimal number then I know where the problem is and can fix it directly instead of fixing every other code that relies on it.
This is a bad example because the code does run if the user's input doesn't get converted with int() but I hope you get the idea.

Related

trying to generate math questions, comparissons not working

can anyone help me? im pretty new to python and im trying to generate 10 files, each with increasingly harder questions. this code is for difficult 2. I dont want the answers in dif. 2 to be negative so whenever i get a second number bigger than the first i swap the two. for some reason some of them still come out with the first number bigger than the second. i added the "its less than" print statments for testing and it will detect the fact that its less than but wont do something about it.
Your issue is that you're casting your random numbers to a string before comparing their mathematical values. You need to compare them as integers then cast them to strings.
I believe this is because you are checking for comparison between 2 strings not 2 integers. This will give bad results for this type of program
num1 = str(r.choice(numbers))
num2 = str(r.choice(numbers))
Here you are storing strings and not integers.
and then below this you are checking if num1 <= num2.
Convert them to integers before comparing them and your code should work.

How do I take a fraction as an input in Python, and use the fraction's value for arithmetic?

Here's an example code I made to illustrate my problem. If the input is an integer or a decimal, it works as intended. But if the input is a fraction such as 4/5, it throws a ValueError since 4/5 is a string that can not be converted into a float.
myinput=input("Enter number. ")
doubleofmyinput=float(myinput)*2
print(doubleofmyinput)
This is not an issue when not using input() since float(4/5) works whereas float("4/5") doesn't, while both float("4.5") and float(4.5) are valid. Thanks.
Using the fractions library you can do the following:
import fractions
myinput = input("Enter number. ")
try:
if not myinput.isnumeric():
myinput = fractions.Fraction(myinput)
except ValueError:
throw ValueError(myinput + " is not a number")
doubleofmyinput=float(myinput)*2
print(doubleofmyinput)
How generous do you want to be in accepting input?
If it's just vulgar fractions (or mixed fractions), you can have a special case for that, either using .split('/') or regular expressions to break the input string up into its component parts, convert each separately, then put them together into a float, a Decimal or a Fraction (depending on what sort of rounding behaviour you need or can tolerate).
If you want to more generally accept arbitrary expressions, probably best to look for a library to do that; a quick google suggests simpleeval, but there are probably others.
If you only want to input the value as a fraction and NOT show it as a fraction then I would suggest using eval.
myinput=float(eval(input("Enter number. ")))
doubleofmyinput= myinput *2
print(doubleofmyinput)
if you want to convert you input value to the appropriate data type than you can use eval for this :
sigma = eval(input("Enter the value of sigma: "))
print(sigma)
Thanks :)

Division in python an types

I have a code which part of it looks like this,
A=(-1//2+(int(math.sqrt(1+8*t)))//2)
if type(A)==int:
print(t)
print(A)
The problem arises when I use "/" to get "A",
Since I am using "/", I always get an extra decimal point. For example 5/5=1.0 or 4/2=2.0 etc, which python interprets it as a float (I am using 3.6.5). Hence whatever the result is my code stuck at line2.
When I use // the same thing happens. I get 5/2=2 which its float actually but it appears as an integer.
Since my code depends on the type of this division how I can solve this problem?
A=(-1//2+(int(math.sqrt(1+8*t)))//2) its a actually the formula for finding the roots of the quadratic equation (where in the equation a=1 and b=1 and c=-2t for ax^2+bx+c) I need only the integer roots with positive values
What you're trying to do won't work. For two integers x and y, x/y is always a float, even if it happens to be integral, and x//y is always an int, even if it has to truncate (throw away) a fractional part. So testing type(A) == int doesn't test for anything except which of the two you used.
There is a method float.is_integer that you can use, and that works fine for integers divided by 2—but it doesn't work once you're using sqrt. Explaining floating-point rounding issues is a big enough job that it takes up a whole paper that's so important that it's been included by reference in multiple language specifications, but the short version is that sqrt could very easily give you a number that's a tiny big bigger or smaller than an integer, so is_integer will give you the wrong answer.
What you probably want to do is something like this:
if math.isclose(A, round(A)):
The round function will round a float to the nearest integer. The isclose function will then check whether the resulting integer is "close enough" to the original float. You should read the docs on isclose to understand exactly what it does, but in this case, I think the default values will be fine, unless you're dealing with huge integers.

Machine Learning in Python - How can I tell if an input is a number or not

I would like to know if a given input is a number or not a number. For example, if entered '1', then it is a number, 'one', 'three hundred' would also be numbers, but 'cat' would obviously not be a number. Furthermore, I would like for it to recognize that "three hundred" is actually the integer 300.
I figured that machine learning classification would be the best way to do something like this (correct me if I'm wrong), but have no idea how to get started. If someone can point to some steps to take to solve this problem, it would be appreciated.
I don't think ML is necessary nor best for what you want to achieve on your project. I say this because it can be done with a single function while ML would require huge data sets for it to actually learn something.
number words to integers then return eval
//pseudo code
function ( input )
if input is a number word
print its a number
print the number
else
print its not a number
To check and convert number words to integers, here are some suggestions

Python: Function simplifying the input instead of passing string

I need to enter a complex string for handling (UTC time code) and breaking down as part of an assignment. I have started the function like this as required:
def convertWmiDateTime(wmiDateTime):
But when I enter this:
convertWmiDateTime(20061122185433.000000+600)
The variable wmiDateTime stores 2.0061122186e+13
If I use raw_input the value 20061122185433.000000+600 will be stored correctly in wmiDateTime, but not when its called as intended above.
Is there a way to preserve what was typed into the input? A way to stop Pythong calculating and simplifying the number? vb. net would be something like (wmiDateTime As String) is there anything like that for Python?
Thanks for looking.
Your function requires a string as its input parameter. You can't call it with a number (as you're doing).
raw_input() returns a string, so the equivalent would be to call
convertWmiDateTime("20061122185433.000000+600")
Your version treats the time code as a floating point number which a) doesn't have the required precision to preserve all the digits and b) will get the timezone info (+600) added, which leads to wrong results as well.

Categories

Resources