Fun Python For Kids
Fun Python For Kids
Notes from a class held online between April - May 2020 with students
age 10-12
Getting Ready
First, we will create a place on the computer where we will work on our programs.
1. Open a browser.
2. Go to drive.google.com. Login into your Google account
3. On the left side of the browser, go to New / Folder. Create a new folder
<YourName>FunCode. This will be your place to keep all your programs for this class.
4. Share this folder with your teacher: in the upper right corner, click on Share. Then when
asked for an email address, enter <email-address-removed>.
5. Double click to go inside the folder <YourName>FunCode
Next, we want to make sure we have Google Colaboratory ready to go. Google Colaboratory is
a program made available by Google, who lets us work on programs “in the cloud.” That means
we will write and run our programs on Google’s computers. How cool is that! Can you imagine
that? Your awesome programs sitting right next to other cool programs, such as the ones that
let you search on Google?
6. Go to New / More / + Connect more apps. Search for Colaboratory. Click Install
7. You should be ready to write your first program using Colab!
1. Go to drive.google.com
Go into your <YourName>FunCode folder. It is important that you keep everything in the
same folder, so I can help you as needed.
2. On the left side of the browser, go to New / More / Google Colaboratory. In the upper left
corner, click on Untitled0 and change to MathWithPython. Keep the ipynb extension --
remember this says this is a Python notebook.
3. Now write
number1 = 5
number2 = 3
print("The product of the two numbers is “,number1*number2)
3.1. Try running this program. Is the result correct?
Now try changing the numbers to something much larger (e.g., Zara tried a number with
20 different digits. Can you beat that? :). Run again…
3.2 Try changing the program so it adds the numbers.
Extra: If you want to try something else, change the program above so that you do the sum of
the numbers (and make sure you change your message too)
Assignment.
Create a new piece of code inside your MathWithPython program (remember you go in the
upper left corner, and click on +Code). Write a program that does the following:
- Greets the user (with something like “Hello”, “Hi”, “What’s up”)
- Tells the user you will help them do some math
- Ask the users for two numbers
- Prints the sum, product, subtraction, and division of the two numbers. (consider making it
clear, by telling the user e.g., “The product is”)
And of course, feel free to try programming other things. The more you practice, the better you
will get!
Lesson 2: If-then-else
What we will learn in this class:
- Quick review: input/output, variables
- Learn about formatting your code
- Learn about conditionals: if-then-else
- Learn about libraries: the random library
- Putting it all together: compare two numbers
- Assignment 2: Write our first game: a number game!
Review program input/output.
How do we “send” something to the output? In other words, what function do we use to write
something for the user?
How about reading from the input? In other words, what function do we use to “capture” what
the user is telling us?
Why do we use quotes in any message we include in these functions?
Bonus question: when we write a program, who are we? In the imagine below -- where are “we”
as programmers?
Review variables.
What is a variable?
Why do we need variables?
When we read a variable from the user, what type is that variable? A number? A string?
How do we convert a variable to make it an integer, so we can do math operations?
Bonus question: How do we convert a variable to make it a real number, so we can do math
operations with decimals?
First, we need to pay attention to how we write and spell things. Computers are very … exact,
they always want to hear the same thing they are used to. If we make a tiny change, they don’t
like that. For instance, try changing one of your previous programs to use Print instead of
print. Does it work? Most likely not. Or, try not including the quotes in print("Hello
world"),and it will not work anymore. Luckily, for most of these mistakes, whenever we make
them (yes, it does happen all the time that we forget a quote), the computer will give us an error
message so we know we have to fix it.
Second, in this class, we will start seeing that even the spaces we use can make a difference.
Python uses indentation to indicate that a certain block of code goes together. Here is a piece of
code that tells us that the two print statements should be executed together ‘as a block’.
if(5 > 1):
print("Hi")
print("What’s up")
If-then-else.
So far, everything we wrote in our program was executed when we ran the program. (that is, the
computer “ran” each command, one by one). But what if we want to execute a command only in
certain situations? For instance, for your first assignment, I asked you to do the division of two
numbers. What if the divisor was 0? Or, we could write a program to talk to a user (we will do
that soon!), but we want to say certain things only if the user said “Yes” To do this, we use an
“if-then-else” command.
if-then-else syntax
if(condition):
<do-this-if-condition-true>
else:
<do-this-if-condition-false>
x = 10
if( x / 2 > 6):
print("It’s sunny today")
else:
print("It’s rainy today")
What will this piece of code do?
x = 10
if( x / 2 > 6):
print("It’s sunny today")
Important! Notice the indentation (empty spaces) before print. This tells the computer the print
statements are to be executed only when the condition evaluates to true. (the same goes for
“else”: it requires a block of code that has indentation)
1. Go to drive.google.com
Go into your <YourName>FunCode folder. It is important that you keep everything in the
same folder, so I can help you as needed.
2. On the left side of the browser, go to New / More / Google Colaboratory. In the upper left
corner, click on Untitled0 and change to NumberGame. Keep the ipynb extension --
remember this says this is a Python notebook.
3. Now let’s ask the user for two numbers as we have done before, and tell the user which
number is bigger.
x = input("Enter a number")
y = input("Now enter another number")
if(int(x) > int(y)):
print("The first number is larger")
else:
print("The second number is larger")
Question: why did we use int?
4. Try running your code. Try running again with other numbers. What happens if the two
numbers are equal?
Libraries.
Python has a LOT of commands (or functions - but we’ll talk about this later) that do interesting
things that are already implemented. That is, somebody else took the time to write them, and
now they are available for us to use. This is a very cool thing, because it means we can be
much more efficient in what we write, and we don’t have to re-write all those commands that
others have already spent time writing. The same will happen with code that we write, we can
make it available for others to use!
These commands are organized into libraries -- yes, pretty much like the books in a library. If we
want to have access to one of these libraries, so we can use the commands inside, we will have
to tell the computer we want access. We do that with the command import.
Let’s try using a library that is one of my favorites, because it lets us create random things. How
fun!
1. While you are in your NumberGame program, go to the upper left corner, and click on
+Code. This will let you create a new code piece.
2. Now let’s tell the computer we want to have access to the random library, and that we
want to create a random number. We do this with a command that is available in the
random library: While you are in your HelloWorld program, go to the upper left corner,
and click on +Code: random.randint(a,b)
This will write a random integer that is larger or equal to a, and smaller or equal to b.
3. Try this code
import random
print(random.randint(1,7))
When you run the code, what do you get? Do you all get the same number?
Try now changing the code so that you get a random integer between 50 and 100.
if(7>5):
print("Wow!")
else:
print("Hmm")
print("Hmm")
import random
print (random.randint(1,7))
print (random.random())
Which is all fine, except that it’s not that practical to keep naming variables, in particular when
they seem to serve the same purpose (like here, we have four different numbers), and even
more so when I have a lot of such variables. For example, what if I wanted to have 10 numbers?
Fortunately Python (and many other programming languages) have lists!
A list is a collection of items. It is very commonly used in Python, and it can be used to store
numbers, strings, a mix of numbers and strings, and even other lists!
What can we do with lists? Loooots of things! I don’t even know them all :) (As it turns out, we
often have to search up for how to do things in programming, and we often discover new things
we didn’t know!)
myList = [3,245,4]
print(myList)
print(myList[0])
print(myList[2])
myList.sort()
print(myList)
myList.reverse()
print(myList)
myList.append(25)
print(myList)
myList.extend([3,4])
print(myList)
print(myList[0:2])
We can even get a random element from a list!
import random
nouns = ["apple", "pear", "sardines"]
print(random.choice(nouns))
Important! Operations on lists are done in place, which means that they are applied directly on
the list. For instance, if I do
myList = [1,3,9,2,0]
myList.sort()
1. Go to drive.google.com
Go into your <YourName>FunCode folder. It is important that you keep everything in the
same folder, so I can help you as needed.
2. On the left side of the browser, go to New / More / Google Colaboratory. In the upper left
corner, click on Untitled0 and change to CoolLists. Keep the ipynb extension --
remember this says this is a Python notebook.
3. Let’s create a list of words.
nouns = ["sun", "dog", "water", "fish", "dish"]
4. Try printing the first item. How about the third item?
5. Try sorting the list.
6. Now let’s create more lists of words. Add a list of adjectives, and a list of verbs. I
suggest you include 5 words in each list.
Hint: use only singular nouns; use only verbs third person singular that can have a direct
object
7. Now let’s try writing a sentence. , using random words selected from your lists.
For instance, I can write a random adjective-noun pair like this
print("The",random.choice(adjectives)," ",random.choice(nouns))
Spend a few minutes to create the three lists of words, and write a sentence that follows
the pattern
The <adjective> <noun> <verb> the <adjective> <noun>
Yay! With just a few lines of code, you can now generate …. how many?? …. sentences!
(hint: a lot!)
Here is my solution:
import random
nouns = ["sun", "water", "fish", "cat", "grass"]
adjectives = ["pretty","ugly","red","smelly","fun"]
verbs = ["reads","eats","smells","drinks","grabs"]
print("The",random.choice(adjectives),random.choice(nouns),random.ch
oice(verbs),"the",random.choice(adjectives),random.choice(nouns))
1. Go to drive.google.com
Go into your <YourName>FunCode folder. It is important that you keep everything in the
same folder, so I can help you as needed.
2. Open the CoolLists program that you created during class. Add a new piece of code
(remember you go in the upper left corner, and click on +Code). Write a program that
does the following:
- Creates a list of persons you know - add at least five names
- Creates a list of adjectives - add at least five adjectives
- Creates a list of nouns (singular nouns) - add at least five nouns
- Creates a list of verbs (this time, use the regular verb forms, like “eat”, “drink”) -
add at least five verbs
- Now write a MadLib story!
You can choose your own, or here is a suggestion for a MadLib to use.
Instead of each <word>, choose at random from the corresponding list. Have fun!
Review questions:
How do we declare lists?
How do we write a list with 4 elements?
How do we access the second element in a list?
myList = [3,10,4,12]
print(myList[0])
print(myList[2])
----
myList = [3,10,4,12]
myList.sort()
print(myList)
print(myList[0])
----
myList = [3,10,4,12]
myList.append(25)
myList.append([3,4])
print(myList)
----
myList = [3,10,4,12]
print(myList[0:2])
Trivia: Who was the first programmer ever?
Answer: Ada Lovelace! Read more about her here See below a picture of her, and the very first
program, written by her.
While Loops.
We’ve done a lot of cool things so far, but a lot of the things we have done were happening just
once. And to be fair, while it’s really cool that we now know how to write Python programs, we
could have done all those math operations and if-then-else tests ourselves.
The big BIG power of computer programming comes from the fact that we can write programs
that repeat a certain thing (math operation, word counting, anything you can think of) a million
times, a billion times, a GAZILLION times, and do it quickly, much much faster than we as
humans could do it.
How do loops work? Simply, these are statements that repeat what follows many times.
Let’s look at while loops. (we’ll look at for loops next time)
while(<condition>):
do-something
The way we read this is: “as long as the <condition> is true, we do-something.”
(you can also think of while-loops as an if-then-statement that is repeated many times)
Let’s try to write a program that prints all the numbers from 1 to 10 (excluding 10)
number = 1
while(number < 10):
print (number," ")
number = number + 1
Assignment 4. Write a program that adds all the numbers that a user provides, until the user
says “done”
1. Go to drive.google.com
Go into your <YourName>FunCode f older. It is important that you keep everything in the
same folder, so I can help you as needed.
2. Open the LoopsLoopsLoops program that you created during class. Add a new piece of
code (remember you go in the upper left corner, and click on +Code). Write a program
that does the following:
- Tells the user you will help them add as many numbers as they want
- Tells the user to say “done” when they are done providing numbers
- Includes a while loop that checks if the user said “done”
- Asks the user for numbers (inside the while loop), and adds them up
- Stops when the user entered “done”
- At the end, prints the sum of all the numbers entered by the user
Here is a fragment:
import random
people = ["dad","mom","brother","sister","dog"]
adjectives = ["heavy", "light", "thin", "thick", "soft"]
noun = ["stick", "banana", "fire", "window", "tree"]
verb = ["smile", "burn", "float", "walk", "laugh"]
#MadLib story
Output:
- Yesterday dog and I went to the park. On our way to the thin park, we saw a thick
tree on a bike. We also saw big soft balloons tied to a banana . Once we got to
the light park, it started to laugh and laugh . We burn all the way home.
Tomorrow we will try to go to the thick park again, hope it does not smile .
Review questions:
Why do we need loops?
How does a while loop work?
How many times does a while loop repeat? (or, when does a loop stop)
What will be the output of this program?
a = 1
while(a < 5):
print ("Yay! ")
a = a + 1
Why do we write?
a = a + 1
a = 1
while(a < 5):
print ("Yay! ")
ENIAC (Electronic Numerical Integrator and Computer) was the first electronic general-purpose
digital computer. Created in 1946. The people who operated the ENIAC were called
“computers.” Over time, the name ENIAC was lost, instead we use “computer” to refer to these
computing machines.
For Loops.
We’ve learned about while loops so far, let’s see another type of loop. For loops are very
similar, except they loop through the elements of a list. They are as powerful as while loops, as
they help us do a LOT of repetition. Why is repetition useful in programming?
for x in list:
do-something
The way we read this is: “do-something for every item x in the list”
Here’s an example:
If we want to repeat something a certain number of times, instead of writing down all the
elements in a list, we can give a range
Now let’s try to add all the numbers to 10000, as we’ve done last time, but now let’s do it with for
loops:
1. Go to drive.google.com
Go into your <YourName>FunCode f older. It is important that you keep everything in the
same folder, so I can help you as needed.
2. On the left side of the browser, go to New / More / Google Colaboratory. In the upper left
corner, click on Untitled0 and change to MoreLoops. Keep the ipynb extension --
remember this says this is a Python notebook.
3. Remember from last time. First, we have to say our sum is 0 (we haven’t added anything
so far!)
sum = 0
4. Now let’s make this repeat for all the numbers up to 10000 (and also print the result)
sum = 0
for number in range(10000):
sum = sum + number
print (sum)
5. Remember the while loop? Let’s put our while-loop solution here, so we can look at them
side by side
sum = 0
number = 1
while(number < 10000):
sum = sum + number
number = number + 1
print (sum)
Let’s try another for loop, this time we can loop through all the words in a list. And do it twice!
6. Add a new piece of code (remember you go in the upper left corner, and click on
+Code).
7. Let’s do a small piece of the MadLib, but now we want many MadLibs!
import random
animals = ["cat","dog","spooky bird"]
moods = ["happy","sad","smelly”]
8. How about if we want to generate ALL the MadLibs we can for the lists above?
For each animal, we want to go through all the moods.
How do we do that? Nested loops!
Assignment 5. Program a Rock, Paper, Scissors game. The game will run six times, and at the
end you will write the score: how many times the computer won, how many times the user won.
1. Go to drive.google.com
Go into your <YourName>FunCode f older. It is important that you keep everything in the
same folder, so I can help you as needed.
2. Open the MoreLoops program that you created during class. Add a new piece of code
(remember you go in the upper left corner, and click on +Code). Write a program that
does the following:
- Tells the user a fun introductory message, and explains them the rules of Rock,
Paper, Scissors
- Tells them they will play six times, and the player who wins more rounds is the
winner.
- Write a for loop that repeat six times
- Inside the for loop:
- The computer picks randomly one of [“R”, “P”, “S”]
- Asks the user to make a choice, reminds them to use R for Rock, P for
Paper, S for Scissors
- Decide who wins (remember if-then-else)
- Keep track of how many times the user won and the computer won
- Outside the for loop, at the end, reports the score, and congratulates the user if
they won.
- Bonus! You can repeat the six-round game as many times as the user wants.
Review questions:
How does a for loop work?
How many times does a for loop repeat? (or, when does a loop stop)
Bonus trivia question: how do we make numbers using these symbols? How about letters?
Humans Computers
0 0
1 1
2 10
3 11
4 100
5 101
6 110
7 111
….
Bonus trivia question: If your fingers were computer bits, where you could either have your
finger up (1) or down (0), up to what number can you count using 10 fingers?
Answer: 1023!
First off, you will need to make sure you have the library. The way we install a library is with the
command pip
1. Go to drive.google.com
Go into your <YourName>FunCode f older. It is important that you keep everything in the
same folder, so I can help you as needed.
2. On the left side of the browser, go to New / More / Google Colaboratory. In the upper left
corner, click on Untitled0 and change to DrawingTurtle. Keep the ipynb extension --
remember this says this is a Python notebook.
3. Write and run
!pip3 install ColabTurtle
from ColabTurtle.Turtle import *
4. Now the ColabTurtle library is available for you to use and do cool drawings
There are many things you can do. Here are some commands you can try.
Get a new pen (ie, initialize a new turtle). Set the speed of drawing to 10 (you can set it to
anything you want)
initializeTurtle()
Note: valid colors are: 'white', 'yellow', 'orange', 'red', 'green', 'blue',
'purple', 'grey', 'black'
Functions.
Oftentimes, we write code that we then need again at a later time. In programming, a nice way
to organize our code is through the use of functions, which allow us to write something once,
and then reuse many times.
To see what functions can do for us, and also to see an example, assume we want to draw the
nice red star we drew earlier three times, at different coordinates.
It works, and we have three nice stars. But this is not very efficient, because I just keep writing
the same code many times. What if I want to draw 100 stars? Or, what if I decide I want to
change the number of units I go forward from 250 to 150? I need to make that correction many
times.
Another way to do it is by using functions. We define a function -- let’s call it star -- and then we
just use that function whenever we want a star
#Notice how I use x and y as variables - and I can set them to
#anything I want when I call the function!
star(300,300)
star(500,400)
star(200,600)
Let’s try to write a function that does a square:
7. Add a new piece of code (use +Code in the upper left corner)
8. Define a function called square, which receives as input the coordinate, and the length of
one side
bgcolor('white')def square(x, y, side):
penup()
goto(x, y)
pendown()
for i in range(0,4):
forward(side)
left(90)
width(1)
Assignment 6. Make a cool drawing to impress your parents and your teacher. The only
requirements are that you use at least one loop, and at least one function. For the rest, the sky's
the limit :)
import random
moves = ["R","P","S"]
print("Hello, we are now playing a few rounds of rock paper scissors. The
rules are simple, rock beats scissors, scissors beats paper, and paper
beats rock")
print("The player who won more rounds wins")
Player_score = 0
Computer_score = 0
Computer = random.choice(moves)
if(Player == Computer):
print("It's a tie")
if(Player == "S"):
if(Computer == "R"):
Computer_score = Computer_score + 1
print("Computer won")
elif(Computer == "P"):
Player_score = Player_score + 1
print("You won")
if(Player == "P"):
if(Computer == "S"):
Computer_score = Computer_score + 1
print("Computer won")
elif(Computer == "R"):
Player_score = Player_score + 1
print("You won")
if(Player == "R"):
if(Computer == "P"):
Computer_score = Computer_score + 1
print("Computer won")
elif(Computer == "S"):
Player_score = Player_score + 1
print("You won")
Review questions:
Why do we use functions?
What does a function do?
What will be the output of this program?
def addNumbers(a,b):
return (a+b)
print(addNumbers(3,7))
def isSad(word):
if word in ["sad","terrible","annoyed"]:
return 1
else:
return 0
PROJECTS!!
What project will you work on?
Project ideas:
● interact with user to get input on what drawing to do. Make a drawing based on user
input (eg, forest, beach, different colors, etc.)
● “guess the animal” game by asking user to think of an animal, then the computer will ask
questions (“does it have stripes?”, “is it big?”, etc.) Maybe try for all animals.
● “guess the number” game where the user thinks of a number, then the computer tries to
guess it by asking questions / making statements
● hangman, where the computer thinks of a word, then the user tries to guess it.
● animation of the rocket launch
● a function to make your own flag
● riddle game with several riddles that the computer will ask the user
It’s quite easy! We simply indicate where we want to get our information from, and then we store
that information in some variables so we can process it inside our program.
I will tell you how to read/write from files on your computers, but we are not going to use that
with the Colab environment (remember, with Colab, our code is “in the cloud”, on the Google
computers, and accessing the files on our computers requires a few extra steps we will not
cover here). Nonetheless, here are the main steps to read/write from a file.
Read:
file = open("myfile.txt","r")
lines = file.readlines()
Now in lines we have a list with all the lines in my file! So I can print them out:
for line in lines:
print (line)
Write:
file = open("myfile.txt","w")
file.write("This is a line")
file.write("This is another line")
file.close()
How about reading from a file that is already online -- like a webpage?
For instance, here is one file online
http://www.gutenberg.org/files/236/236-0.txt
We can read from an URL with the help of a library called BeautifulSoup
import bs4
import requests
URL = "http://www.gutenberg.org/files/236/236-0.txt"
book = requests.get(URL, {}).text
Now in the variable book we have the entire content of a book, from that URL! You can try
reading other pages that you like, and using them in your programs to do all sorts of interesting
things.
print (len(words))
print (words.count(“Mowgli”))
4. Try also this alternative of splitting a book into words, which separates words based on
space as well as punctuation
import bs4
import requests
import re
URL = "http://www.gutenberg.org/files/236/236-0.txt"
book = requests.get(URL, {}).text
print(len(words))
words.count("Mowgli")
Assignment 7.
● Write a first version of your project. Save it in your <YourName>FunCode f older.
● [Optional] Try a few more things when reading a webpage. For instance, you can try
counting all the words in the file. Or counting all the words that differ from
[“the”,”of”,”a”,”an”,”with”] . Or finding the most frequent words on a webpage.
def tree(branchLen):
if branchLen > 2:
forward(branchLen)
right(20)
tree(branchLen-20)
left(40)
tree(branchLen-20)
right(20)
backward(branchLen)
Note how the function tree calls the function tree? This is called recursivity - it is an important
concept in programming, as it allows you to solve very complicated problems in simple ways.
For instance here, we can think of a tree as being composed of multiple trees, which in turn are
composed of multiple trees, and so on. So even if the tree looks complicated, with lots and lots
of branches, it is actually just a few lines of code.
Quick review. Functions.
Review questions:
Why do we need to use files (documents) to read and write from our programs?
How do we read from a file?
Can we read from a webpage?
Or this one?
print (len(words)) #len means length
print (words.count(“today”))
Dictionaries.
We have seen different ways of storing data using Python. Can you name the ways in which we
have stored data so far?
There is another very convenient way of storing data which is a dictionary. As the name says,
you can think of it as a dictionary, in which each word is a “key” to a definition.
You see it has some similarities with the list, except that each item has two parts: the key (in this
example the word), and the value (in this example, the definition).
Can you spot another difference with respect to lists? (hint: remember what type brackets we
used when declaring a list?)
Or another one:
secretCode = {"a":"c","b":"d","c":"e"}
Here, we want to create a secret code, so we write a “map” between original characters and
secret encodings (see below for more)
Very much like a list, we can access elements in the dictionary. Recall that in a list we used an
“index” (position in the list) to access an element. Here, we can simply use the key of an item to
access it. For instance,
mydict = {"water":"a kind of liquid", "dog":"an animal with four legs",
"food":"something you can eat"}
print (mydict["dog"])
will print the definition I included for “dog” in the dictionary I defined earlier.
We can also loop through all the elements in a list using both the key and the value:
for attribute, value in person.items():
print(attribute," ",value)
will display all the entries in the person dictionaries.
We can add an entry from the dictionary, simply by creating a new key:
secretCode = {"a":"c","b":"d","c":"e"}
secretCode["d"] = "f"
Let’s try to write a program that does a Caesar cipher! This is a way of creating secret
messages, so that only you and the person who knows “the rule” (how you created the secret
message) can decipher. It’s a very simple idea, we basically replace each character in the
alphabet with another character some fixed number of positions down the alphabet.
1. Go to drive.google.com
Go into your <YourName>FunCode folder. It is important that you keep everything in the
same folder, so I can help you as needed.
2. On the left side of the browser, go to New / More / Google Colaboratory. In the upper left
corner, click on Untitled0 and change to Dictionary. Keep the ipynb extension --
remember this says this is a Python notebook.
3. Let’s use a dictionary to create a Caesar cipher
caesarCipher = {'A': 'D', 'C': 'F', 'B': 'E', 'E': 'H', 'D': 'G',
'G': 'J', 'F': 'I', 'I': 'L', 'H': 'K', 'K': 'N', 'J': 'M', 'M':
'P', 'L': 'O', 'O': 'R', 'N': 'Q', 'Q': 'T', 'P': 'S', 'S': 'V',
'R': 'U', 'U': 'X', 'T': 'W', 'W': 'Z', 'V': 'Y', 'Y': 'B', 'X':
'A', 'Z': 'C', 'a': 'd', 'c': 'f', 'b': 'e', 'e': 'h', 'd': 'g',
'g': 'j', 'f': 'i', 'i': 'l', 'h': 'k', 'k': 'n', 'j': 'm', 'm':
'p', 'l': 'o', 'o': 'r', 'n': 'q', 'q': 't', 'p': 's', 's': 'v',
'r': 'u', 'u': 'x', 't': 'w', 'w': 'z', 'v': 'y', 'y': 'b', 'x':
'a', 'z': 'c'}
What is the rule used in this cipher?
4. Let’s create a function that takes a string (a text) and a dictionary that includes a Caesar
cipher, and creates a secret message.
def encode(message,secretEncoding):
secretMessage = "" #the secret message is at first empty
Assignment 8.
● Finish your project! Please let me know if you would like to meet for 30 min during the
coming week so I can help you with your project.
● [Optional] Write a decoder for secret messages. Very much like the encoder, except that
it works in the reverse: it takes a secret message, and it tells you the original message.
Hint: you can “reverse” a Caesar cipher with one line, for instance:
reversedCaesarCipher = dict((v, k) for k, v in caesarCipher.items())
You now know the basics of computer programming in Python! You’ve learned some of the
most important concepts in programming: variables, lists, and dictionaries, conditionals, loops,
functions, and input/output. You have already seen how you can use what you learned for a lot
of cool projects, and there are sooo many other projects you can do with this newly acquired
knowledge. For instance, you could create a conversation system, or you could write a program
that generates Haiku poetry or cooking recipes, or you could develop a dice game or a card
game, or you could write a system that analyzes the online reviews of a product and determines
if people like or dislike the product. There are so many amazing things you can accomplish now
that you know that you can add all the numbers to a billion or count all the words in a book in a
matter of seconds.
There are of course many more things to learn. For instance, we haven’t addressed at all
concepts such as recursivity (when a function calls itself), or object oriented programming (when
we define objects that have certain properties and behaviors). We also talked only a little about
strategies to solve problems (algorithms).
There are many ways in which you can continue to learn. Here are a few you can try:
- Codecademy
- Datacamp for Python
- Several courses offered on Coursera
But the very best way to learn is to program! Pick a problem that you are motivated to solve,
and just get started. When you get stuck, ask around, look online, and you will find solutions.
And on the way to solving the problem, you will learn a lot! I am so excited to see what you will
accomplish next as brand-news computer programmers!