Back to Study Material Python

Input and Output

The print function writes output to the standard output stream. Its full signature is print(*objects, sep=" ", end="\n", file=sys.stdout, flush=False). By ...

Input and Output

The print Function

The print function writes output to the standard output stream. Its full signature is print(*objects, sep=" ", end="\n", file=sys.stdout, flush=False). By default, multiple values are separated by a space and a newline is added at the end. Example: print("Score:", 95) outputs "Score: 95". You can change the separator with sep: print("a", "b", "c", sep="-") outputs "a-b-c".

Formatted Output with f-strings

f-strings (formatted string literals), introduced in Python 3.6, are the modern and preferred way to embed expressions inside strings. Prefix a string with f and wrap expressions in curly braces: name = "Alice"; print(f"Hello, {name}!") outputs "Hello, Alice!". You can include expressions and format specifiers: print(f"{3.14159:.2f}") outputs "3.14". f-strings are faster than % formatting and str.format() and far more readable.

The input Function

The input function reads a line of text from the keyboard and returns it as a string. Example: age = input("Enter your age: "). The optional prompt string is displayed before reading. Critically, input always returns a string, even if the user types a number. To work with the value as an integer you must convert it: age = int(input("Enter your age: ")). Forgetting this conversion is one of the most common beginner bugs.

Type Conversion on Input

Because input returns a string, arithmetic on raw input gives unexpected results. "5" + "3" is "53" (string concatenation), not 8. Use int() for whole numbers, float() for decimals, and split() combined with map() for multiple values on one line. Example for two integers on one line: a, b = map(int, input().split()). This pattern appears constantly in competitive programming problems.

Worked Example

Write a program that asks for a user's name and birth year, then prints their approximate age. name = input("Your name: "); year = int(input("Birth year: ")); age = 2024 - year; print(f"{name}, you are approximately {age} years old."). This example combines input, type conversion with int(), arithmetic, and f-string output — all core I/O skills tested in introductory Python exams.

Exam Tip

Exams frequently test what happens when you pass multiple arguments to print: they are joined by the value of sep (default space). They also test the end parameter: print("hello", end="") suppresses the trailing newline, so the next print continues on the same line. Another common question: why does input("Enter: ") + 5 raise a TypeError? Because input returns a string and you cannot add an integer to a string without explicit conversion.