Quick Overview
`int("12")` parses, but `int("12.5")` raises `ValueError` rather than truncating. `int(12.5)` does truncate, toward zero, which is why the two look inconsistent.
Write two functions: string_to_int(txt) that converts a numerical string into an integer, and int_to_string(num) that converts an integer into a string.
User inputs (from forms or command line arguments) enter Python as strings. Converting them to numbers is required before doing math operations.
Use built-in int() and str() type casting functions:
def string_to_int(txt):
return int(txt)
def int_to_string(num):
return str(num)
# Testing string to int
print(string_to_int("6"), type(string_to_int("6"))) # Output: 6 <class 'int'>
print(string_to_int("1000")) # Output: 1000
# Testing int to string
print(int_to_string(45), type(int_to_string(45))) # Output: '45' <class 'str'>
Python is strongly typed, meaning it will NOT implicitly convert "5" + 5 (this raises a TypeError). Explicit type casting via int() and str() is required.
int("hello") raises a ValueError: invalid literal for int() with base 10. Use try/except blocks when parsing unpredictable user input.Use int() and str() for explicit type casting. Next, let's count words in a sentence!
A function with no `return` hands back `None`, so a forgotten one surfaces as a `TypeError` at the call site rather than at the line that actually caused it.
`minutes * 60` returns an `int` when given an `int`, while `/` always produces a float regardless of the operands. Multiplication preserves the type; division does not.
`base * height / 2` always yields a float in Python 3 because `/` never returns an int, even for whole numbers. `//` floors instead, which is almost never what an area wants.