Remember
float() converts a supported number or numeric string into a floating-point number.
float() converts a supported number or numeric string into a floating-point number.
Follow the example, change its sample, and compare what happens.
Explain the result and test your understanding.
Focus on how the names, objects, and calculations change. We’ll inspect the printed output in the next section.
Follow the code and watch its state change. Guided simulation.
text = '3.5'
number = float(text)
print(number)Top-level scope
'3.5'Object 2 · float3.5float() converts a supported number or numeric string into a floating-point number.
(no output)
What do you expect this program to print?
EXAMPLE INSTRUCTIONS
text = '3.5'
number = float(text)
print(number)
|
v
DISPLAYED RESULT
3.5
FINAL BINDINGS
text --> object 1 (str)
number --> object 2 (float)
object 1: '3.5'
object 2: 3.5Choose a different sample input, then follow every step through to the output. Before revealing it, predict what the program will display.
Choose a sample and follow its execution. Guided simulation.
text = '3.5'
number = float(text)
print(number)Top-level scope
'3.5'Object 2 · float3.5The example has finished. Compare the final output with the values and references above.
3.5
What do you expect this program to print?
text = '3.5'
number = float(text)
print(number)float() FunctionThe float() function in Python is used to convert a number or a string into a floating-point number (i.e., a decimal number).
This is helpful when you need precision or decimal values in your calculations.
float([value])
value (optional) – A number or a string that looks like a number.x = float(5)
print(x)
5.0
price = float("19.99")
print(price)
19.99
x = float()
print(x)
0.0
If no value is given, float() returns 0.0.
num = float("1e3")
print(num)
1000.0
float("hello") # ❌ Raises ValueError
0.1 + 0.2 may not be exactly 0.3.In coding interviews, float() is often used for type conversion before performing arithmetic or formatting results.
float() converts int, str, or no argument to a decimal numberValueError for invalid strings0.0 if called with no argumentsAsk the user for a price and discount percentage, then calculate and print the final price.
price = float(input("Enter the price: "))
discount = float(input("Enter the discount %: "))
final_price = price - (price * discount / 100)
print("Final price after discount:", final_price)
Connect what you noticed in the example with the idea below.
float() converts a supported number or numeric string into a floating-point number.
float() accepts every arbitrary word as a numeric value.
This is the misconception to avoid.Reference checks are optional and do not count toward course progress.