Python Numeric Conversions: int() and float()
Choose the conversion by the input contract
In the first chapter you used int() to convert whole-number text. Use float() when the text can contain a fractional part. Neither function changes the original text; each returns a numeric value you can assign to a name.
quantity_text = " -4 "length_text = "2.5"print(int(quantity_text) + 10)print(float(length_text) * 4)Surrounding spaces and a leading minus sign are accepted in ordinary integer text. float("2.5") represents two and a half. In these examples, the text uses a period for the decimal point.
Converting an existing float
int() truncates a finite float toward zero; it does not round to the nearest integer or always round down. float(7) produces 7.0. Large integers may lose precision when converted to float.
Integer text is not decimal text
This code intentionally raises ValueError. If the input contract allows decimal text, use float() first. Only convert that result to an integer if discarding the fraction is actually required. The same kind of error occurs for float("tea"). Do not guess how invalid data should be handled; exception handling is taught later.
Practice
Pretend a user entered " 3.75 " as a length. Choose a conversion, multiply the length by two, and predict the result. The sample text stands in for input() so the code does not need interactive input.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Numeric conversion
Check your understanding of numeric conversions.
Which conversion accepts ordinary text "3.25" while retaining its fractional part?
What is printed?
print(int(-7.9))What is printed?
print(float("3") * 2)What happens when this code runs?
print(int("4.5"))After value = float(text), what happens to the original name text?