In the previous unit, we learned to interact with users using input() and to display results with print(). Remember that input() returns a string, so we must convert it to a number with int() or float() before doing arithmetic. When joining numbers with text, we use str() to convert numbers to strings. We also contrasted concatenation ("Hello " + name) with comma-separated printing (print("Hello", name), which auto-inserts spaces). For arithmetic, we differentiated between / (float division), // (integer division), and % (modulus), and used round(value, 2) to format decimals. A common pitfall is writing "Age: " + 10, which causes a type error; fix it with "Age: " + str(10) or print("Age:", 10).
Now students try to finish the following practice to review what we learned last unit:
Read the price (float) and quantity (int) for two items. Compute and print the total cost and the average price (rounded to two decimals). Also, show two print styles:
str() and a currency symbol.Output example:
Price of item 1: 2.5
Qty of item 1: 4
Price of item 2: 5
Qty of item 2: 3
Total = 22.0 | Average price = 3.75
You pay $22.0 in total, avg $3.75
Answer example:
price1 = float(input("Price of item 1: "))
qty1 = int(input("Qty of item 1: "))
price2 = float(input("Price of item 2: "))
qty2 = int(input("Qty of item 2: "))
total = price1 * qty1 + price2 * qty2
avg_price = (price1 + price2) / 2
print("Total =", round(total, 2), "| Average price =", round(avg_price, 2))
print("You pay $" + str(round(total, 2)) + " in total, avg $" + str(round(avg_price, 2)))
With these tools, our programs can now receive input, compute results, and present them clearly. Today we’ll build on this foundation and teach programs to ‘decide’ using conditions.