How to create float type value in Python

float type variable

Float Numbers are numbers with a fractional part.

Floating-point number literals have two forms. One is to use decimal as the follows.

1.23, 1., .1

We can also write floating-point number in scientific form by combining number and e.

3.14e-10, 4E210, 4.0e+210,

Operators with mixed type operands convert the integer operand to floating point.


print 1.0 / 2.0 #  www .j av a 2  s.co  m
print 1/2.0 
print 1.0/2 
print 1/2. 
print 3 * 3.75 / 1.5
print 7.0 / 2

The code above generates the following result.

Convert string to float type

handling exceptions when converting string to float.


try:#   www .  ja v  a  2  s  .  c o  m
    num = float(raw_input("Enter a number: "))
except:
    print "Something went wrong!"

try:
    num = float(raw_input("\nEnter a number: "))
except(ValueError):
    print "That was not a number!"

try:
    num = float(raw_input("\nEnter a number: "))
except(ValueError):
    print "That was not a number!"
else:
    print "You entered the number", num     




















Home »
  Python »
    Data Types »




Data Types
String
String Format
Tuple
List
Set
Dictionary