Teach Your Kids To Code: A Parent-friendly Guide to Python Programming

(vip2019) #1
Numbers and Variables: Python Does the Math 49

you’d type 4 ** 2. Here’s what our program, MathHomework.py,
looks like when we put it together:


MathHomework.py


print("MathHomework.py")


Ask the user to enter a math problem


problem = input("Enter a math problem, or 'q' to quit: ")


Keep going until the user enters 'q' to quit


while (problem != "q"):


Show the problem, and the answer using eval()


print("The answer to ", problem, "is:", eval(problem) )


Ask for another math problem


problem = input("Enter another math problem, or 'q' to quit: ")


This while loop will keep going until you enter 'q' to quit


This while statement will keep asking for problems and print-
ing answers until the user presses the Q key to quit the program.
While this short program can’t help us with algebra yet, it can
do more than basic math. Remember our discussion about Python’s
true division? We called it “pizza division,” because it let us split
pizzas evenly among any number of people. Well, Python can still
do integer division (whole-number division); we just need to learn
two new operators.
When would you want to do integer division? Let’s say your
teacher gives you and your three friends 10 cartons of chocolate
milk to enjoy, and you want to divide the milk fairly so that each
of you gets the same number of cartons. There are four of you (you
plus three friends), so 10 ÷ 4 equals 2.5. Unfortunately, you can’t
just cut a carton of milk in half. If you had cups, you could split
a carton between two friends, but let’s pretend there are no cups
around. If you wanted to be fair, you would have to take two car-
tons each, and give the teacher back the remaining two cartons.
That sounds a lot like long division: the two leftover cartons that
you return to the teacher are the remainder when you divide 10
by 4. In math, we sometimes note the remainder from long division
like this: 10 ÷ 4 = 2 R2. In other words, 10 divided by 4 equals a
quotient of 2, with a remainder of 2. This means that 4 goes into
10 evenly 2 times, with 2 remaining.
In Python, integer division is performed with the double-
forward slash operator, //. So 10 // 4 equals 2 , and 7 // 4 equals 1
(because 4 goes into 7 only 1 time, with a remainder of 3). The //
operator gives us our quotient, but what about the remainder? To

Free download pdf