Lecture: Input, Output & Strings
Lecture script · about 15–20 minutes spoken · Week 3
Opening
Picture a café kiosk. You tap in your name, Mariana, and order 2 lattes. A slip prints that says "Order for Mariana: 2 lattes," and the cup label only has room for 3 letters, so it says MAR. In those few seconds a program asked you for text, kept it, built a sentence around it, and cut off a piece of it.
That pattern shows up in a lot of work. A nursing student types a temperature reading into a chart form. A business major builds a receipt line from a customer's order. Each of those programs has to treat typed text as text, convert it on purpose, and take it apart by position. When one of those steps slips, a program can print 2525 where you wanted 50, without a single warning.
In Week 1 you learned to predict what a line prints, run it, and read an error from its last line. In Week 2 you gave values names, sorted them by type, and met int and str as conversion tools, along with the TypeError you get when you add a string to a number. This week those conversions become an everyday tool, because everything a person types reaches your program as a string.
Here's the plan for this lecture. We'll ask the person at the keyboard for a value, build output with f-strings, pick single characters out of a string, cut pieces out with slices, and count characters with len. Then we'll put it all together and check a chatbot's claim with a run. Next, in Week 4, Booleans & Conditionals, your programs start choosing which line runs.
1. Ask the keyboard: typed input is always a string
Think about a librarian at a help desk who asks what book you're looking for and writes your answer on a slip. Whatever you say, the slip holds words in ink. If you say a number out loud, the slip still holds marks on paper, not an amount you can add. A program that asks a question works the same way.
Python's tool for asking is input(), the built-in function that shows a prompt, waits for the user to type a line and press Enter, and hands back exactly what was typed as a string. The prompt is the message input() displays to tell the user what to type, such as Book title, followed by a colon and a space.
Let's ask the reading log for its book. The program says book gets input with the prompt Book title. The user types the river book and presses Enter. Now book holds the text "the river book." If you ask Python for its type, you get class str, a string. To pin a run that doesn't depend on anyone's typing, this course writes the typed value as a literal: book gets the string "the river book."
Here's where people get caught. Suppose the user types 25. The pinned run stores that as typed gets the string "25," in quotation marks. Ask for its type, and you get class str again. Digits in quotation marks are text. Now multiply that by 2. You might expect 50. Python prints 2525, two copies of the text side by side, exactly as Week 2's string-times-a-number lines did.
The fix is a conversion. Age gets int of typed, and int turns the text "25" into the whole number 25. Then age plus 1 works out 25 plus 1, which is 26, and Python prints 26. If you skip the conversion and add 1 to the string directly, nothing prints, and the last line of the error message names TypeError.
Pause and try this. The reading log holds 45 pages read. The user types 30 for the pages read since the last entry. Why must the program use int before adding, and what does the sum print?
Think about what type that 30 is when it arrives.
Here's the answer. The 30 arrives as the string "30," and a string can't be added to the number 45. After int turns it into 30, the program works out 45 plus 30, which is 75, and prints 75.
So typed text stays text until you convert it, and that's the habit to carry: wrap int around typed digits before you count with them.
2. Build output with f-strings, not glue
Go back to that order slip. Nobody typed "Order for Mariana: 2 lattes" by hand. Somebody wrote a template with blanks, and the register fills them in for every customer. Python has the same idea built in.
An f-string is a string with the letter f right before its opening quote, in which every pair of curly braces holds a name or an expression whose value Python fills in. So you write the letter f, then a quotation mark, then your sentence, with a name inside curly braces wherever a value belongs.
The reading log uses two of them. The first f-string says Now reading, a colon, and then book in curly braces. Python fills in the title, and the output reads Now reading: the river book. The second f-string starts with pages_read in curly braces, followed by the words pages read so far. The output reads 45 pages read so far. Notice that you never converted 45 to a string. The f-string handled the number for you.
The braces can hold a whole expression, not only a name. With age holding 25, an f-string that says Next year you will be, with age plus 1 in the braces, prints Next year you will be 26. Python did the arithmetic inside the braces first.
Before f-strings, people glued pieces together. Concatenation is joining two strings end to end with the + operator, which works only when both sides are strings. You'll see it once, because it's what f-strings replace. Gluing the text Now reading to book with a plus sign prints the same line as the f-string. But glue the number pages_read onto the text pages read so far, and Python stops. The last line of the error message names TypeError, because one side is a number and the other is text.
Pause and try this. A classmate's line prints the words in braces, pages_read in curly braces, instead of the number 45. What one character did they leave out?
Picture the start of their string.
Here's the answer. They left out the f before the opening quote. Without the f, the braces are ordinary characters, so Python prints them as they are.
The f fills the blanks. No f, no filling.
3. Pick one character by its index
Picture a row of gym lockers, each with a number painted on its door. You open a locker by its number. Now imagine the very first locker is painted 0, not 1. That's how Python numbers the characters in a string.
A character is one letter, digit, space, or punctuation mark; a string is a row of characters kept in order. An index is a whole number in square brackets after a string that picks out the one character at that position, counting from 0 at the left. Python uses zero-based indexing, which means numbering the positions in a string starting from 0, so the first character sits at index 0 and the last sits at the length minus 1.
Let's read the reading log's title, the river book, position by position. Index 0 is t. Index 1 is h. Index 2 is e. Index 3 is the space, because a space is a character too. Index 4 is r, the start of the word river. So book at index 0 prints t, and book at index 4 prints r.
Counting from the end is often handier. A negative index is an index below zero that counts back from the end of a string, so an index of minus 1 picks the last character and minus 2 the one before it. Book at minus 1 prints k, the last letter of the title. And the word cat at minus 1 prints t. You never need to know how long a string is to reach its last character this way.
Pause and try this. The word cat has 3 letters. A classmate asks for cat at index 3 to get its last letter. What goes wrong?
Count the positions starting from 0.
Here's the answer. The positions of cat are 0, 1, and 2, so index 3 is past the end. Python stops, and the last line of the error message names IndexError. The last letter is at minus 1.
Count from 0 on the left and from minus 1 on the right.
4. Cut a piece with a slice
Think of a baker cutting a loaf between the 4th mark and the 9th mark. The bread between those marks goes in the bag. The 9th mark is where the knife stops; it isn't a piece of bread you take home.
A slice is a piece cut from a string with square brackets and a colon, which keeps the characters from index start up to, but not including, index stop. That makes it half-open: it includes its start position and leaves out its stop position.
Here's the reading log's slice. Book from 4 to 9 prints river. It starts at index 4, which is r, and stops before index 9, which is the space after river. So it keeps the characters at indexes 4, 5, 6, 7, and 8. That's 9 minus 4, which is 5 characters. Stop minus start always tells you how many characters a slice keeps.
The pinned predict-the-output line does the same with capital letters. The word PYTHON sliced from 1 to 4 prints YTH. Index 4, the O, is the stop, so it's left out. The word hello sliced from 1 to 4 prints ell.
You can leave a number out. With no start, the slice begins at the front, so book up to 3 prints the. With no stop, it runs to the end, so book from 10 onward prints book. And a third number is a step, the optional third number in a slice, which says how many positions to move each time; a step of minus 1 walks backward through the string. PYTHON with a step of 2 prints PTO, every second letter. Hello with a step of minus 1 prints olleh, the word backward.
Pause and try this. Someone predicts that PYTHON sliced from 1 to 4 prints YTHO, four letters. Using stop minus start, how many characters should the slice keep?
Do the subtraction before you decide.
Here's the answer. Three characters, because 4 minus 1 is 3. The slice keeps Y, T, and H and drops the O at the stop, so it prints YTH.
A slice keeps the start and drops the stop.
5. Count characters: the strict index and the forgiving slice
Picture a cinema row of 14 seats numbered 0 to 13. Hand the usher a ticket for seat 14, and you're stopped, because that seat doesn't exist. Ask for seats 4 through 99, and you're shown seats 4 to 13, the ones that exist. Strings treat a single index and a slice in that same way.
len() is the built-in function that counts the characters in a string, with spaces and punctuation counted too. Len of book prints 14: 3 letters in the, 5 in river, 4 in book, and 2 spaces. Because counting starts at 0, the last index is 14 minus 1, which is 13, and book at index 13 prints k.
Now step one position too far. Book at index 14 prints nothing. The last line of the error message names IndexError. An IndexError is the error type Python reports when an index points to a position where no character sits, such as index 14 in a string of 14 characters. The program started, and that line stopped it.
But ask for a slice that runs far past the end, book from 4 to 99, and there's no error at all. Python prints river book. A slice takes whatever characters exist in its range and stops quietly at the end of the string.
Pause and try this. Len of book is 14. Which index holds the last character, and what does book from 4 to 99 print?
Remember where counting starts.
Here's the answer. The last character is at index 13, because 14 minus 1 is 13, and it's k. Book from 4 to 99 prints river book, because a slice stops quietly at the end instead of raising an error.
An index must hit a character. A slice takes what's there.
6. Put it together and check a chatbot's claim
A ticket machine asks two questions and prints a slip that uses both answers. Most small programs in this course have that shape: ask, convert, build, print.
Here's the reading log doing all four. It asks for the book title, and the user types the river book. It asks for pages read, and the user types 30. It converts the 30 with int and works out 45 plus 30, which is 75. Then three f-strings print Now reading: the river book, then Short title: river, using the slice from 4 to 9, and then 75 pages read so far. The program asked twice, converted once, and built three lines of output.
The same shape works anywhere. A temperature converter asks for Celsius, and the user types 20. It converts the 20 with int, works out 20 times 9, which is 180, then 180 divided by 5, which is 36.0, then adds 32 to reach 68.0. The decimal point comes from division, which always gives a float, as Week 2 showed.
Now the chatbot. Suppose you ask one what PYTHON sliced from 1 to 4 prints, and it answers YTHO, explaining that the slice runs from index 1 to index 4. That sounds reasonable. But a chatbot predicts likely text; it doesn't run your program. So you type the line into your browser runner and run it, and the output is YTH. The chatbot included the stop, the classic slice slip, and you caught it with a run.
Pause and try this. A chatbot says the typed value 25 times 2 prints 50. What do you do with that claim, and what will the run show?
Think about what type a typed value has.
Here's the answer. Treat it as a guess and run it. The typed 25 is the string "25," so the run prints 2525, two copies of the text, and the run caught the slip.
The chatbot proposes, and the run decides.
Closing
Let me pull it together in the order we built it. Input always hands back a string, so the typed 25 is text until int turns it into a number, and then 25 plus 1 prints 26. An f-string fills each pair of braces with a value, so the reading log prints 45 pages read so far, and without the f the braces print as they are. Indexes count from 0 on the left and from minus 1 on the right, so book at 0 is t and book at minus 1 is k. A slice keeps its start and drops its stop, so book from 4 to 9 is river, 5 characters. Len counts every character, the last index is the length minus 1, an index past the end raises an IndexError, and a slice past the end stops quietly. And every claim about what code prints gets checked by a run.
Next in this module come the slide deck, the Readings and Resources page, the lecture tutorial, the practice set, the quiz, and the Coding Lab. Then, in Week 4, Booleans & Conditionals, your programs learn to choose which line runs, often based on what the user typed.
Built with The Course Maker · samples.thecoursemaker.com