Sub topic 1
Writing Output with `print()`
Prerequisites
This chapter assumes basic Python syntax, variables, expressions, and running a script. You should also know str, int, and float, plus basic if, while, try, and except statements.
Writing output with `print()`
print() writes text to standard output, usually the terminal. It accepts multiple values and separates them with a space by default. The sep argument changes that separator. The end argument replaces the usual newline.
print("a", "b", "c", sep="-")
print("Loading", end="...")
print("done")This prints:
a-b-c
Loading...doneUse file= when output should go to another stream or file. That choice becomes important when separating normal results from diagnostics.
Escape sequences, raw strings, and multi-line text
An escape sequence is a backslash followed by a special character. Common sequences include \n for a newline, \t for a tab, and \\ for a literal backslash.
print("Name:\tAda\nStatus:\tready")A raw string, written with an r prefix, keeps most backslashes literal. It is useful for regular expressions and Windows paths.
pattern = r"\d+\sitems"
path = r"C:\Users\Ada\notes.txt"
print(pattern)
print(path)For text spanning several lines, use triple-quoted strings. Their indentation and newlines become part of the string.
message = """First line
Second line
Third line"""
print(message)Reading input with `input()`
input() displays an optional prompt, waits for a line, and returns the entered text as a str. It does not return a number automatically.
name = input("Name: ")
print(f"Hello, {name}!")This program's data flow is:
Turning input text into numbers
Convert input explicitly with int() or float(). Conversion can raise ValueError when the text is not valid.
raw = input("Quantity: ")
quantity = int(raw)
print(f"Total items: {quantity}")Use float() for decimal values:
price = float(input("Price: "))
print(f"Price: ${price:.2f}")Validate untrusted input with try and except, then retry when conversion fails.
Exercise
What type does input() return, and which function converts text such as "42" to an integer?
Show answer
input() returns str. int("42") returns the integer 42.