Python Quest

Track 2 · Lesson 9 of 11

Processing user input

Read what a user types, clean it up, convert it, and split one line into several values.

About 35 minBeginner4 exercisesFree

You will be able to

  • Read text with input() and convert it to the type your program needs
  • Clean typed text with strip(), lower() and title() before using it
  • Split one line of input into several values with split()
  • Unpack the parts of a split line into separate variables

Real users don't type tidy data. They add a space before their name, write it in capitals, press Enter on an empty line, or type three numbers on one line separated by spaces. A program that works only with perfect input breaks the first time a real person uses it.

This lesson pulls together what you've learned about strings and conversions into a reliable routine for input: read, clean, convert, use.

Read, clean, convert, use
name = input("Your name: ").strip().title()
hours = float(input("Hours worked: "))
rate = float(input("Hourly rate: "))

pay = hours * rate
print(f"{name} earns {pay:,.2f} SAR")
Input given to the program: " layla hamdan ", "37.5", "42"

Try it: Change the first stdin value to "OMAR " and run it again. title() and strip() tidy it up.

Line by line:

  1. input("Your name: ") shows the prompt and returns what was typed, as a string: " layla hamdan ".
  2. .strip() removes the spaces at both ends, and .title() capitalises each word. Methods can be chained: each one works on the result of the one before.
  3. float(input(...)) reads the hours and converts them in one step. float() already ignores outer spaces, so no strip() is needed for numbers.
  4. The f-string formats the pay with a thousands separator and two decimal places.

The prompt text is shown to the user, but as you saw in Asking for input, the checker leaves prompts out and compares only what your program prints. The exercises use input() with no prompt text to keep the code short; a prompt of your own does no harm.

Several values on one line: split()

When a user types 120 80 45 on one line, input() returns the single string "120 80 45". The string method split() breaks it apart wherever there is whitespace and gives you the pieces as a list of strings:

"120 80 45".split()      # ['120', '80', '45']
"  120   80 45 ".split() # ['120', '80', '45'] - extra spaces are ignored

You'll study lists properly later. For now you need one trick: when you know how many pieces there are, you can unpack them straight into variables, the same way you did with multiple assignment in Variables and assignment:

length, width, height = "120 80 45".split()

Each variable still holds a string, so convert them before doing arithmetic.

Splitting a line of numbers
line = input("Length, width and height in cm: ")
length, width, height = line.split()

volume_cm3 = float(length) * float(width) * float(height)
print("Volume:", volume_cm3 / 1000, "litres")
Input given to the program: "30 20 15"

Try it: Change the stdin to "30 20" (only two numbers). Python raises a ValueError because there aren't enough values to unpack.

Splitting on something other than spaces

split() with no argument splits on any run of whitespace. Give it a separator to split on something else, such as a comma: "80,75,90".split(",") gives ['80', '75', '90']. With a separator, extra spaces are kept: "80, 75".split(",") gives ['80', ' 75']. That's fine if you convert with int() (it ignores outer spaces), but strip text pieces before you display or compare them.

Predict the output

line = "3 4"
a, b = line.split()
print(a + b)
print(int(a) + int(b))

Guided practice · ●difficulty 1 of 5 · about 5 min

Weekly pay slip

A payroll program reads three lines with input() (no prompt text — the tests type the values for you):

  1. the employee's name, which may have extra spaces and odd capitals,
  2. the hours worked (can have decimals),
  3. the hourly rate in SAR (can have decimals).

Clean the name so each word starts with a capital and there are no outer spaces, calculate the pay, and print:

Faris Odeh earns 1,575.00 SAR

That's the output for " faris odeh", 37.5 and 42. Show the pay with a thousands separator and two decimals. Store the cleaned name in name and the pay in pay.

Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.

Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type

Output

Run your code to see its output, or Check to test it against the requirements.

The solution becomes available after you pass, or after all three hints and two checks.

Challenge · ●●difficulty 2 of 5 · about 6 min

Shipping box volume

A packing station measures each box and types the three dimensions on one line, in centimetres, separated by spaces — for example 40 30 25. Staff aren't careful about spacing, so " 40 30 25 " must work too.

Read the line with input() (no prompt text), split it into length, width and height, and store the volume in litres in litres (1 litre = 1000 cubic centimetres). Dimensions can have decimals. Print:

Volume: 30.0 litres

Show the volume with one decimal place.

Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.

Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type

Output

Run your code to see its output, or Check to test it against the requirements.

The solution becomes available after you pass, or after all three hints and two checks.

Edge cases · ●●difficulty 2 of 5 · about 6 min

Clean up a customer record

A loyalty-card form collects a customer's full name and membership code, one per line (input() with no prompt text). People type them carelessly: " sara AL-HARBI " and " ab12 ".

Store the tidied name in name (no outer spaces, each word capitalised) and the tidied code in code (no outer spaces, all capitals). Then print:

Customer: Sara Al-Harbi (AB12)

A customer who gave only one name, such as " yousef", is fine too.

Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.

Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type

Output

Run your code to see its output, or Check to test it against the requirements.

The solution becomes available after you pass, or after all three hints and two checks.

Debugging · ●●difficulty 2 of 5 · about 6 min

Fix the quiz score total

A teacher types a student's three quiz scores on one line, separated by commas, such as 80,75,90. The program should print the total (a whole number) and the average with two decimals:

Total: 245
Average: 81.67

Instead it prints Total: 807590 and then crashes. Find and fix the bug. Teachers sometimes put a space after each comma (80, 75, 90), and that must work too. Keep the variable names total and average.

Python code editor. Tab indents. Press Escape then Tab to leave the editor. Control or Command plus Enter runs the code; Shift plus Enter checks your answer.

Ctrl+Enter run · Shift+Enter check · your code is saved in this browser as you type

Output

Run your code to see its output, or Check to test it against the requirements.

The solution becomes available after you pass, or after all three hints and two checks.

Summary

  • input() always returns a string; follow the routine read, clean, convert, use.
  • Clean text with chained methods such as strip().title() or strip().upper().
  • split() breaks a line on whitespace and ignores extra spaces; split(",") splits on commas.
  • Unpack a split line into variables (a, b, c = line.split()) and convert each piece before calculating.