Reading — step 1 of 7
Learn
~2 min readGetting Started
Every value in Python has a type. Sometimes you need to change a value from one type to another — most often when reading user input (which comes in as a string) and using it as a number.
The classic beginner bug
python
input() always returns a string, even if the user typed digits. "25" + 1 makes no sense to Python — strings concatenate, ints add. Python raises a TypeError rather than guess what you meant.
The fix is explicit conversion:
python
The four conversion functions you need
python
What can be converted to what
- str → int works only if the string is a clean integer:
int("42")✓,int("3.14")✗ ValueError,int("hi")✗ ValueError. - str → float is more forgiving:
float("3.14")✓,float("42")✓ (returns42.0). - float → int truncates toward zero:
int(3.7)is3,int(-3.7)is-3(not-4!). To round properly, useround()first:int(round(3.7)). - anything → str always works:
str(True)→"True",str(None)→"None".
Truthy and falsy
Python treats some values as "falsy" — they evaluate to False in a boolean context. Everything else is "truthy."
Falsy values:
False,None,0,0.0,""(empty string),[](empty list),{}(empty dict)
Truthy: everything else.
This lets you write idiomatic Python:
python
Common conversion mistakes
- Forgetting to convert input:
n = input(); print(n + 1)→ TypeError. - Converting unparseable text:
int("3.14")→ ValueError. Usefloat()first if you might have a decimal. - Assuming
int()rounds:int(2.9)is2, not3. Useround(2.9)for proper rounding. - Comparing types directly:
"5" == 5isFalse— they're different types! Convert first.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…