Programs need to communicate with users. The most basic interactions are printing output and reading keyboard input.
print()
print() displays text or variable values on the screen.
Some characters have special meaning in code, so they need escape sequences.
\\: backslash\': single quote\": double quote\n: newline\t: tab
print("\"Hello\nWorld\"")Output:
"Hello
World"KNOWLEDGE QUIZ
Placeholder formatting
You can also insert values into a string with placeholders.
%d: integer%f: floating-point number%s: string
length = 10
width = 5
area = length * width
print("Area = %d * %d = %.2f" % (length, width, area))Output:
Area = 10 * 5 = 50.00A more modern style is the f-string, which can directly reference variables inside a string.
print(f"Area = {length} * {width} = {area:.2f}")KNOWLEDGE QUIZ
Controlling the line ending
By default, print() ends with a newline. Use the end parameter when you do not want that newline.
num1 = 1
num2 = 2
num3 = 4
num4 = 8
print(num1, end=', ')
print(num2, end=', ')
print(num3, end=', ')
print(num4, end='...')Output:
1, 2, 4, 8...input()
input() reads text from the keyboard and assigns it to a variable.
Important: input() returns a str by default. Convert it when you need a number.
import math
r = float(input("Radius: "))
area = math.pi * r ** 2
print("Area = %.2f" % area)One possible run:
Radius: 5
Area = 78.54Here, float() converts the input string into a decimal number. math.pi comes from Python’s math module.
KNOWLEDGE QUIZ
Output Lab Bench
Run the three code cards in order and watch how each statement changes the terminal.
Calculate the distance between two points
Read two coordinate points and print the planar distance.
- Read x1, y1, x2, and y2 as four floating-point numbers.
- Apply the distance formula to compute the result.
- Print the distance rounded to two decimal places.
Build a temperature record card
Read one Celsius value, store it in clearly named variables, convert it to Fahrenheit, and print a compact report.
- Read one Celsius value with float(input(...)).
- Store the Fahrenheit result in a variable named fahrenheit.
- Create a string variable named report_title and print it together with the converted value.