Most programs do two things: take some input from the outside world and write some output back. This lesson covers Python's two built-ins for that job, input() and print(), and the parameters that let you control exactly what goes where.
input()input() pauses the program, waits for the user to type something and press Enter, then returns whatever they typed as a string. Always a string. Even if they type a number.
Sample run:
The argument to input() is the prompt: any text you want shown before the cursor. A trailing space in the prompt ("What's your name? ") keeps the user's input visually separated from the question.
input() is the synchronous, blocking version. The program stops dead until Enter is pressed. There's no timeout, no default value, no validation. Whatever the user types is what you get back.
If the user presses Enter without typing anything, you get an empty string "", not None. That's a real result, not an error, and you have to handle it yourself if it matters.
input() Always Returns a StringThis is the single most common beginner trap with input(). Watch:
Sample run:
Python doesn't crash because multiplication is broken. It crashes because quantity is the string "3", not the number 3, and you can't multiply a string by a float. You have to convert the input to the type you actually need. The built-ins int() and float() do that:
Sample run:
int(input(...)) is so common you'll see it everywhere. The same pattern works for float() when prices or weights are involved:
Sample run:
The flow looks like this:
If the user types something that can't be converted (int("hello")), you'll get a ValueError. Handling that gracefully needs try/except. For now, assume reasonable input.
print()Here's the full signature of print():
That looks dense, but each piece is straightforward. *objects means you can pass as many arguments as you want. The other four are keyword parameters with defaults: a space between arguments, a newline at the end, output goes to standard output, and the output buffer isn't flushed immediately. The next sections walk through each one.
The simplest case prints a single value:
Multiple arguments get separated by a space and joined into a single line:
print() automatically converts every argument to its string form, so mixing strings, integers, and floats is fine. You don't need to call str(...) on numbers first.
sep Parametersep controls what print() puts between its arguments. It defaults to ' ' (a single space).
sep="" removes the separator entirely. sep=", " is handy for producing comma-separated output without manually adding commas. sep="\n" puts each argument on its own line, which is one quick way to print a list across multiple lines:
sep only applies between the arguments you pass in a single print() call. It has nothing to do with what happens between calls.
end Parameterend controls what print() writes after all the arguments. It defaults to '\n' (a newline), which is why each print() call moves the cursor to the next line.
Change end to keep multiple calls on the same line:
The first two calls write text with no newline at the end, so the third call continues on the same line. The third call uses the default end="\n", so the cursor moves down after it.
A common use is building progress indicators or formatted lists across multiple iterations. You can also use end=" " to separate calls with a space instead of a newline:
Or use end="\t" to separate with tabs, which is useful for quick tabular output.
f"..." strings are Python's most readable way to embed values inside text, and they're worth a quick introduction here.
The basic shape is a string literal prefixed with f, with expressions inside curly braces:
Anything inside {...} is evaluated as a Python expression. You can include variables, arithmetic, method calls, anything that produces a value. The :.2f part is a format specifier that rounds the number to two decimal places.
Without f-strings, you'd write the more verbose:
The f-string version is cleaner, faster, and easier to read. It's the default formatting tool in modern Python (added in Python 3.6).
Two more useful tricks for quick debugging:
The = after the variable name prints both the name and the value, which is handy when you're debugging and want to know what a variable holds without retyping its name. This was added in Python 3.8.
You can also embed multi-token expressions:
That's enough f-string for now. Just remember that f"...{value}..." swaps in the value of value.
Sometimes you need more than one value from the user. The straightforward way is one input() call per value:
Sample run:
Each input() prompts and waits separately. The user types one value, presses Enter, and the next prompt appears.
If you want to read several values from a single line, use the split() method on the input string. split() breaks the string apart on whitespace and returns a list:
Sample run:
You can then unpack the list into named variables:
Sample run:
Two things are happening here. input().split() produces a list of three strings. The line product, price_str, quantity_str = ... is iterable unpacking: Python assigns each list element to the matching name on the left. If the user types too few or too many words, you'll get a ValueError.
If you need a different separator, pass it to split(). For comma-separated values:
Sample run:
Notice the leading spaces in ' Sam' and ' Riley'. split(",") only splits on commas and doesn't trim surrounding whitespace. To clean each piece, use a list comprehension or process each value as you use it.
For now, when you want both comma separation and clean tokens, the common pattern is:
Sample run:
That's a preview of list comprehensions.
file ParameterBy default, print() writes to standard output (often shown as stdout), which is the terminal where your script is running. The file parameter lets you redirect that output somewhere else.
The most common alternative destination is standard error (stderr), a separate output stream meant for diagnostic messages, warnings, and errors. The reason it matters: when someone runs your script and pipes the output somewhere else (python script.py > results.txt), only stdout goes into the file. stderr still shows up on the terminal.
To write to stderr, import sys and pass sys.stderr as the file:
When run normally, both messages look identical. The difference shows up when output is redirected. Run that script as python script.py > results.txt, and results.txt will only contain Order received, while WARNING: low stock still shows up in the terminal. That separation is the whole point: regular output goes to the file, warnings stay visible to the operator.
You can also write to an open file object. For now, the rule of thumb is simple: send regular output to stdout (the default), and send diagnostic messages to stderr.
Cost: print() with file=sys.stderr is just as fast as the default. The cost difference comes from where the message ends up, not from any extra work Python has to do.
flush ParameterThis one matters less day-to-day, but it's good to know it exists. flush=False by default. When True, Python forces the output buffer to write immediately instead of waiting.
Why is there a buffer in the first place? Writing to a terminal one character at a time is slow at scale. Python buffers output and writes it in chunks, which is much faster. The downside: if your program crashes or runs in an unusual environment (some IDEs, redirected output, piped processes), buffered output can appear out of order or not at all.
Without flush=True, the Working and the dots might all appear at once at the end, since the buffer wouldn't be written until the newline at the end. With flush=True, each piece shows up immediately. Use flush=True when you're printing progress indicators or doing something where the timing of output visibility matters.
For most application code, you can leave flush at its default.
Here's a tiny order summary program that uses every piece from this lesson: reading input, converting types, splitting multiple values from one line, using f-strings for output, and sending a warning to stderr.
Sample run:
Don't worry about the if statement yet, but you can see the shape of a complete tiny program: prompt the user, convert what comes back, do something with it, and print results plus diagnostics on the right streams.
10 quizzes