1.3 Input and Output
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"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}")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.