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

(vip2019) #1

48 Chapter 3


Finally, at x, we increase the width or thickness of the pen
as we get farther from the center of the screen. Figure 3-9 shows
the drawings that result from entering eight sides and three
sides.

Figure 3-9: The picture from ColorSpiralInput.py with eight sides (left)
and three sides (right)

Python Does Your Homework


We’ve seen that Python is a powerful and fun programming lan-
guage that can handle all sorts of data: numbers, strings, lists,
and even complex math expressions. Now you’re going to put
Python’s power to work to do something very practical: your
math homework!
We’re going to write a short program that combines strings
and numbers, using the eval() function to turn math problems
into answers. Earlier in the chapter, I said that the eval() function
could turn the string "20" into the number 20. As promised, eval()
can do even more than that: it can also turn "2 * 10" into the num-
ber 20. When the eval() function operates on a string of keyboard
characters, it evaluates them just like the Python shell would. So
when we enter a math problem as input, running eval() on that
input can give us the answer to the problem.
By printing the original problem that the user entered, then
outputting eval(problem), we can show the original problem and
the answer all on one line. Remember the operators in Table 3-1:
if you needed the answer to 5 ÷ 2, you’d type 5 / 2, and for 4^2 ,
Free download pdf