Strings, input & output

~25 min

f-strings: the default way to format output

You could glue strings together with +, but do not. Use f-strings — put an f before the quotes and drop variables inside {curly braces}:

name = "Tunde"
price = 1500
print(f"{name}, your total is ₦{price * 3}")
Tunde, your total is ₦4500

You can put any expression inside the braces, and you can control formatting:

amount = 1499999.5
print(f"₦{amount:,.2f}")
₦1,499,999.50

:,.2f means "thousands separators, 2 decimal places". You will use this on every receipt you ever print.

Useful string methods

Strings come with built-in tools. Try these in the REPL:

>>> "lagos".upper()
'LAGOS'
>>> "  Ada Obi  ".strip()
'Ada Obi'
>>> "080-1234-5678".replace("-", "")
'08012345678'
>>> len("Ibadan")
6

Methods do not change the original string — they return a new one. If you want to keep the result, assign it: clean = raw.strip().

Getting input from the user

input() shows a prompt, waits for the user to type, and gives you what they typed:

name = input("What is your name? ")
print(f"Welcome, {name}!")
What is your name? Bisi
Welcome, Bisi!

Critical fact: input() ALWAYS returns a string. Even if the user types 25, you get "25". This bites every beginner:

age = input("Your age: ")
print(age + 5)
Your age: 25
Traceback (most recent call last):
  File "age.py", line 2, in <module>
    print(age + 5)
          ~~~~^~~
TypeError: can only concatenate str (not "int") to str

Read it bottom-up: TypeError, string plus int. The fix is to convert:

age = int(input("Your age: "))
print(f"Next year you will be {age + 1}")
Your age: 25
Next year you will be 26

Use int() for whole numbers, float() for decimals.

When conversion fails: ValueError

What if the user types nonsense?

>>> int("twenty")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'twenty'

Bottom line first: ValueError — the text 'twenty' cannot become an int. For now, our programs may crash on bad input like this; in Week 2 you will learn to guard against it, and later to handle it gracefully.

Try it now

Write airtime.py: ask for the user's name and how much airtime they want to buy (₦). Print a confirmation line like Bisi, you bought ₦500.00 airtime. using an f-string with :,.2f formatting. Type it — do not paste — and test it with a decimal amount too.

Sign in to track your progress.