Input, Output and f-strings
You will format output clearly and understand how text entered with input becomes a string.
Printing values
name = 'Mina'
points = 42
print('Player:', name, 'Points:', points)
print('Ready', end='!\n')
print() puts spaces between separate values, so the first line is easy to read. Its usual ending is a new line. Here end='!\n' changes that ending to an exclamation mark and then a new line.
Formatting strings
item = 'notebook'
price = 3.5
quantity = 4
print(f'{quantity} {item}s cost ${price * quantity:.2f}')
print(f'Next quantity: {quantity + 1}')
Put an f before a quoted string to make an f-string. Curly braces hold a value or expression. :.2f formats the price with exactly two digits after the decimal point.
visitors = 1234567
city = 'Lima'
print(f'{city} had {visitors:,} visitors.')
print('{} has {} letters.'.format('Python', 6))
The : inside an f-string starts a format instruction. The , instruction adds thousands separators. You may also use str.format(), as in the second line, but f-strings are often easier to read.
Getting user input
entered_age = '12'
age = int(entered_age)
print(f'Next year you will be {age + 1}.')
The simulated value starts as text. int() changes '12' into the number 12, so Python can add 1 before printing the sentence.
Key points
- print() displays values and normally starts a new line after them.
- F-strings use curly braces for values and expressions.
- Use :.2f for two decimal places and :, for thousands separators.
- str.format() is an older formatting style you may still see.
- Text returned by input() must be converted for numeric math.
Worked example
A bKash-style receipt: build a neat line from a name and an amount with an f-string.
name = "Nusrat"
amount = 1250.5
print(f"{name} sent {amount:.2f} taka")
How it works, step by step
- Put f before the quote to make an f-string.
- {name} drops the variable's value into the text.
- {amount:.2f} formats the number to exactly 2 decimal places.
References & Further Reading
Related entries from PyLabs's own reference library.
Practice exercise
Not passed yetSet name to 'Kai' and score to 12500. Use one f-string to print the sentence below with a thousands separator.
Expected output:
Kai scored 12,500 points.
# Write your code below
Check yourself
Input, Output and f-strings quiz
10 questions. You get instant feedback per question, and the timer starts when you press the button.
Lesson incomplete
Not completedCreate an ID or sign in to save lesson completion across devices.