Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Computer Literacy: ST Louis School

Download as pdf or txt
Download as pdf or txt
You are on page 1of 53

ST LOUIS SCHOOL

COMPUTER LITERACY

Python programming
Name: ________________________
Class: ________________________
Number: ________________________
Table of Contents

Lesson 1 Coding using Python .................................................................................. 3


Lesson 2 Input and output ........................................................................................ 8
Lesson 3 Making Decisions ..................................................................................... 13
Lesson 4 Some text, some math and going loopy .................................................. 21
Lesson 5 While loop ................................................................................................ 24
Lesson 6 Simple games I ......................................................................................... 29
Lesson 7 Simple games II ........................................................................................ 31
Lesson 8 Loop & List ............................................................................................... 35
Lesson 9 Function ................................................................................................... 41
Lesson 10 Strings ...................................................................................................... 46
Lesson 11 A simple encryption python program ...................................................... 50

2
Lesson 1 Coding using Python

Coding is writing instructions for a computer to perform a task. A finished set of


instructions is known as a program. Computer programs control everything from
smartphones to space rockets.

What's a computer language?


Computer languages are like human languages, but with fewer words and very
precise rules about how to use them. There are many programming languages
currently used by coders around the world such as C/C++, Java, Pascal, Python etc.
Some are best in one situations, others in another.

What is Python?
Python is a text-based computer language which means it's made up of words,
numbers and symbols (such as * and =).

Why choose Python?


Python is one of the most popular computer languages and it's very concise – that
is, you don't need to type much in order to create programs that do a lot. Python is
a powerful, modern programming language used by many famous organisations:

⚫ Google makes extensive use of Python in its web search systems.


⚫ The popular YouTube video sharing service is largely written in Python.
⚫ The Dropbox storage service codes both its server and desktop client software
primarily in Python.
⚫ The widespread BitTorrent peer-to-peer file sharing system began its life as a
Python program.
⚫ Maya, a powerful integrated 3D modeling and animation system, provides a
Python scripting API.
⚫ JPMorgan and UBS apply Python to financial market forecasting.
⚫ NASA uses Python for scientific programming tasks.

3
Downloading Python (https://www.python.org/downloads/ )
Python comes in different numbers after the name. Please download and install
version 3 or above.

IDLE
IDLE is Python's Integrated Development and Learning Environment. You will start
programming in IDLE that helps you write, edit and save your code. IDLE is a special
text editor like Microsoft word and Notepad, except it understands Python and helps
you get your code right.

Which Window?
Python uses two main windows – the Shell window and the Code window.

Shell Window
The Shell window is used for running code. You can also use it to write and test small
pieces of code, but not save them. It is similar to REPL in mu editor. In the Shell
Window, you will see the command prompt (>>>)

4
Code Window
The Code Window is used for writing code. Long programs should always be written
in this window. It allows you to save and edit code. Use the "File" menu in the Shell
window and choose "New file" to open the Code Window.

The Code window starts off completely blank.

Hello World
It has been a tradition that your first program when learning a new language is
"Hello World". The aim is to try to make the computer say "hello" to the world. If you
want to find out how to write "Hello World" for other computer language, you may
visit https://en.wikibooks.org/wiki/Computer_Programming/Hello_world.

Trial 1
In the Shell Window, type the following after the >>> prompt and then press RETURN
key.
>>>print("Hello, world!")

If all is well, you should get something like this:

If you make a mistake in your code, you'll usually get a red error message. For
example, try to type Print("Hello, world!") after the >>> prompt. You will
get:

5
The red error message means you have typed something wrong (in the above
example, you type Print instead of print). This is called syntax error. Colons, brackets,
quotation marks, apostrophes, cases and spelling of Python words have to be just
right. The combination of spelling, punctuation and layout is called syntax.

We have the above syntax error because Python is case-___________________.

The Shell window is great for testing short pieces of code, but it won't let you save
anything.

Trial 2
In the Shell window, click on File (at the top) to open the File menu. Select "New File"
and a code window labelled "Untitled" will pop up, like this:

Type in the text below, just as you did before:


print("Hello, world!")

Then choose File and select "Save As", save your file in "d:\temp\lesson01.py"

6
To run the saved program, click on Run and select "Run Module" (Or just pressing
F5 function key), the Shell window should pop up and the words "Hello, world!"
should appear.

Practical Exercise
Write a program which produces the following output. Save your file as 3xyy.py
(where x is your class and yy is your class number).

Please replace "Chan Tai Man" with your real name.

7
Lesson 2 Input and output

To be useful, a program usually needs to communicate with the outside world by


obtaining input data from the user and displaying result data back to the user. This
lesson will introduce you to Python input and output.

Input and Output


Anything you tell a computer, whether by typing, moving a mouse or loading a disk,
counts as ________________. Anything the computer sends back, whether shown on
screen, printed out or burned onto a disk, is known as __________________.

You can use input() function to ask for input from a user.

Demo 1
Create the following program in Code window:

Save and run the program:

Type in your name and press ENTER, you will get:

8
name = input("Enter your name: ")

The input function returns what the user has typed. In the above example, your
name is now stored inside the variable, name.

Note: Certain types of code automatically appear in certain colours in Code window.
Variables are black, functions are purple, keywords are orange, error messages are
red, function definitions are blue and strings are green.

Demo 2
Create the following program in Code window:

Save and run the program:

int() tells the computer to treat the variable inside the brackets as an "integer" or
whole number. If you remove the int() function in the above program and run,
you should get an error message.

Trial 3
Create the following program in Code window:

9
Save and run the program:

In the above sample run, variable year stores "2000" which is a string. ("2000" is
not equal to 2000) The computer can't do the calculation without turning the input
into a number.

Integers and Floats


There are two types of numbers in coding: integers and floats. An integer is always
a whole number, such as 2. A float can be any number, including numbers with a
decimal point, such as 2.5 – you can think of the decimal point 'floating' between
the digits.

Learning Resources
1. Learn Python from SoloLearn
https://www.sololearn.com/Play/Python/hoc

2. Python Tutorial from w3schools.com


https://www.w3schools.com/python/default.asp
3. Learn Python from Hour of Code
https://craft.buzzcoder.com/?lesson=hoc

Useful Tools
1. Python Tutor
http://www.pythontutor.com
2. Repl>it
https://repl.it

10
Comment
Comments are descriptions of program statements or remarks which help people
understand how the program works. The text after a # is simply ignored as a human-
readable comment and is not considered part of the statement.

Exercise
Explain briefly why the following lines of code are incorrect.
(a) Print("Hello world!")
Ans: It is incorrect because ___________________________________________________

(b) print(Hello world!)


Ans: It is incorrect because ___________________________________________________

(c) print "Hello world!"


Ans: It is incorrect because ___________________________________________________

Practical Exercise
By modifying the given program, try to write a python program with the following
sample outputs (words in italics are input from user). Save your file as 3xyy.py (where
x is your class and yy is your class number).

Sample output 1:
What is your name? Peter
Year of birth? 2001
Peter , you are nearly 18 years old.

Sample output 2:
What is your name? John
Year of birth? 2003
John , you are nearly 16 years old.

11
[Given program]

# Please debug this program. There are THREE mistakes in this program.

name = input("What is your name? ")


year = input(Year of birth? )

# Hint: What is the data type of "year"?


age = 2019 - year
print(name + ", you are nearly", age)

12
Lesson 3 Making Decisions

To write a program that allows you to make decisions, the computer needs to react
differently to different answers. For this, you need conditions to compare pieces of
information.

What are conditions?


A condition is a bit of code that compares two pieces of information. Conditions use
operators to make comparisons. For example, the operator == checks if two pieces
of information are the same.

Open the Shell window and type this:


>>> age = 10
>>> age == 12

Press RETURN. You should see this on the next line:


False

The condition is False because age is set to 10, not 12. To a computer, a condition
can only ever be True or False. Try typing this into the Shell window, then press
RETURN:
>>> age = 10
>>> age == 10

This time, you should see True on the next line.


True

Another word for a condition is a Boolean expression. The True or False status of
a Boolean expression is known as _________________________________.

Comparative operators
There are symbols that the computer uses to compare two pieces of information.
== < <=
is equal to is less than or equal to
!= > >=
is greater than

13
if statement
One important conditional is known as if statement, which tests whether a
condition is True.

False

True
Boolean
statement 1 statement 2
expression

if (Boolean expression):
statement 1
statement 2

Here's a program showing an if statement in action…


Open a new file, then type this line of code:
user_reply = input("Do you like robots? (Type yes or no)")
if user_reply == "yes":
print("Beep boop!")

The Code window should automatically add an indent of four spaces at the start of
the next line after colon (:).

Python uses blank spaces known as indents to group lines of code together, so the
computer knows what to do next. Lines with the same indent run as a block, from
top to bottom. Where a line is indented, it means it belongs to the line above it.

Try to run the program:


If you type in "yes",

14
If you type in "no" (or anything else other than "yes"), the program won't respond.

Question: What is the program output if the user input "Yes"? _________________

else statement
The word else tells the computer which path to follow when the condition for if
isn't met.

statement 1b
False

True
Boolean
statement 1a statement 2
expression

if (Boolean expression):
statement 1a
else:
statement 1b
statement 2

Open the previous program and add these two lines below the final line:
else:
print("Well, robots don't like you either.")

The completed code should look like this:

15
Try to run the program and answer no to activate the else part of the code. An
else isn't very specific. It's like replying "none of above" to multiple-choice question.

elif statement
elif is short for "else-if". elif always comes after an if and activates when
conditions for the if have not been met. It also has its own condition and only runs
if that has been met. elif allows your program to have more branching paths, and
for each of those paths to unfold when the user gives a specific answer.

False
statement 1c

Boolean
expression 2
True

statement 1b
False

Boolean True
statement 1a statement 2
expression 1

if (Boolean expression 1):


statement 1a
elif (Boolean expression 2):
statement 1b
else:
statement 1c
statement 2

16
Try to add different options, the program becomes:

Try to run the program and give different inputs:

We may improve the above program as follows:

The above program will output "Invalid input!" if the user input other than
"yes", "no" or "maybe".

17
Sample output

Using Logical Operators (and or not)


We can use and and or to combine more than one comparison. If you use and,
both parts of the comparison must be true for the statement to be True. If you use
or, only one part needs to be true.

Demo 1:
>>> a = 3
>>> b = 4
>>> a > 2 and b < 3
False

Demo 2:
>>> a = 1
>>> b = 2
>>> a == b or a != b
True

18
By using logical operators, our program is able to handle more reasonable inputs:

Notice that the comparison can't be written as follows:


if user_reply == "yes" or "Yes":

Sample output:

Try to modify the program such that it can also handle "Y", "y" ,"N", "n" as input
correctly.

19
Exercise
Assume a = 15, b = 17.
Fill in the following table:

Expression Result
a == 15 True
b == 20
a == b
a != 3
b != a + 2
a > b
a + 2 >= b
b < 0
a + b >= 32
not(a == 2)
a == b or a != b
a == b and a != b
not ((a == 1) or (b >= 4))
not (a == 1) or (b >= 4)
not (a == 1) and not (b >= 4)
0 < a
0 < a <= 20
-1 < b < 10

20
Lesson 4 Some text, some math and going loopy

Escape sequences
Try opening IDLE in interactive mode and enter the code below:
>>> print("Q: What is SLS?\nA: St. Louis School")

If you have not pressed your RETURN key yet, to see what happens, do so now.
Q: What is SLS?
A: St. Louis School

You should have discovered \n has a special purpose. It is an example of an escape


sequence. Table below shows some more escape sequences.
Escape sequence What is does
\n creates a line return in a string of text
\t creates a TAB style indent in a string of text
\\ allows a backslash to appear in a string of text
\" allows a double quotation mark to be used in a string of text
\' allows a single quotation mark to be used in a string of text

Trial 1
Are you a bit confused about the last three escape sequences? If so, type in and run
the code below.
>>> print("Here are quotation marks: \" \' and here is a slash: \\")
Here are quotation marks: " ' and here is a slash: \

Trial 2
>>> print('I say "Hi", you say "Why?", and I say "I don\'t know"')
I say "Hi", you say "Why?", and I say "I don't know"
The above codes take advantage of the fact that you can choose whether to
surround strings in double quotation marks or single ones. Watch out though, you
will get a lot of syntax errors if you do not do this carefully.

Write down the outputs.


1. print("a\\b\\c") ________________
2. print("\\\\\\") ________________
3. print("\"\'\'\"") ________________
4. print("a\tc") ________________

21
Maths
Using Python as a calculator is easy, if you remember two things:
1. In Python, as in almost all programming languages, the multiplication symbol
is an asterisk *.
2. The division symbol is a forward slash /.
>>> 10 / 4
2.5
>>> 3 * 3
9

There is another way of division. If you use two forward slashes instead of one,
Python will produce an integer as an answer. An integer is a whole number (a
decimal such as 2.5 is called a float). You can now find the remainder, with another
mathematical operator called the modulus. This is represented by a % sign.
>>> 11 / 4
2.75
>>> 11 // 4
2
>>> 11 % 4
3

Some more mathematical operators


Operator Name Example Answer
* multiply 2 * 3 6
/ divide (normal) 20 / 8 2.5
// divide (integer) 20 // 8 2
% modulus 20 % 8 4
+ add 2 + 3 5
- subtract 7 – 3 4
** exponential 7**2 49

What is googol?
A googol is 10100. We can find out the value of googol in Python:
print(10**100)

How many digits? _______(How to count the number of digits correctly in Python?)

22
Combing text and maths
It is also possible to combine text (or strings) and numbers in the print() function.
The comma is used here as a separator between the text and the maths.
>>> print("111 divided by 4 = ", 111 / 4)
111 divided by 4 = 27.75
>>> print("11 divided by 4 = ", 11 / 4)
11 divided by 4 = 2.75

Trial 3
print("11 divided by 4 also equals: ", 11//4, "remainder: ", 11%4)

Output: _______________________________________________________________________

Going loopy
Computers are great at repetitive tasks. So are humans, but we get bored easily!
Computers are not only good at them, they are fast! Therefore we need to know
how to tell them to do repeats. To do this we use a while loop. This runs some code
while something is true and stops when it becomes false.

Imagine you were trying to write some code in a History lesson at school, when you
should be doing History. Your teacher might ask you to write fifty lines. Well, no
matter, Python can do that.

Try opening IDLE in interactive mode and then enter the code below.
>>> lines = 0
>>> while lines < 50:
print("I will not write code in history lesson.")
lines = lines + 1

Here is another solution to the same problem:


>>> print("I will not write code in history lesson.\n" * 50)

Although the first code is longer, a while loop is often more useful as it can do far
more complex tasks. For example, with a while loop you can ask a computer to
count to 100 or even larger!

23
Lesson 5 While loop

Python's while statement is the most general iteration construct in the language. In
simple terms, it repeatedly executes a block of statements as long as a test at the
top keeps evaluating to a true value.

Demo 1
number = 1
while number <= 10:
print(number)
number = number + 1

The above program will print from 1 to 10.

How do while loops work?


To start with we create a variable and assign a value to it. A variable is a space in the
computer's memory where we can store, for example, a string or an integer. We
create a variable by naming it.

In the code above, we assign 1 to the variable number. The next line of code while
number <= 10: says "while the variable called number is less than or equal to 10
do the following".

All of the code that is indented after the colon is to be repeatedly performed by the
computer. That is, it loops through these two lines of code until number is no longer
less than or equal to 10.

The last line of code number = number + 1 is in the loop. It keeps adding 1 to
number for each passage through the loop.

Demo 2
number = 1
sum = 0
while number <= 10:
sum = sum + number
number = number + 1
print(sum)

24
The above program calculates __________________________________________________

To have a better picture what is happening during the iteration, you may copy the
code above to http://www.pythontutor.com and watch the changes for each
iteration.

Demo 3
number = 1
sum = 1
while number <= 100:
sum = sum * number
number = number + 1
print(sum)

The above program calculates __________________________________________________


How many digits? _______

More to learn: https://en.wikipedia.org/wiki/Factorial

Infinite loops
Sometimes you may want a while loop to keep going for as long as the program is
running. This kind of loop is called an infinite loop.
while True:
ans = input("Are you bored? (y/n)")
if ans == "y":
print("How rude!")
break

25
To stop a loop from running, you can use the keyword break on the line after a
conditional, such as an if statement.

Exercise
See if you can re-write the following code in three different ways so that the program
still produces output which counts to a hundred.

number = 1
while number < 101:
print(number)
number = number + 1

In your new code, you are not allowed to use the less than operator <. Instead you
should use one of these comparative operators in each program: <= > !=

Method 1 (using <=):


number = 1
while ________________:
print(number)
number = number + 1

Method 2 (using >):


number = 1
while ________________:
print(number)
number = number + 1

Method 3 (using !=):


number = 1
while ________________:
print(number)
number = number + 1

26
Fill in the blanks
(a) By using Python program, find 1 + 2 + 3 + … + 10

____________
s = 0
while ( a <= 10 ):
s = s + a
a = a + 1
print(s)

(b) By using Python program, find 1 + 3 + 5 + … + 19


a = 1
________________
while (____________):
s = s + a
a = ________________
print(s)

Practical Exercise
By modifying the given program, try to write a python program with the following
sample outputs (words in italics are input from user). Save your file as 3xyy.py (where
x is your class and yy is your class number).

Sample output 1:
Enter a number: 100
1 + 2 + … + 100 = 5050

Sample output 2:
Enter a number: 1000
1 + 2 + … + 1000 = 500500

27
[Given program]

num = input("Enter a number: ")


s=
a=
while (a <= int(num)):
s=s+a
a=a+1
print("1 + 2 + .. + ", num, " = ")

28
Lesson 6 Simple games I

Guessing game
In this game, the computer will generate a random number from 1 to 20, which you
then try to guess.

Let's see the sample output first:

There are three parts in this program.


Part 1. Getting random number and user input
Part 2. Checking
Part 3. Print out message

Part 1
In Python, you need to import random module before you can generate a random
number in your program.
from random import *
num = randint(1,20)

29
Start by opening a new program and importing anything from random module.
Then use randint(a,b) to generate a random number from a to b inclusively.

Then ask the player to guess a number, and store the answer as a variable, called
guess. Since the return type of input() function is a string and so we need to
use int() function to convert the input to integer.
guess = int(input("Enter a number [1-20]: "))

Part 2
Now begin a while loop. (This will keep the game running until the player guesses
correctly.)
while guess != num:
if guess < num:
print("Too small...")
elif guess > num:
print("Too large...")
guess = int(input("Enter a number [1-20]: "))

The above program segment keeps the code running until the player guesses
correctly. If the input number is less than the computer's number, message "Too
small…" will appear. Similarly, if the input number is greater than the computer's
number, message "Too large…" will appear. Otherwise (that is: guessed correctly),
message "Bingo" will appear.

Part 3
The final line of the program is not indented, it's outside the while loop. Program
is as follows:

Save your file as 3xyy.py (where x is your class and yy is your class number).

30
Lesson 7 Simple games II

Global Defense Program


You'll be creating a global defense network. This asks the player to guess the
password for Earth's weapons – before it's too late.

Let's see how the program works:

There are three parts in this program.


Part 1. Program setting and display
Part 2. Checking
Part 3. Print out message

31
Part 1
Open a new file, create an aliens variable, saying how many aliens have invaded
in the first wave. Then add another variable password to store the password.
aliens = 2
password = "ALIENS"

Then tell the computer what to show on screen at the start.


print()
print("------------------------------------------------")
print("\tWelcome to the Global Defense Network")
print("------------------------------------------------")
print()

The print() function adds a blank line.

Next, store the user's input to variable guess.


guess = input("Enter password: ").upper()

To convert the string to UPPERCASE, we use upper() method. For example:


>>> "abc".upper()
'ABC'
>>> a = "sls"
>>> a.upper()
'SLS'
>>> a
'sls'

Part 2
Create a while loop. The loop will run as long as whatever you type in does not
match the password stored in the program.
while guess != password:
print("Incorrect Password!")

32
Start the aliens multiplying, using the exponent operator, **. Then display the
number of aliens with a print function.
aliens = aliens ** 2
print("There are", aliens, "aliens now on Earth. Try again!")

The next lines use an if statement with break to stop the while loop is the aliens
outnumber humans, ending the game.
if aliens > 7400000000:
break

The following lines will run as long as the aliens do not outnumber humans.
print("Password hint: the things that are attacking us.")
guess = input("Enter password: ").upper()

Part 3
Finish with an if/else statement, like this. They are outside the while loop. The if
code will run if the aliens go over 7.4 billion. The else code will run if you guess the
password correctly.
if aliens > 7400000000:
print("No....You lose!")
else:
print("You win!")

Save your file as 3xyy.py (where x is your class and yy is your class number).

33
Exercise
1. Study the following code:
a = 3
print(a ** a)

What is the output?


A. 9
B. 27
C. 81
D. 729

Ans: ______________

2. If we want to exit the while loop, which command should be used?


A. exit
B. return
C. break
D. continue

Ans: ______________

3. By using Python program, find 22 + 33 + 44 + 55 + … + 2020


a = 2
s = 0
while ________________
_________________
a = a + 1
print(s)

Ans: ______________________________________

34
Lesson 8 Loop & List

for loops

while loops only stop when something changes. If it doesn't change, they could go
on forever. With for loops, you can tell them exactly when to stop.

How many times?


Each time you use a for loop, you need to tell it how many times to repeat. To do
this you need a type of function called range().

Trial 1:
To create a very simple for loop using range(), open a new file, save it, and type
this:
for x in range(10):
print(x)

When you run the program, you will see:


0
1
2
3
4
5
6
7
8
9
>>>

When you use the range(n) function, it creates a list of numbers starts from 0 to n
– 1. In the above example, range(10) returns 0 to 9.

for x in range() tells the computer to run the code that follows once for each
entry in the list.

35
Trail 2:
for x in range(3,10):
print(x)

When you run the program, you will see:

When you use the range(a,b) function, it creates a list of numbers starts from a
to b – 1. In the above example, range(3,10) returns 3 to 9.

Trail 3:
for x in range(3,10,2):
print(x)

When you run the program, you will see:

When you use the range(a,b,c) function, it creates a list of numbers starts from
a to b – 1 with step c. By default, step is 1.

for x in range(3,10,3):
print(x)

When you run the program, you will see:

36
Using Lists

Python allows you to group lots of pieces of information together by making a list.
Lists are stored using variables.

Making a list
You create a list using square brackets, like this:
spacelist = ["rocket", "planet", "asteroid", "alien"]

To access the item in the list, you have to specify the index number of the item in
square bracket. For example,
>>> spacelist = ["rocket", "planet", "asteroid", "alien"]
>>> print(spacelist[1])
planet

The example above print out the second item in the list. Notice that the index
number starts from 0.

Displaying the whole list


You can use a for loop to display the whole list.
>>> for x in spacelist:
print(x)

rocket
planet
asteroid
alien
>>>

Replacing, deleting, adding


You can replace an item by entering a new one. Try:
spacelist[0] = "planet zarg"

The first item in the list should now be "planet zarg".


>>> spacelist
['planet zarg', 'planet', 'asteroid', 'alien']

37
To delete an item, you should use del command:
>>> spacelist
['planet zarg', 'planet', 'asteroid', 'alien']
>>> del spacelist[0]
>>> spacelist
['planet', 'asteroid', 'alien']

To delete a range of items in the list, you should use del(list[i:j]) command
to remove items from element i to element j – 1.
>>> spacelist
['planet', 'asteroid', 'alien', 'moon']
>>> del(spacelist[1:3])
>>> spacelist
['planet', 'moon']

The above del command remove elements from index 1 to 2 in the list.

You can add an item to the end of a list using append method.
>>> spacelist
['planet', 'asteroid', 'alien']
>>> spacelist.append("moon")
>>> spacelist
['planet', 'asteroid', 'alien', 'moon']

38
Table below summarizes the common List functions.
Function Description Example
del(a[i:j]) Deletes elements from the list >>> a = ['a','b','c']
from element i to element j-1 >>> del(a[1:2])
>>> a
['a', 'c']
a.append(x) Appends an element to the end >>> a = ['a','b','c']
of the list >>> a.append('d')
>>> a
['a', 'b', 'c', 'd']
a.count(x) Counts the occurrences of a >>> a = ['a','b','a']
particular element >>> a.count('a')
2
a.index(x) Returns the index position of the >>> a = ['a','b','c']
first occurrence of x in a >>> a.index('b')
1
a.insert(i,x) Inserts x at position I in the list >>> a = ['a','c']
>>> a.insert(1,'b')
>>> a
['a', 'b', 'c']
a.pop() Returns the last element of the >>> a = ['a','b','c']
list and removes it; an optional >>> a.pop(1)
parameter lets you specify 'b'
another index position at which
to remove >>> a
['a', 'c']
a.remove(x) Removes the element specified >>> a = ['a','b','c']
>>> a.remove('c')
>>> a
['a', 'b']
a.reverse() Reverses the list >>> a = ['a','b','c']
>>> a.reverse()
>>> a
['c', 'b', 'a']
a.sort() Sorts the list >>> a = ['a','c','b']
>>> a.sort()
>>> a
['a', 'b', 'c']

39
Exercise
1. Study the following code:
list1 = [1, 2, 3, 4, 5]
print(list1[0])

What is the output?


A. 0
B. 1
C. 2
D. [1, 2, 3, 4, 5]

Ans: ______________

2. Study the following code:


list1 = [0, 1, 2, 3, 4, 5]
print(len(list1))

What is the output?


A. 5
B. 6
C. len(list1)
D. [0, 1, 2, 3, 4, 5]

Ans: ______________

3. Study the following code:


list1 = [1, 2, 3, 4, 5, 6]
del list1[1]
print(list1)

What is the output?


A. [1, 2, 3, 4, 5, 6]
B. [2, 3, 4, 5, 6]
C. [1, 3, 4, 5, 6]
D. [1, 2, 3, 4, 5]

Ans: ______________

40
Lesson 9 Function

You're already familiar with the print(), input(), and len() functions from
previous lessons. Python provides several built-in functions like these, but you can
also write your own functions. A function is like a mini-program within a program.

More about built-in functions


max() The max() function selects the maximum value from the list you give
it. Similar to min() function which returns the minimum value.
>>> max([4,8,5,3])
8

sum() The sum() returns the sum of numbers


>>> a = [3,4,5,6]
>>> sum(a)
18

pow() The pow(x,n) return the value of xn


>>> pow(2,3)
8

round(x,y) The round(x,y) function round off the given number x to y decimal
places.
>>> round(123.456,1)
123.5

abs() The abs(x) returns the absolute value of x.


>>> abs(-5)
5
>>> abs(5)
5

What is the output?


>>> pow(max([1,2,3,4]),min([2,3,4,5]))
______________________________________

41
Making a function
You can define your own functions by using def statement.
def hello():
print("Hello world!")
print("Yea")

The first line is a def statement, which defines a function named hello(). The code
in the block that follows the def statement is the body of the function. This code is
executed when the function is called, not when the function is first defined.
>>> for i in range(3):
hello()

Hello world!
Yea!
Hello world!
Yea!
Hello world!
Yea!

def Statements with Parameters


When you call the print() or len() function, you pass in values, called arguments
in this context, by typing them between the parentheses. You can also define your
own functions that accept arguments.
>>> def hello(name):
print("Hello " + name)

>>> hello("Peter")
Hello Peter
>>> hello("John")
Hello John

The definition of the hello() function in the above code has a parameter called
name. A parameter is a variable that an argument is stored in when a function is
called. The first time the hello() function is called, it's with the argument "Peter".
The program execution enters the function, and the variable name is automatically
set to "Peter" which is what gets printed by the print() statement.

42
Return Values and return statements
When you call the len() function and pass it an argument such as "Hello", the
function call evaluates to the integer value 5, which is the length of the string you
passed it. In general, the value that a function call evaluates to is called the return
value of the function.

When creating a function using the def statement, you can specify what the return
value should be with a return statement. A return statement consists of the
following:
⚫ The return keyword
⚫ The value or expression that the function should return
>>> def isEven(num):
return num % 2 == 0

>>> isEven(3)
False
>>> isEven(8)
True

Complete the following:


>>> def isOdd(num):
____________________________

>>> isOdd(3)
True
>>> isOdd(4)
False

Sometimes we need to have more than one parameters in the function. For example,
we are going to define a function to return the area of a rectangle. The code is as
follows:
>>> def GetArea(width, height):
return width * height
>>> print("Area is", GetArea(3, 4))
>>> Area is 12

43
Exercise
1. Study the following code:
print(max([4,8,3,9,2,6]))

What is the output?


A. 4
B. 6
C. 9
D. 2
Ans: ______________

2. Study the following code:


def hello(n):
for i in range(n):
print("Hello")
hello(2)

How many "Hello" will be displayed?


A. 0
B. 1
C. 2
D. 3
Ans: ______________

Practical Exercise
By modifying the given program, try to write a python program with the following
sample outputs (words in italics are input from user). Save your file as 3xyy.py (where
x is your class and yy is your class number).

Sample output 1:
Please input an integer to check: 100
100 is not a prime number

Sample output 2:
Please input an integer to check: 23
23 is a prime number

44
[Given program]

def isPrime(num):
isP = True
for i in range(2, num):
if :
isP = False
break
return isP

a = int(input("Please input an integer to check: "))


if isPrime(a):
print(a, "is a prime number")
else:
print(a, "is a prime number")

45
Lesson 10 Strings

Coders use the word "string" for any data made up of a sequence of letters or other
characters. Words and sentences are stored as strings. Almost all programs use
strings at some point. Every character that you can type on your keyboard, and even
those you can't, can be stored in a string.

String basic
Strings can be put into variables. The strings must always have quotation marks at
the beginning and end. Either double quotation marks or single quotation marks
are fine.
>>> a = "abc"
>>> a == 'abc'
True

Length of a string
You can use a handy function, len(), to count the number of characters in a string
(including the spaces).
>>> a = "Louis"
>>> len(a)
5

Combining strings
Variables become really useful when you combine them to make new variables. If
you add two strings together, you can store the combination in a new variable.
>>> a = "St."
>>> b = "Louis"
>>> c = "School"
>>> d = a + b + c
>>> d
'St.LouisSchool'

You may assign multiple values to the corresponding variables at the same time:
>>> a, b, c = "St.", "Louis", "School"
>>> d = a + b + c
>>> d
'St.LouisSchool'

46
Accessing character(s) in a string
Each character in a string has an index, just like each entry in a list.
>>> a = "abcde"
>>> a[3]
'd'
>>> a = "abcde"
>>> a[2:4]
'cd'

What is the output of the following statements?


>>> a = "abcdefgh"
>>> a[1:5]
_____________________________________

Case conversion
We can use lower() and upper() methods to convert a string into lowercase or
UPPERCASE.
>>> a = "abc"
>>> a.upper()
'ABC'
>>> b = "ABC"
>>> b.lower()
'abc'
>>> "abcABC".upper()
_____________________________________
>>> "a1B2".lower().upper()
_____________________________________

Empty String
To create empty string, use a pair of quotation marks.
>>> a = ""
>>> a
''
>>> len(a)
0

47
Pattern matching
We can use startswith() and endswith() method to find if there is any
matching pattern.
>>> a = "Computer"
>>> a.startswith("com")
False
>>> a.endswith("er")
True

To return the position of a substring, we can use find() method, the function will
return -1 if not found.
>>> a = "sls179"
>>> a.find("179")
3
>>> a.find("SLS")
-1

Split
Sometimes it is useful to split the string into words. To do this, we use split()
method.
>>> a = input("Enter words: ")
Enter words: You jump? I don't jump.
>>> a.split()
['You', 'jump?', 'I', "don't", 'jump.']

Type conversion
Python contains a number of built-in functions for converting things of one type to
another.

int() can convert string to an integer.


>>> a = "23"
>>> int(a) + 1
24

48
str() converts a number to its string representation
>>> "sls" + 179
Traceback (most recent call last):
File "<pyshell#189>", line 1, in <module>
"sls" + 179
TypeError: can only concatenate str (not "int") to str
>>> "sls" + str(179)
'sls179'

Exercise
1. Study the following code:
school = "St Louis"
print(len(school))

What is the output?


A. 6
B. 7
C. 8
D. 10

Ans: ______________

2. Study the following code:


school = "Sls"
print(school.upper().lower())

What is the output?


A. Sls
B. sLS
C. sls
D. SLS

Ans: ______________

49
Lesson 11 A simple encryption python program

Caesar Cipher
A Caesar Cipher is an encryption method that takes the letters of the message you
want to send and "shifts" each letter along the alphabet a certain number of places.
The number of places moved along is known as the shift amount, or "key".

For example, if the first letter of the word you want to encrypt is C, and the key is 3,
the letter will become F.

The inner ring of the wheel above shows the alphabet shifted along 3 places.

Creating your cipher


Start a new file and create a variable alphabet that contains a string with the whole
list of alphabets.
alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"

Next, ask the user to enter a message and convert to upper case, then save to a
string variable stringToEncrypt.
stringToEncrypt = input("Enter message to encrypt: ").upper()

Next, ask the user to type in a number. This will be used as the key to encrypt their
message.
shiftAmount = int(input("Enter a number (1-25): "))

50
Now, create an empty string. This is where the encrypted message will be stored
when your program run.
encryptedString = ""

To encrypt your message, you need to shift each letter in turn. You can do this with
a for loop, using the index of each letter to work out.
for c in stringToEncrypt:
pos = alphabet.find(c)
newpos = (pos + shiftAmount) % 26
encryptedString = encryptedString + alphabet[newpos]

The find() function searches the "alphabet" variable for the first appearance of
the current character c, and returns its position.

The expression "(pos + shiftAmount) % 26" returns the shifted position. The modulus
operator % find out the remainder when (pos + shiftAmount) divides 26.

The last line in the program is not indented. This means it will run when the for loop
has finished.
print("Your encrypted message is ", encryptedString)

The complete program is as follows:

Sample output:

51
To have a better picture what is happening during the iteration, you may copy the
code above to http://www.pythontutor.com and watch the changes for each
iteration.

Practical Exercise 1
Save your file as 3xyy.py (where x is your class and yy is your class number).

Practical Exercise 2
By modifying the given program, try to write a python program with the following
sample outputs (words in italics are input from user). Save your file as 3xyy-2.py
(where x is your class and yy is your class number).

Sample output 1:
Enter your choice (Encrypt = 1, Decrypt = 2): 1
Enter the word: apple
Enter key: 6
Your encrypted message is GVVRK

Sample output 2:
Enter your choice (Encrypt = 1, Decrypt = 2): 2
Enter the word: gvvrk
Enter key: 6
Your encrypted message is APPLE

52
[Given program]

def encrypt(w, k):


s = ""
for c in w:
pos = alphabet.find(c)
newpos = (pos + k) % 26
s = s + alphabet[newpos]
print("Your encrypted message is", s)

def decrypt(w, k):


s = ""
for c in w:
pos = alphabet.find(c)
## STATEMENT 1
s = s + alphabet[newpos]
print("Your decrypted message is", s)

alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
choice = int(input("Enter your choice (Encrypt = 1, Decrypt = 2): "))
word = input("Enter the word: ").upper()
key = int(input("Enter key: "))
if choice == 1:
encrypt(word, key)
elif choice == 2:
## STATEMENT 2

53

You might also like