The float () function in Python

The float () function in Python converts the value specified to a floating-point number. How does the float () function have a syntax, what parameters do you have, how can you find out in this article with Quantrimang?

The float () function in Python converts the value specified to a floating-point number. How does the float () function have a syntax, what parameters do you have, how can you find out in this article with Quantrimang?

The float () function in Python Picture 1The float () function in Python Picture 1

The float () function syntax in Python

 float([x]) 

Parameters of float () function:

float () has only one parameter:

  1. x : number or string to be converted into a floating-point number

The function accepts value types that can be parameterized as follows:

  1. Number: May be an integer or a decimal.
  2. Chain:
    1. Contains any type of number.
    2. The left or right whitespace or a new line of values ​​are ignored by the program.
    3. Can use mathematical operators.
    4. Can be used with NaN, Infinity or inf (both lower and upper case).

Value returned from float ()

The values ​​returned by the float () function depend on the parameter passed.

  1. If the parameters are passed in accordance with Python requirements, the result returned is a corresponding floating point number.
  2. If no parameters are passed, the function returns 0.0.
  3. If the passed parameter is not a decimal number or does not match any of the cases mentioned above, the program will report an error.
  4. If a number is passed outside of the Python float, the output will occur exception OverflowError .

Example 1: How does the float () function work?

 # viết bởi TipsMake.com 
# đối với số nguyên
print(float(10))

# đối với số thập phân
print(float(11.22))

# đối với chuỗi
print(float("-13.33"))

# đối với chuỗi có khoảng trắng
print(float(" -24.45n"))

# chuỗi gây ra lỗi
print(float("abc"))

Run the program, the result is:

 10.0 
11.22
-13.33
-24.45
ValueError: could not convert string to float: 'abc'

Example 2: float () with infinity and Nan (Not a number)?

 # viết bởi TipsMake.com 
# đối với NaN
print(float("nan"))
print(float("NaN"))

# đối với inf/infinity
print(float("inf"))
print(float("InF"))
print(float("InFiNiTy"))
print(float("infinity"))

Run the program, the result is:

 nan 
nan
inf
inf
inf
inf

The float () function has only a few notes like that. Remember to practice regularly with Python exercises.

Previous lesson: eval () function in Python

Next lesson: exec () function in Python

4 ★ | 2 Vote