- Related Questions & Answers
- 10 Interesting Python Cool Tricks
- howdoi in Python
- How to print without newline in Python?
- How to download Google Images using Python
- How to clear screen in python?
- get() method for dictionaries in Python
- Generating random number list in Python
- gcd() function Python
- frozenset() in Python
- floor() and ceil() function Python
- Finding Mean, Median, Mode in Python without Libraries
- Find the k most frequent words from data set in Python
- Find size of a list in Python
- Find length of a string in python (3 ways)
- Find all the numbers in a string using regular expression in Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

Float method is part of python standard library which converts a number or a string containing numbers to a float data type. There are following rules when a string is considered to be valid for converting it to a float.

The string must have only numbers in it.

Mathematical operators between the numbers can also be used.

The string can represent NaN or inf

The white spaces at the beginning and end are always ignored.

The below program indicates how different values are returned when float function is applied.

n = 89 print(type(n)) f = float(n) print(type(f)) print("input",7," with float function becomes ",float(7)) print("input",-21.6," with float function becomes ",float(-21.6)) print("input NaN, with float function becomes ",float("NaN")) print("input InF, with float function becomes ",float("InF"))

Running the above code gives us the following result −

<class 'int'> <class 'float'> input 7 with float function becomes 7.0 input -21.6 with float function becomes -21.6 input NaN, with float function becomes nan input InF, with float function becomes inf

Passing a stream without having any numeric values throws error.

print("input Tutorials, with float function becomes ",float("Tutorials"))

Running the above code gives us the following result −

Traceback (most recent call last): File "C:/xxx.py", line 18, in print("input Tutorials, with float function becomes ",float("Tutorials")) ValueError: could not convert string to float: 'Tutorials'

Advertisements