Special Offer Diwali Special Bundle Offer: 3 courses for ₹8,999, save ₹9,001 (50% OFF)! Limited seats available. View Bundles →
0% Completed
Tutorials / Python Tutorial / Chapter 1: Getting Started & Language Basics
PYTHON ⏱ 10 min read

Input and Output with Modern f-strings

Interacting with users requires reading keyboard input and presenting cleanly formatted output.

What is it?

The `input()` function prompts the user for text input from the console. Formatted string literals (f-strings, introduced in Python 3.6) provide the most readable, powerful way to format output.

Why is it used?

Powers command-line tools, interactive scripts, terminal menus, and dynamic data logging.

Detailed Explanation

The `input()` Function: • Always returns a `str` (string). If you want a number, you must explicitly wrap it: `int(input("..."))`. Modern f-strings (`f"..."`): • Embed variables directly with `{variable}`. • Embed expressions and function calls: `{price * 0.9}`. • Format specifiers: • `:.2f`: Float to 2 decimal places. • `:,`: Comma separated thousands (`₹{1000000:,}` -> `₹1,000,000`). • `:>10` / `:<10`: Left/right alignment with padding.

Syntax Structure

Syntax Blueprint
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(f"Hello {name}, you are {age} years old.")

Code Example

PYTHON Code
# Student Report Card Generator
student_name = "Rohan Patil"
subject_1 = 88
subject_2 = 92
subject_3 = 85

total_marks = subject_1 + subject_2 + subject_3
average_percentage = total_marks / 3

# Modern f-string formatting
print(f"{'STUDENT GRADE REPORT':^40}")
print("-" * 40)
print(f"Name:       {student_name}")
print(f"Total:      {total_marks} / 300")
print(f"Percentage: {average_percentage:.2f}%")
print(f"Status:     {'PASSED WITH DISTINCTION' if average_percentage >= 75 else 'PASSED'}")
print("-" * 40)

Explanation of the Code

• `f"{'...':^40}"` centers text across 40 characters. • `"-" * 40` repeats the hyphen 40 times to draw a divider line. • Demonstrates inline conditional ternary expression inside the f-string placeholder.

Expected Output

STUDENT GRADE REPORT ---------------------------------------- Name: Rohan Patil Total: 265 / 300 Percentage: 88.33% Status: PASSED WITH DISTINCTION ----------------------------------------

Real-World Application

Used across CLI utilities, automated cron report generators, and terminal dashboards.

Common Mistakes to Avoid

• Forgetting that `input()` returns a string, causing `age + 1` to crash with `TypeError`. • Omitting the leading `f` before the string quote (`"{name}"` will print literal curly braces).

Quick Practice Challenge

Format a price variable `95400.5` into Indian currency with two decimal places and thousands commas using an f-string.

Key Takeaways

• `input()` always captures input as a string. • Always prefix formatted strings with `f"..."`. • Use f-string specifiers (`:.2f`, `:,`) for professional numeric displays.