Step 1 of 7 · Reading · ~3 min
Learn
Getting Started
Type Conversion
Everything that arrives on input arrives as text, and text does not add up. In this lesson you learn how to turn text into a number, a number back into text, and how each of those conversions quietly changes the value you end up with.
input() hands you text, always
A line that looks like a number is still a string. + between two strings glues them; +
between a string and an int is an error, because Python refuses to guess which one you meant.
Three functions do almost all of the work
int() applied to a string accepts only a clean whole number. int("2.5") does not chop the
decimal off for you — it raises ValueError: invalid literal for int() with base 10: '2.5', and
so does int("hi"). When the text may contain a dot, float() is the tool that reads it; you can
narrow it afterwards with int(float("2.5")), which is 2.
int() chops toward zero — it does not round
Three different answers from the same number. int() throws the fraction away and keeps the sign,
round() goes to the nearest whole number, and // (from the numbers lesson) always goes down.
On positive values the first two often agree, which is why the difference only bites you the first
time a negative value shows up.
A conversion can change the spelling
Text to number and back is not a round trip. The number 42 has no memory of the two zeros that
were typed in front of it, and a trailing zero after a decimal point is gone for good. Printing the
text you read is therefore not the same as printing the value you converted.
bool() and the falsy values
bool() answers "is there anything here?". These values are falsy — they convert to False:
False, None, 0, 0.0, "" (the empty string), [] (an empty list). Everything else is
truthy.
Common mistakes
- No conversion at all. For the lines
4and9, gluing the two strings with+prints49; adding the two numbers prints13. Nothing crashes, so this one is easy to miss. round()where a chop was asked for.9.99becomes10instead of9, and only a fractional part of.5or more gives it away.//on a negative value. Floor division sends-9.99to-10, one lower thanint()gives you.- Printing the text instead of the value.
"0042"printed as text is still0042; converted and printed it is42.
Your exercise
Read the two lines the starter already reads, convert them to numbers, and print the sum three ways: as a decimal, chopped to a whole number, and inside a short report line. The mistake to watch for is the silent one — two strings added together do not complain, they just stick.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…