0% found this document useful (0 votes)
16 views11 pages

Python For Kids (Level1-Level 2) - 2nd Week

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 11

Python for kids | Sue’s Academy

Chapter 3.
Numbers and Variables: Python Does the Math
Variables: Where We Keep Our Stuff
In Chapter 1 and Chapter 2, we used a few variables (you might remember name from our
first program in Chapter 1 or x and sides from Chapter 2). Now let’s look at what variables really
are and how they work.
A variable is something you want the computer to remember while your program is
running.
my_name = "Bryson"
Let’s try a program using some variables. Type the following code in a new IDLE window
and save it as ThankYou.py.
ThankYou.py
my_name = "Bryson"
my_age = 43
your_name = input("What is your name? ")
your_age = input("How old are you? ")
print("My name is", my_name, ", and I am", my_age, "years old.")
print("Your name is", your_name, ", and you are", your_age, ".")
print("Thank you for buying my book,", your_name, "!")

Figure 3-1. A program with four variables and the output it creates

Copyright @ Sue’s academy 18


Python for kids | Sue’s Academy

Numbers and Math in Python


The computer is great at remembering values. We can use the same variable hundreds or
thousands of times in the same program, and the computer will always give us the right value as
long as we’ve programmed it correctly. Computers are also great at performing calculations
(addition, subtraction, and so on). Your computer is able to perform over one billion
(1,000,000,000, or a thousand million) calculations every second! That’s much faster than we can
compute numbers in our heads; although we’re still better than computers at some tasks, fast math
is a contest the computer will win every time. Python gives you access to that mathematical
computing power with two main types of numbers, and it also lets you use a whole set of symbols
to do math with those numbers, from + to - and beyond

Python Numbers
The two primary types of numbers in Python are called integers (whole numbers, including
negatives, like 7, -9, or 0) and floating-point numbers (numbers with decimals, like 1.0, 2.5,
0.999, or 3.14159265).

Python Operators
The math symbols like + (plus) and - (minus) are called operators because they operate, or
perform calculations, on the numbers in our equation. When we say “4 + 2” aloud or enter it on our
calculator, we want to perform addition on the numbers 4 and 2 to get their sum, 6.
Python uses most of the same operators that you would use in a math class, including +, -,
and parentheses, (), as shown in Table 3-1. However, some operators are different from what you
may have used in school, like the multiplication operator (the asterisk, *, instead of ×) and the
division operator (the forward slash, /, instead of ÷). We’ll get to know these operators better in
this section.

Table 3-1. Basic Math Operators in Python

Copyright @ Sue’s academy 19


Python for kids | Sue’s Academy

Doing Math in the Python Shell

Try typing some of the examples listed in Table 3-1 and see what Python says; Figure 3-2
shows some sample output. Feel free to try your own math problems as well.

Figure 3-2. Type the example math problems (expressions) from Table 3-1, and Python
gives the answers!

Copyright @ Sue’s academy 20


Python for kids | Sue’s Academy

Syntax Errors: What Did You Say?


While we’re typing in the Python shell, we have a chance to learn about syntax errors.
Whenever Python, or any programming language, can’t understand the command you typed, it
may respond with a message like "Syntax Error". This means there was a problem with the way
you asked the computer to do something, or your syntax. Syntax is the set of rules we follow in
building sentences or statements in a language.

Take a look at Figure 3-3 to see some examples of syntax errors, followed by the
expressions stated in a way that Python can understand.

Figure 3-3. Learning to speak Python’s language

Copyright @ Sue’s academy 21


Python for kids | Sue’s Academy

Variables in the Python Shell


As we’ve discussed, the Python shell gives us direct access to the programming power of
Python without having to write entire stand-alone programs. We can even use variables, like x and
my_age, when we’re typing in the Python shell; we just have to assign them values, as you learned
to do in this chapter’s opening example. If you type x = 5 at the command prompt (>>>), Python
will store the value 5 in memory as the variable x and will remember it until you tell Python to
change the value (for example, by entering x = 9 to give x a new value of 9). See the examples in
the Python shell in Figure 3-4.

Figure 3-4. Python remembers our variable’s value for as long as we want.

Copyright @ Sue’s academy 22


Python for kids | Sue’s Academy

Programming with Operators: A Pizza Calculator

Speaking of pizza, now let’s imagine you own a pizzeria.


Let’s write a small program to figure out the total cost of a simple pizza order, including
sales tax. Say we’re ordering one or more pizzas that all cost the same, and we’re ordering in
Atlanta, Georgia, in the United States. There’s a sales tax that’s not included in the menu price but
is added at the end of the purchase. The rate is 8 percent, meaning that for every dollar we pay for
the pizza, we must also pay eight cents in sales tax. We could model this program in words as
follows:
1. Ask the person how many pizzas they want.
2. Ask for the menu cost of each pizza.
3. Calculate the total cost of the pizzas as our subtotal.
4. Calculate the sales tax owed, at 8 percent of the subtotal.
5. Add the sales tax to the subtotal for the final total.
6. Show the user the total amount due, including tax.

Type this into a new window and save it as AtlantaPizza.py.


AtlantaPizza.py

# AtlantaPizza.py - a simple pizza cost calculator


# Ask the person how many pizzas they want, get the number with eval()
number_of_pizzas = eval(input("How many pizzas do you want? "))
# Ask for the menu cost of each pizza
cost_per_pizza = eval(input("How much does each pizza cost? "))
# Calculate the total cost of the pizzas as our subtotal
subtotal = number_of_pizzas * cost_per_pizza
# Calculate the sales tax owed, at 8% of the subtotal
tax_rate = 0.08 # Store 8% as the decimal value 0.08
sales_tax = subtotal * tax_rate # Add the sales tax to the subtotal for the final total
total = subtotal + sales_tax # Show the user the total amount due, including tax
print("The total cost is $",total)
print("This includes $", subtotal, "for the pizza and")
print("$", sales_tax, "in sales tax.")

Copyright @ Sue’s academy 23


Python for kids | Sue’s Academy

Figure 3-5 shows some sample output.

Figure 3-5. A sample run of our AtlantaPizza.py pizza calculator program

Strings: The Real Characters in Python


Strings are what we call text, or keyboard characters, in a programming language; they
are groups (or “strings”) of letters, numbers, and symbols.
SayMyName.py
# SayMyName.py - prints a screen full of the user's name
# Ask the user for their name
name = input("What is your name? ")
# Print their name 100 times
for x in range(100):
# Print their name followed by a space, not a new line
print(name, end = " ")

print(name, end = " rules! ")

Figure 3-6. Python prints a screen full of my name when I run SayMyName.py.

Copyright @ Sue’s academy 24


Python for kids | Sue’s Academy

Improving Our Color Spiral With Strings


Strings are so popular that even turtle graphics in Python have functions for taking strings
as input and writing them to the screen.
The function to ask a user for a string, or text, in the Turtle library is turtle.textinput(); this
opens a pop-up window asking the user for text input and lets us store that as a string value.
Figure 3-7 shows the nice graphical window that Turtle pops up for us when we use
turtle.textinput("Enter your name", "What is your name?"). There are two arguments in
Turtle’s textinput() function. The first argument, "Enter your name", is the window title for the
pop-up window. The second argument, "What is your name?", is the prompt that asks the user for
the information we want.

Type this into a new window and save it as SpiralMyName.py.

SpiralMyName.py
# SpiralMyName.py - prints a colorful spiral of the user's name import turtle
# Set up turtle graphics
t = turtle.Pen()
turtle.bgcolor("black")
colors = ["red", "yellow", "blue", "green"]
# Ask the user's name using turtle's textinput pop-up window
your_name = turtle.textinput("Enter your name", "What is your name?")
# Draw a spiral of the name on the screen, written 100 times
for x in range(100):
t.pencolor(colors[x%4]) # Rotate through the four colors
t.penup() # Don't draw the regular spiral lines
t.forward(x*4) # Just move the turtle on the screen
t.pendown()
# Write the user's name, bigger each time
t.write(your_name, font = ("Arial", int( (x + 4) / 4), "bold") )
t.left(92) # Turn left, just as in our other spirals

Copyright @ Sue’s academy 25


Python for kids | Sue’s Academy

The final result is a lovely spiral; my son Max ran the one shown in Figure 3-8.

Figure 3-8. A colorful text spiral

Lists: Keeping It All Together


In addition to strings and number values, variables can also contain lists. A list is a group of
values, separated by commas, between square brackets, [].
Type the following code into a new window and save it as ColorSpiralInput.py.

ColorSpiralInput.py
import turtle # Set up turtle graphics
t = turtle.Pen()
turtle.bgcolor("black") # Set up a list of any 8 valid Python color names
colors = ["red", "yellow", "blue", "green", "orange", "purple", "white", "gray"]
# Ask the user for the number of sides, between 1 and 8, with a default of 4
sides = int (turtle.numinput("Number of sides", "How many sides do you want (1-8)?", 4,
1, 8))
# the turtle.textinput() function asked the user for a string
# Draw a colorful spiral with the user-specified number of sides
for x in range(360):
t.pencolor(colors[x % sides]) # Only use the right number of colors
t.forward(x * 3 / sides + x) # Change the size to match number of sides
t.left(360 / sides + 1) # Turn 360 degrees / number of sides, plus 1
t.width(x * sides / 200) # Make the pen larger as it goes outward

Copyright @ Sue’s academy 26


Python for kids | Sue’s Academy

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’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.
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

Copyright @ Sue’s academy 27


Python for kids | Sue’s Academy

Figure 3-10. Python tackles your math homework.

PROGRAMMING CHALLENGES
To practice what you’ve learned in this chapter, try these challenges.

#1: CIRCULAR SPIRALS


Look back at the ColorCircleSpiral.py program in Chapter 2 (ColorCircleSpiral.py) that
drew circles instead of lines on each side of the spiral. Run that example again and see if you can
determine which lines of code you’d need to add to and delete from the ColorSpiralInput.py
program (ColorSpiralInput.py) to be able to draw circular spirals with any number of sides
between one and eight. Once you get it working, save the new program as CircleSpiralInput.py.

#2: CUSTOM NAME SPIRALS


Wouldn’t it be cool to ask the user how many sides their spiral should have, ask for their
name, and then draw a spiral that writes their name in the correct number of spiral sides and
colors? See if you can figure out which parts of SpiralMyName.py (SpiralMyName.py) to
incorporate into ColorSpiralInput.py (ColorSpiralInput.py) to create this new, impressive design.
When you get it right (or come up with something even cooler), save the new program as
ColorMeSpiralled.py.

Copyright @ Sue’s academy 28

You might also like