Output with print()#
You have already used print(). Let's learn everything it can do.
Printing several values#
Separate values with commas. print() puts one space between them automatically and converts numbers to text for you:
The sep parameter#
sep (separator) decides what goes between values. Default is a space " ".
The end parameter#
end decides what is printed after the last value. Default is "\n" (a new line).
Escape sequences#
Special characters inside strings start with a backslash \:
| Code | Meaning |
|---|---|
\n |
new line |
\t |
tab space |
\\ |
a backslash |
\" / \' |
quote inside a string |
f-strings (formatted strings) - the best way to format output#
Put f before the quotes and write variables or expressions inside { }:
Formatting numbers inside f-strings#
| Format | Example | Result |
|---|---|---|
:.2f - 2 decimal places |
f"{3.14159:.2f}" |
3.14 |
:, - thousands separator |
f"{1500000:,}" |
1,500,000 |
:.1% - percentage |
f"{0.875:.1%}" |
87.5% |
:>8 - right align in 8 spaces |
f"{'Hi':>8}" |
Hi |
:<8 - left align |
f"{'Hi':<8}" |
Hi |
:^8 - centre |
f"{'Hi':^8}" |
Hi |
:05d - pad with zeros |
f"{42:05d}" |
00042 |
Older ways you'll see in other code: "Hello %s" % name and "Hello {}".format(name). They still work, but f-strings (Python 3.6+) are shorter, faster and easier to read.
Input with input()#
input() pauses the program, waits for the user to type something and press Enter, then returns what they typed as a string.
name = input("Enter your name: ")
print("Welcome,", name)
On a computer it looks like this:
Enter your name: Arjun
Welcome, Arjun
In our browser editor, click + Input and type the input values there (one per line) before pressing Run. Try it below.
input() always gives a string#
This is the #1 beginner mistake:
a = input("First number: ") # user types 10
b = input("Second number: ") # user types 20
print(a + b) # 1020 (text joined, not added!)
Convert the input to a number:
a = int(input("First number: "))
b = int(input("Second number: "))
print(a + b) # 30
input() हमेशा string (text) देता है, चाहे user नंबर ही क्यों न टाइप करे। इसलिए "10" + "20" का जवाब 30 नहीं बल्कि "1020" आता है - Python दोनों texts को जोड़ (join) देता है।
हल: int(input()) या float(input()) लिखें - इससे text तुरंत नंबर में बदल जाता है और गणित सही होता है।
Reading several values from one line#
Use .split() to break a line at spaces, and map() to convert each part:
You'll understand map() fully in the Lambda lesson - for now, remember this pattern.
Complete example: Simple interest calculator#
Summary#
print(a, b, sep=..., end=...)- control spaces and line endings.- Escape sequences:
\n,\t,\",\\. - f-strings:
f"{value}", with formats like:.2f,:,,:>10. input()returns a string - convert withint()/float().map(int, input().split())reads several numbers from one line.