1. Adding machineTo do
Read two whole numbers (two input calls) and print their sum.
| Input | Output |
|---|---|
| 1 ⏎ 2 | 3 |
| 10 ⏎ -4 | 6 |
Module 0 · Functions, Variables · Lesson 4 of 5
Python has whole numbers (int) and decimals (float). Because input gives you a string, convert it first:
x = int(input("x? "))
y = float(input("y? "))
Operators you'll use constantly:
+ - * as you'd expect/ divides and always gives a float: 7 / 2 is 3.5// divides and drops the remainder: 7 // 2 is 3% gives the remainder: 7 % 2 is 1** is "to the power of": 3 ** 2 is 9To control how a number looks, use round(z, 2) or format it inside an f-string:
print(f"{z:.2f}") # 2 decimal places
print(f"{1234567:,}") # 1,234,567
Classic beginner bug: "2" + "3" is "23", not 5. If math looks weird, check whether you forgot int().
What is 7 / 2 in Python 3?
What does "2" + "3" give?
What does f"{2/3:.2f}" produce?
What is 10 % 3?
Read two whole numbers (two input calls) and print their sum.
| Input | Output |
|---|---|
| 1 ⏎ 2 | 3 |
| 10 ⏎ -4 | 6 |
Read a mass in kilograms (a whole number) and print the energy in joules, using E = m × c² where c = 300000000.
| Input | Output |
|---|---|
| 1 | 90000000000000000 |
| 14 | 1260000000000000000 |
Read a bill total (may have decimals) and the number of people. Print each person's share as dollars with exactly two decimals, like $33.33.
| Input | Output |
|---|---|
| 100 ⏎ 3 | $33.33 |
| 59.5 ⏎ 2 | $29.75 |