Find a course

Module 2: Math, Text and InputLesson 4 of 1013 min

Strings and User Input

Ask the user for input, convert text to numbers, join and repeat strings, and build tidy output with f-strings and string methods.

Step 1 of 14Learn

Programs that listen

So far your programs say the same thing every time. Real programs react to the person using them. input() pauses the program, shows a prompt and waits for the user to type something and press Enter:

name = input("What's your name? ")
print("Nice to meet you,", name)

Whatever the user types is stored in name. Notice the space at the end of the prompt: without it, the user's typing would be jammed right against the question mark.

Here is the rule that causes more beginner bugs than any other: input() always returns a string. Even if the user types 15, you get the text "15", not the number 15.

age = input("Age: ")
print(age + 1)

This crashes with a TypeError, because Python won't add the number 1 to the text "15". It doesn't guess what you meant. You have to convert the text yourself:

age = int(input("Age: "))
print("Next year you will be", age + 1)

int() turns a string of digits into an integer. Use float() when the user might type decimals, such as a price or a time in seconds, and str() to turn a number back into text.

Step 2 of 14Practice · What would you do?

What would you do?

Ava's program asks for two test scores and adds them:

a = input("Score 1: ")
b = input("Score 2: ")
print(a + b)

She types 40 and 45, and the program prints 4045. What's the best fix?

Step 3 of 14Practice · Diagram

input() always gives you text

At which step does the value become a real number?

Tap the shape that answers the question, then press Check.

input() always gives you textProcess diagram: User types 15 → input() returns "15" → int() converts it → Now math works.User types 15input()returns "15"int()converts itNow mathworks
User types 15
input() returns "15"

A string, even though it looks like a number.

int() converts it

int("15") gives the number 15.

Now math works

15 + 10 is 25, not "1510".

Step 4 of 14Learn

Joining, repeating and measuring text

Strings have their own operators. + joins (concatenates) them and * repeats them:

first = "Super"
second = "Nova"
print(first + second)   # SuperNova
print("ha" * 3)         # hahaha
print("-" * 20)         # a line of 20 dashes

+ doesn't add a space, so "Super" + " " + "Nova" is how you'd get Super Nova.

You can't join a string and a number with +. "Level " + 3 is a TypeError. Convert first: "Level " + str(3).

len() counts the characters in a string, including spaces and punctuation: len("Game over!") is 10.

Each character has a position called an index, and Python starts counting at 0:

word = "PYTHON"
print(word[0])    # P
print(word[2])    # T
print(word[-1])   # N  (negative counts from the end)

The last index of a string is always len(word) - 1. Asking for word[6] here causes an IndexError, because a 6-letter string has indexes 0 to 5.

Step 5 of 14Compare

Index positions in "PYTHON"

AspectPYTHON
Index from the start012345
Index from the end-6-5-4-3-2-1

Step 6 of 14Practice · Choose one

tag = "gamer42". What does print(tag[1] + tag[-1]) show?

Step 7 of 14Learn

f-strings: the easy way to format

Building output with commas and + gets messy fast. f-strings are cleaner. Put an f before the opening quote, then write any variable or expression inside curly braces:

name = "Leo"
points = 1250
print(f"{name} scored {points} points!")
print(f"Double points: {points * 2}")

This prints Leo scored 1250 points! and Double points: 2500. You don't need str(); the f-string converts values for you.

f-strings can also format numbers. Add :.2f after a value to show exactly two decimal places:

price = 7.5
tax = price * 0.08
print(f"Tax: ${tax:.2f}")   # Tax: $0.60

Without the format, you'd see 0.6, which looks odd for money. The 2 is the number of decimal places; :.1f would give one.

Forgetting the f is the number one f-string bug: print("{name} won") prints the braces literally, {name} won. If you see curly braces in your output, check for the missing f.

Step 8 of 14Practice · Fill in the blanks

Fill in the blanks

Complete the line so it prints Total: 12.50 when total = 12.5. print("Total: {total:.f}")

Step 9 of 14Practice · Code challenge · Python

Code challenge · Python

A leaderboard needs neat names. Complete score_line(name, points): remove extra spaces from the start and end of name, give it a capital first letter like a title, and return a string in this format:

Nova scored 1250 points!

For example, score_line(" nova ", 1250) returns "Nova scored 1250 points!".

The def line and the return are already written for you; you will learn exactly how they work in the Functions lesson. Fill in the middle.

Real Python, running in a sandbox in your browser.
  • score_line(" nova ", 1250)
  • score_line("leo", 80)
  • score_line("PRIYA", 0)
  • score_line(" sam", 3)

Step 10 of 14Tap to reveal

Handy string methods

  1. .upper() and .lower()

    "Hello".upper() gives "HELLO" and .lower() gives "hello". Lowercasing is perfect for comparing answers: answer.lower() == "yes" accepts Yes, YES and yes.

  2. .strip()

    Removes spaces from both ends: " pizza ".strip() gives "pizza". Users often type stray spaces, so stripping input avoids "wrong answer" bugs.

  3. .replace(old, new)

    "I like cats".replace("cats", "dogs") gives "I like dogs". Every match is replaced.

  4. .title()

    Capitalizes each word: "new york".title() gives "New York".

  5. Strings don't change

    Methods return a new string. name.upper() on its own does nothing useful; write name = name.upper() to keep the result.

Step 11 of 14Practice · Work it out

What does this print? `` msg = " Hi there " print(len(msg.strip())) ``

Step 12 of 14Practice · Put in order

Put these lines in order to make a program that asks for a price and a quantity and prints the total with two decimals.

Drag the items, or use the arrow buttons, to put them in order.

  1. qty = int(input("How many? "))
  2. total = price * qty
  3. print(f"Total: {total:.2f}")
  4. price = float(input("Price: "))

Step 13 of 14Note

Step 14 of 14Practice · Spot the mistake

This program should greet the user and say how old they will be in 5 years. Tap the lines with bugs.