- Python Float()
- Python float() with Examples
- float() Syntax
- Parameters
- Return Values
- 1- float() function with +ve number values
- 2- float() function with -ve numbers
- 3- float() function with a string containing numbers
- float() function with invalid inputs
- Python Return Float From Function
- Method 1: Using the float() Function
- Related Tutorials
- Programmer Humor
Python Float()
This tutorial explains Python float() method that takes a number or string and returns a floating-point value. If it is not able to convert string to float, then it raises the ValueError. Let’s try to understand how to use it with the help of simple examples.
Let’s now go through each of the section one by one.
Python float() with Examples
Float() is a built-in Python function that converts a number or a string to a float value and returns the result. If it fails for any invalid input, then an appropriate exception occurs.
float() Syntax
The basic syntax to use Python float() is as follows:
Parameters
First, the parameter is optional. If you don’t pass a value, then it returns 0.0. Also, the valid argument can only be a number or a string containing some numeric value.
Also, if you supply a string with a number with leading or trailing spaces, then it ignores the spaces and returns a float value.
Return Values
The float() function returns a floating-point value equivalent to the number passed as is or in the form of a string.
It raises the following exceptions when it receives invalid input data.
ValueError – When you pass a wrong argument such as a string that doesn’t contain a number
TypeError – When you pass a type argument that it doesn’t allow such as a complex number or NoneType
Here, we are using float() to address different use cases. Hope, these should help you this function from all corners.
1- float() function with +ve number values
In this example, we’ll pass +ve values in the float() call. So, it will simply convert them to an equivalent floating-point number.
2- float() function with -ve numbers
This time, we’ll execute float() on a group of -ve values. We’ve stored all test numbers in a list to run our tests.
""" Desc: Python example to demonstrate float() function on -ve numbers """ # Test Input testInput = [-1, -10000, -0.0, -1.1001, -1.000000000000001, -1.0000000000000001, -1.0000] for eachItem in testInput: print("float(<>) = <>".format(eachItem, float(eachItem)))
This code would give you the following result:
float(-1) = -1.0 float(-10000) = -10000.0 float(-0.0) = -0.0 float(-1.1001) = -1.1001 float(-1.000000000000001) = -1.000000000000001 float(-1.0) = -1.0 float(-1.0) = -1.0
3- float() function with a string containing numbers
When you pass a number in string format (in quotes), then float() converts the value to float type and returns the result.
For testing this, we’ve taken a list of strings containing both +ve and -ve numbers.
""" Desc: Python example to demonstrate float() function on strings """ # Test Input testInput = ["-1", "-10000", "0.0", "1.1001", "1.000000000000001", "-1.0000000000000001", " 1.0000 "] for eachItem in testInput: print("float(<>) = <>".format(eachItem, float(eachItem)))
After running this code, you would get the following output:
float('-1') = -1.0 float('-10000') = -10000.0 float('0.0') = 0.0 float('1.1001') = 1.1001 float('1.000000000000001') = 1.000000000000001 float('-1.0000000000000001') = -1.0 float(' 1.0000 ') = 1.0
You can now go through the result and understand our test input list included multiple values. And the float() function successfully returned the correct float values for each of them. Also, it ignored the leading and trailing spaces as given in the last element of the list.
Python float() function also accepts words like NaN, Infinity, inf (in lower and upper cases). Let’s check this fact with an example.
""" Desc: Python float() exmaple for NaN, Infinity, inf """ # Test Input testInput = ["nan", "NaN", "inf", "InF", "InFiNiTy", "infinity"] # Let's test float() for eachItem in testInput: if isinstance(eachItem, str): print("float('<>') = <>".format(eachItem, float(eachItem))) else: print("float(<>) = <>".format(eachItem, float(eachItem)))
After running the given code, the output is:
float('nan') = nan float('NaN') = nan float('inf') = inf float('InF') = inf float('InFiNiTy') = inf float('infinity') = inf
float() function with invalid inputs
Finally, we’ll test the float() function by passing some invalid input values. And hopefully, we’ll try to cover all the errors or exception it can throw.
Let’s see how does float() operate with the wrong parameters.
""" Desc: Python float() exmaple for invalid input values """ # Test Input with all possible invalid values testInput = [None, "Python", "0,1", "0 1", 1+2j] # We'll use exception handling to continue even if some error occurs for eachItem in testInput: try: if isinstance(eachItem, str): print("float('<>') = <>".format(eachItem, float(eachItem))) else: print("float(<>) = <>".format(eachItem, float(eachItem))) except Exception as ex: print("float(<>) = <>".format(eachItem, ex)) # Also, check for 1/0 try: print("float(1/0) = <>".format(float(1/0))) except Exception as ex: print("float(1/0) = <>".format(ex))
Since this program raises exceptions for every invalid input, hence we used Python try-except block to catch and print errors. After running the given snippet, you see the following output:
float(None) = float() argument must be a string or a number, not 'NoneType' float(Python) = could not convert string to float: 'Python' float(0,1) = could not convert string to float: '0,1' float(0 1) = could not convert string to float: '0 1' float((1+2j)) = can't convert complex to float float(1/0) = division by zero
We hope that after wrapping up this tutorial, you should feel comfortable in using the Python float() method. However, you may practice more with examples to gain confidence.
Also, to learn Python from scratch to depth, do read our step by step Python tutorial .
Python Return Float From Function
A Python function can return any object such as a float value such as 3.14 . To return a float, you can use the built-in float() function or create your own function with an arbitrary simple or complex expression within the function body and put the result of this after the return keyword (e.g., return 10/3 ).
Method 1: Using the float() Function
Python’s float() function takes an argument such as a string or an integer and attempts to convert it to a float. You don’t need to import a library as it is built-in. For example, float(‘3.14’) converts the string to a float 3.14 and float(3) converts the integer to the float 3.0 .
Here’s a code snippet exemplifying this approach:
# String to Float x = '3.14' print(float(x)) # 3.14 # Int to Float x = 3 print(float(x)) # 3.0
⭐⭐⭐ This is the most straightforward approach to returning a float from a function.
You can also watch my explainer video and visit the recommended blog tutorial on the topic:
If you want to learn more about this code snippet to calculate the value of Pi, feel free to check out our Finxter tutorial on the topic.
Related Tutorials
Programmer Humor
Q: How do you tell an introverted computer scientist from an extroverted computer scientist? A: An extroverted computer scientist looks at your shoes when he talks to you.
While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.
Be on the Right Side of Change 🚀
- The world is changing exponentially. Disruptive technologies such as AI, crypto, and automation eliminate entire industries. 🤖
- Do you feel uncertain and afraid of being replaced by machines, leaving you without money, purpose, or value? Fear not! There a way to not merely survive but thrive in this new world!
- Finxter is here to help you stay ahead of the curve, so you can keep winning as paradigms shift.
Learning Resources 🧑💻
⭐ Boost your skills. Join our free email academy with daily emails teaching exponential with 1000+ tutorials on AI, data science, Python, freelancing, and Blockchain development!
Join the Finxter Academy and unlock access to premium courses 👑 to certify your skills in exponential technologies and programming.
New Finxter Tutorials:
Finxter Categories: