Lesson 4 of 4
Read values typed by the user with input(), convert them to numbers, and present results as clear, well-aligned output.
About 20 minutes
input()sep, end and f-string alignmentSo far every value has been written into the program. Often you want a program to work with values that change each time it runs. input() pauses the program, shows a message (the prompt), and waits for the user to type something. Whatever they type is returned as a string.
In SPASCLE's editor there is no keyboard prompt while the program runs. Instead, when your code uses input(), a Program input box appears below the editor. Type one value per line; each input() call takes the next line, in order.
sample = input("Sample name: ")print("Recording data for", sample)The prompt Sample name: is printed first, then the program continues with the value from the input box. Try changing the input and running it again.
input() always returns a string, even when the user types a number. Text that looks like 2.7 can't be used in arithmetic until you convert it with float() (for decimals) or int() (for whole numbers). It is common to do both steps on one line.
This program asks for the mass and volume of a sample and calculates its density.
mass = float(input("Mass (g): "))volume = float(input("Volume (cm³): "))density = mass / volumeprint(f"Density: {density:.2f} g/cm³")Forgetting to convert
mass = input("Mass: ") without float(), then mass / volume fails with a TypeError, because you can't divide text. If the user types something that isn't a number, float() raises a ValueError. Later you will learn how to check input before using it.print() has two optional settings. sep sets what goes between values (a space by default), and end sets what goes at the end of the line (a new line by default). Changing end lets the next print() continue on the same line.
print("Fe", "Cr", "Ni", sep=" | ")print("Loading", end="...")print("done")Results are easier to read in neat columns. In an f-string, a number after the colon sets a minimum width. < aligns left, > aligns right, and you can combine width with decimal places, as in {density:>8.2f}.
print(f"{'Metal':<10}{'Density':>10}")print(f"{'Aluminium':<10}{2.70:>10.2f}")print(f"{'Copper':<10}{8.96:>10.2f}")print(f"{'Gold':<10}{19.32:>10.2f}")Most simple programs follow the same three steps: input (get the values), process (calculate), and output (present the result). This program converts a temperature typed by the user into two other scales.
celsius = float(input("Temperature (°C): "))kelvin = celsius + 273.15fahrenheit = celsius * 9 / 5 + 32print(f"{celsius:.1f} °C = {kelvin:.2f} K")print(f"{celsius:.1f} °C = {fahrenheit:.1f} °F")Choose an answer and press Check answer. You can retry as often as you like.