Skip to lesson content

PYTHON / LESSON 4 OF 18

Input output and operators

Read the explanations, work through the examples, and complete the student tasks.

Learning goals

Read user input, format output, and use arithmetic, comparison, logical, membership, and identity operators correctly.

Explanation

input returns a string. Convert it when you need arithmetic. print accepts multiple values; sep controls their separator and end controls what follows the output. An f-string inserts expressions inside braces.

Arithmetic operators include +, -, *, /, //, %, and **. / performs division; // floors the quotient; % gives a remainder; ** raises a power. Comparisons such as ==, !=, <, and >= produce booleans. Assignment operators such as += update a name. Use parentheses to clarify mixed expressions.

Example 1 A simple order calculator

For this example, enter whole numbers when prompted.

name = input("Customer name: ")
quantity = int(input("Quantity: "))
price_rupees = int(input("Unit price in rupees: "))
total = quantity * price_rupees
print(f"{name}, your total is Rs {total}.")
print("Receipt", quantity, total, sep=" | ")

For Ali, 3, and 250, the final two lines are:

Ali, your total is Rs 750.
Receipt | 3 | 750

This introductory example assumes valid numeric input. Lesson 12 adds validation and error handling.

Example 2 Operators in context

print(17 // 5, 17 % 5, 2 ** 3)
print(-7 // 3)
score = 75
has_paid = True
print(score >= 50 and has_paid)
print(score < 50 or not has_paid)
print("py" in "python")
score += 5
print(score)
a = [1, 2]
b = [1, 2]
c = a
print(a == b, a is b, a is c)

Expected output:

3 2 8
-3
True
False
True
80
True False True

== compares values; is compares object identity. Separate equal lists have equal contents but are different objects. Use is None for missing values, not is to compare ordinary numbers or text. and and or short circuit; with nonboolean operands they return an operand rather than always returning True or False.

Student tasks

1. Read a number of minutes and report full hours and remaining minutes. Input 135 must produce 2 hours and 15 minutes.

2. Ask for a rectangle's width and height and print its area. Test 4 and 6; expected area: 24.

3. Check whether a supplied username occurs in a list of allowed names. Print a boolean.

4. Create two equal but separate lists and an alias. Display and explain both equality and identity comparisons.

Completion check: use numeric conversion, an f-string, //, %, and at least one logical expression.