Functions, Variables · 13 min

Run scripts and read input

Use the terminal, turn input into numbers, and format a result.

Jump to the automation lab

A text editor saves source as a .py file. The terminal runs commands such as python estimate.py. Enter python on its own to try expressions in the interactive interpreter. Depending on your installation, use python3 in place of python.

input() returns one line as a string. Convert it with int() or float() before calculating. In this playground, the Program input field supplies one line per call. A real terminal can show a prompt using input("Hours: ").

Use an f-string such as f"{total:.2f}" to display two decimal places. Formatting rounds the display while leaving the original number available for later calculations. Floats approximate many decimal fractions.

Follow the example

The first line arrives as text.

Run the example and practice

Keep the two inputs in their original order. Add a fixed booking fee of 3 before formatting the total.

Target output

Total: 33.00
Show a hint

Add 3 to the result of hours * rate. Use Run code with a different input to see the result change.

Run code uses the input here. Check output uses the original sample input.

Output

Ready

Run your code to see the output here.

The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.

Show one solution
hours = float(input())
rate = int(input())
total = hours * rate + 3
print(f"Total: {total:.2f}")

Automation lab

Split a shared expense

Read a total and a headcount from program input, then calculate the equal share.

Output

Ready

Run the example to see the output here.

Enter 79.20 and 6 on separate lines in Program input, then run it again.

Further reading in Automate the Boring Stuff with Python by Al Sweigart