0% found this document useful (0 votes)
23 views

Python Booklet-Year 10

Uploaded by

virajd205
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Python Booklet-Year 10

Uploaded by

virajd205
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

HARNESS THE POWER OF

Python

print(“\n\nPress the
enter key to begin.”)
Python Introduction
Python is a programming language developed by Guido van Rossum and first released in 1991. The
name was inspired by the British comedy group Monte Python but the official mascot of the language
has become the python snake.

Python is
• Easy to use. Many of the popular languages like Visual Basic, C# and Java are considered
high level languages, which means that they’re closer to human language than machine language
but Python with its clear and simple rules, is even closer to English.

• Powerful. Python is open source software. 5 out of the 7 major NZ universities (including
Auckland university) use Python for their programing as well as many big companies:
• Many components of the Google spider and search engine are written in Python
• Games: Battlefield2, crystal Space, Star Trek, Bridge Commander, Temple of Elemental
Evil, Disney Interactive Media Group etc
• NASA: Johnson Space Center uses Python in its Integrated Planning System as the
standard scripting language
• IBM East Fishkill is using Python to create the business practice logic for factory tool control
applications.
• Industrial Light+Magic, Microsoft, Red Hat, verison, Xerox and Yahoo

• Python is Object oriented (OOP)

• Python is a ‘Glue’ Language. It can be integrated with other languages such as C, C#


and Java

• Python runs everywhere. Python programs are platform independent which means that
regardless of the operating system you use to create your program, it’ll on any other computer with
Python.

• Python has a Python Tutor mailing list, an informal way for beginning programmers to
ask questions.
http://mail.python.org/mailman/listinfo/tutor

• Python is free and open source. Python is free and you can install it on your computer.
At school we are using Python 3.3 with an IDLE.

Start Python
Open IDLE (Python GUI) this opens the Python Shell (interactive mode)
File New – this will open a Python file (script mode)

When writing Python code, the IDLE has two open windows – the shell (interactive mode where you try
things out as it shows you the results of your code) window, and the development window or script
mode. The shell is where the Python code actually runs (the GUI) and while the development window is
where programs are developed. When using script mode files must be saved with .py on the end. IDLE
is a special text editor like MS Word, except it understands Python and helps you get your code right.
First program Hello World

What’s the first thing programmers want to say to the rest of us? Hello World. It is 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 can do this you will have tested whether everything that was set up for
you is working properly.
• Start up IDLE.

2
• In the new Python File (not the shell) type in: print(“Hello World”)

NOTE: In Python, getting the computer to write words can be done using the print function. The word
print tells Python that you want to print some words out on the screen. This is called printing a string.
Print is in lowercase letters. The text inside the brackets in the quotation marks is what will show.

• Save the program eg hello_world.py This is your first program.

• Run the program (F5)

The words “hello world” are called a string. A string is made up of a series of characters. If the
characters make up a word or a sentence it is called a sting literal.

In between the brackets we also need to add what we want Python to print I quotations marks.
So I could write: “My online name is CodeCracker.” I would write this like
print(“My name is CodeCracker.”)

Error Messages
Computers take everything literally. If you misspell a function name by even one letter, the computer
will have absolutely no idea what you mean. Eg

Change the ‘n’ in print to ‘m’ eg primt(“Hello World”)


Save & F5
You will get an error message

Traceback (most recent call last):


File “H:/Documents/10DTG/Python Beginner Book/hello world.py”, line 3, in <module>
primt(“Hello World.”)
NameError: name ‘primt’ is not defined

Translated this is saying – Huh? The key line in the message is NameError: name ‘primt’ is not
defined. This is saying the computer doesn’t recognise primt. As a human being we can ignore the typo
and recognise the word as print but the computer can’t. An error is a bug in the program and it needs
to be fixed.

Colour coding
Colour coding is called Syntax highlighting.
• Special words that are part of Python like print and input are displayed in purple
• Strings are displayed in green
• The output (what the interpreter displays as a result of what you type) is in blue.
• Comments are red

Comments
A # symbol begins a comment. Any comments are for programmers and are ignored by the computer.
Comments should be used to explain what almost all variables are for and to explain the purpose of
any pieces of code. It is a good idea to start all programs with a few comments. It is helpful to list the
title of the program and its purpose. You can also list the name of the programmer and the date it was
written. Comments help others understand the intention of your program.

Using Blank lines


Blank lines make it easier for us to read the program. A computer will ignore blank lines in a program.
Eg type in

print(“Mary had a little lamb and everywhere that Mary went the lamb was sure to follow.”)

Save and F5.


Edit the text by adding in the next line before the speech marks. “It followed her to school one day.”
Save and F5.

3
Edit the code to force the new text to go to a new line by adding in \n into the code as follows

print(“Mary had a little lamb and everywhere that Mary went the lamb was sure to follow. \n It followed
her to school one day.”)

Escape Sequences

\n Creates new line 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 speech mark to be used in a string of text.

Waiting for the User


You can keep the window open until the user is done with an application. Practice the following code.

print("Game Over")
input("\n\nPress the enter key to exit.")

Task 1
In a new window write the code to say “Hello Word, nice to meet you.” Save and F5.

Task 2
In a new window create an error message of your own by entering your favourite ice cream flavour eg
leave off one of the speech marks. Then make up for your error and enter a statement that prints the
name of your favourite ice cream.

Task 3
Write some code so that the computer will show the text for a joke. An example is below but you may
want to use your own joke.

print("Question: What goes clip?\nAnswer: A one legged horse.”)

Task 4
Write a program that prints your favourite quote. It should give credit to the person who said it on the
next line.

Task 5
Write and save a program that prints out your name and waits for the user to press the Enter key
before the program ends.

Part 2
Using strings and quotation marks (quotes)
• You can use either a pair of single (' ') or double ("") quotes to create string values. The computer
doesn’t care. The quotes are like bookends telling the computer where the string begins or ends.
• You can’t start with a single quote and end with double quotes.
• You can start and end with double quotes and have single quotes inside eg
print("With the words, 'Houston, we have a problem.', Jim Lovell became one of USA's most
famous astronauts.")
• Multiple values: You can print multiple values with a single print() functions. Eg
print("Same","message","as before"). This will print out Same message as before. Note that the
program does not need spacebars between the words as the comma serves this function.

4
• When you have a list of arguments, you can start a new line after any of the comma separators in
the list. Eg
print("orange",
"green",
"red")
This will print out orange, green, red but it might make your code easier to read.

• Triple quoted strings: When the string covers multiple lines, use three double quotes at the start
and finish. Eg
print("""Baa, baa black sheep
Have you any wool?
Yes Sir, Yes Sir
Three bags full""")
Triple quoted strings will print multiple lines exactly as the way you type them.

• Specifying a final string to print: By default, the print( ) function always starts on a new line
which is usually what you want. You can specify that a print function could end with a space and
then print two print functions on the one line. Eg
print("Here", end=" ")
print("it is ...")

• Repeated strings: You can program the print function to print multiple times eg
print("I want a pie for lunch."*10)
This will print “I want a pie for lunch” 10 times.

Functions
print() is called a function. What print () will do is print anything you throw at it inside brackets. They
must be separated by a comma, and strings (bits of text) must be put in speech marks. Everything
inside the brackets will be printed out in order. The results from sums can also be output but you must
not put the calculations in speech marks.

Task 6
Write a short program which prints the teacher told the class, Python is an amazing program, and the
class agreed.

Task 7
Write a short program which prints these lines to Lorde’s song Royal. Make sure each line starts on its
own line.

I've never seen a diamond in the flesh


I cut my teeth on wedding rings in the movies
And I'm not proud of my address
In the torn up town, no post code envy

Task 8
Write a program that has two print functions but prints on one line.

Task 9
Write a program to print a short statement 6 times but each statement is to start on a new line.

5
Part 3 Variables
• In computing terms a variable is something that the computer has to remember. Like a piece of
information that is stored into a box.
• Whenever any word or number follows a = symbol, it is regarded by Python as a variable.
• Variables store a piece of data, and gives it a specific name. For example:

Spam=5 means that the variable spam now stores the number 5. Each variable must be unique.

• A variable provides a way to label and access information. Instead of having to know exactly where
in the computer’s memory some information is stored, you use a variable to get at it. It’s kind of
like calling your friend on his cell phone. You don’t have to know where in the city your friend is to
reach him. You just press a button and you get him. But before you use a variable you have to
create it. eg

name=”Hemi”

Once a variable has been created it refers to some value and it can be used just like a value. Eg the
line

print(name) prints the string Hemi just like the statement print(“Hemi”) does.

print(“hi,”, name) prints the string Hi, followed by a space, followed by Hemi.

• Rules about creating variable names:


o A variable name can only contain only numbers, letters and underscores
o A variable name can’t start with a number
• Guidelines about naming variables:
o Choose descriptive names so they represent what the variable contains.
o Be consistent – either use underscore, eg high_score or highScore. It’s not important which
you use as long as you’re consistent.
o Follow the language traditions eg the first letter should be lower case eg high not High and
don’t use an underscore as the first letter
o Don’t make them too long – the longer the name the greater the chance of a typo.

Variables can be concatenated with strings.


bandName = “The Beatles”
print (“The most successful band ever were “ + bandName)

6
7
Getting User Input
We have looked at how to write text and how to create variables but now we need to get the computer
to ask questions and save the answer we give.

Input statements allow the user to interact with your program. Getting user input isn’t very hard and the
result doesn’t look much different. For example”

input(“What is your name?”) The first line asks for your name
print(“My name is R2D2”) The second line merely states a name

The problem with the above code is that after asking for your name it doesn’t save it. Do you remember
that by using a = symbol we could create a variable.

yourName = input(“What is your name?”) Now the computer remembers the name you
print(“My name is R2D2”) give and can use it.
print(yourName + “ was my dad’s name”)

Try this code:

#Personal Greeter
#Demonstrates getting user input

name=input ("Hi, What's your name?") # asks for name


print(name)#prints name
print("Hi,", name) #prints Hi puts a space in and then the user’s name

input("\n\nPress the enter key to exit.") #waits for the user to end the program.

Name is a variable and its job is to call to the function input – input(). The input function gets some text
from the user. It takes a string argument that it uses to prompt the user for this text.

Task 10
Write a small program that asks the user to input their name. When you run the program follow the
instructions and key in your name.

Task 11
Write a small program that greets the user {eg hello}, asks them their name and then replies with “It’s
good to use you, {name!}”. Ask the user to press enter to close the program. Call the program personal
greeter.

Task 12
Write a short program that asks a person their name, and their location, and then replies “Hello {name},
I hope the weather is good in {place}. Ask the user to press enter to close the program. Use 4 lines of
code and use comments. Remember to use a comma after the name and a full stop at the end of the
sentence. Hint: use the structure print (“It is good to see you,”, name+”!”)

Task 13
Write a program that allows a user to enter his or her two favourite foods. The program should then
print out the name of a new food by joining the original food names together.

Working with Numbers – Maths


Python can do maths!
Python uses two different types of numbers:
Integers which are whole numbers – numbers with no fractional part or numbers that can be
written without a decimal point. Eg 1, 27, -100, 86

8
Floats – Floating point numbers. These are numbers with a decimal point. 2.3, -99.1, 1.0

Useful Mathematical Operators


Operator Description Example Answer
+ Addition 7+3 10
- Subtraction 7-4 3
* Multiplication 7*3 21
/ Division (True) 7/3 2.3333333333333335
// Division (integer) 7//3 2
% Modulus 7%3 1
NOTE: Division True will print the remainder (floats)
Division (Integer) will print only the whole number and ignore the remainder.
Modulus produces the remainder of an integer division expression.

Type the following equations into Python and see how easy it is to do maths! Remember to add a print
function.

2*2
2+2
2/2
2-2

The +. -, / and * symbols are called operators because they tell the computer to do an operation. Try
the following equations:

12 * 12
1 + 78
45 / 3
10 * 2 + 5 / 2 - 2

Combining text and maths


Concatenation is a hard word to remember!
So you have seen that Python can be used to work out equations, we will now ask Python to print
numbers and words together. In programming languages adding together strings with numbers or
strings with more strings is called concatenation.

For example I could say “I am a school student and I am aged 14”.


print(“I am a school student and I am aged” +14)

Or I could write:
print(“2+2 = “ + str(2+2))

It is also possible to combine text (or strings) and numbers in the print() function. The comma is used
here as a separator between text and the maths.

print("111 divided by 4 = ", 111/4)


111 divided by 4 -27.75

Task 14
Write a short program that assigns x the value of 20 and y 10. Then
• add x and y together

9
• take y from x
• multiple x and y
• divide x by y
• shows the modulus of x divided by y.

Save as number_input.py
Remember to use comments
The output: 30, 10, 200, 2.1, 0.

Comparative Operators
In programming we often ask computers to make checks to see if something is true or false. This helps
computers make decisions based on the algorithms we write. For example in a game if the lives
dropped to 0 then the game would finish and display the game over screen:

lives = 1
If lives == 0:
print(“Game Over ! !”)

Try these out in the Python interpreter and you will see that Python will reply either True or False:

3>1
3<1
3 = = 2 +1
5-2>1
1==1
0 > 0.001

Remember that in Python adding a symbol, = creates a variable. In order to test whether something is
equal to something we use = =.

10
11
Task 15
Write a program to make the computer do some simple calculations for you.
Here are 3 lines of code to help you:

No1=int(input(“Give me the first number”))

sum= No1+No2

print(“The sum is”,sum)

Use the program to calculate the difference between No1 and No2 (subtract); the product of No1 and
No2; the quotient (divide) and the whole number remainder (modulus). Ask it to print the results of the
calculations as per the print line above. Save the program as calculator.py

Task 16
Enter this code.
Save the code as Rich Kid Budget – bad

#Rich Kid Budget – bad


#demonstrates asking for user input
#demonstrates a logical error

print(""" Rich Kid Budget


Totals your monthly spending so that your budget doesn't run out (and you’re forced to go to mummy
and daddy for more money).

Please enter the requested, monthly costs. Since you're rich, ignore cents and use only dollar
amounts.""")#Use triple quotation marks to enter multiple lines

petrol= input("Petrol:") #all variable names have lowercase letters


games = input("Computer Games:")#Use a capital letter for the parts that are to be printed
clothes = input("Designer Labels:")#use a colon at the end of the labels
food =input("Dining Out:")
tutor =input("Personal Tutor:")

total = petrol + games + clothes + food + tutor #Asks the program to total all the costs

print ("\nGrand Total:", total)# Asks the program to print the total and call it Grand Total

input("\n\nPress the enter key to exit")#Asks the user to press enter to close the program.

What’s the problem with the code??


The program isn’t working correctly. It has a bug but not a bug that causes it to crash. When a program
produces unintended results but doesn’t crash, it has a logical error. Because it doesn’t crash you don’t
get an error message to help you work out what went wrong.

The total just shows the costs for each item and puts them one after the other. It doesn’t add the costs
together.
How do we fix this? Somehow those string values returned by input() need to be converted to numeric
ones (numbers). Then the program will work as intended. The code needed to do this is:
petrol =input(“Petrol:”) # this is the original input code
petrol =int(petrol) #this is the new piece of code which converts the petrol value into a numeric
one. Note that the petrol starts with a lowercase letter as the variable name is lowercase.

This code can be shortened to one line using the following format:
games =int(input(“Computer Games:”))

12
This nests two function calls – input() and int() by putting one inside the other. In this statement for
games, input() goes out and asks the user how much they are allowed to spend on games. The user
enters some text, and that is returned as a string. Then, the program calls the function int() with that
string. int() returns the integer the string represented. Then, that integer is assigned to games.

Task 17
Modify the code used for Rich kid budget bad so that it does return the correct total and then save the
file as Rich kid budget good.

Task 18
Write a program that uses the input () function to get the user’s name, age and weight. Save the
program as useless_ trivia.py

Task 19
Write a program that asks for a person’s name and age and then greets the person, and tells them how
old they will be in the year 2115. Save the program as name_age.py

Task 20
Write a Tipper program where the user enters a restaurant bill total. The program should then
display two amounts: a 15 percent tip and a 20 percent tip. Save as tipper.py

Task 21
Write a short program which:
a. Adds up the following list of values and assigns the variable SubTotal to the results.
Values: 1.50, 2.75, 13.15, 11.45
b. Sets a variable, GSTRate, at 0.15, multiplies the subtotal by GSTRate, to a new variable,
GST
c. Adds GST to SubTotal, to find Total
d. Print the Subtotal, GST and Total.
Call the program assigning integers to variables.py

Task 22
Write a Car Salesman program where the user enters the base price of a car. The program should add
on a bunch of extra fees such as GST, licence plates, tow bar, sound system and seat covers. Make
the GST 15% of the base price. The other fees should be set values. Display the actual price of the car
once all the extras have been added on. Save the file as car.py

13
14
Part 4
Using Random Input
Using random numbers: examples of an application –
• Guess my number Game: a computer chooses a number between 1 and a 100 and the player
tries to guess it in as few attempts as possible.
• Craps Game: this simulates the roll of two, six sided dice. It displays the value of each and their
total. To determine the dice values the program uses functions that generate random numbers.
Python generates random numbers based on a formula so they are not truly random.

Task 23
Write the following program and run the program to see what it does.

# Craps Roller
# Demonstrates random number generation

import random

# generate random numbers 1 - 6


die1 = random.randint(1, 6)
die2 = random.randrange(6) + 1

total = die1 + die2

print("You rolled a", die1, "and a", die2, "for a total of", total)

input("\n\nPress the enter key to exit.")

Explanation
The first line of the code in the program introduces the import statement. This allows you to import or
load, modules and in this case it is the random module: import random

Modules are files that contain code meant to be used in other programs. These modules usually group
together a collection of programming related to one area. The random module contains functions
related to generating random numbers and producing random results.

Using the randint() Function


The random module contains a function, randint(), which produces a random integer. The Craps Roller
program accesses randint() through the following function call:
random.randint(1,6)
Notice that the program calls the function which has the randit() in it. This is called dot notation and
using the random.randint() means that the function randint() belongs to the module random. The
randint() requires 2 integer values and returns a random integer between those values (including the
first and last value). So by entering the values 1,6 to the function, I’m guaranteed to get back either 1,
2, 3, 4, 5, or 6.

Using the randrange() Function


The random module also contains a function randrange(), which produces an integer. The randrange(6)
produces an integer from, and including, 0 up to but not including the last number. So randrange(6)
produces either 0,1, 2, 3, 4, or 5. To include the number 6 a +1 was added:
die2 = random.randrange(6) + 1 and then a 6 is added.

In the Craps Roller program both randint() and randrange() were used to show you two different
functions for generating random number. You can pick which one suits your needs.

Part 6 Using the If Statement


15
Branching as used in a computer program means making a decision to take one path or another.
Through the if statement, your programs can branch to a section of code or just skip it, all based on
how you’ve set things up. The if statement uses indenting to show what lines of code would be
executed if the statement is correct. The ELSE statement shows what code to execute if the
statement is incorrect.

Comparison Operators
Operator Meaning Sample Condition Evaluates to
== Equal to 5==5 True
!= Not equal to 8 != 5 True
<> Same as != not equal to 6<>7 True
> Greater than 3>10 False
< Less than 5<8 True
>= Greater than or equal to 5>=10 False
<= Less than or equal to 5<=5 True

Task 25
Type in the following program which will illustrate how the if statement works. Save the program as
password.py

# Password
# Demonstrates the if statement

print("Welcome to Lynfield System Security Inc.")


print("-- where security is our middle name\n")

password = input("Enter your password: ")

if password == "secret":
print("Access Granted")

input("\n\nPress the enter key to exit.")

Examining the if statement


The key to the program Password is the if statement

if password == "secret":
print("Access Granted")

If password is equal to “secret”, then “Access Granted” is printed and the program continues to the next
statement. But, if it isn’t equal to “secret”, the program does not print the message and continues
directly to the next statement following the if statement.

Creating Conditions
All if statements have a condition. A condition is just an expression that is either true or false. Python
has its own, built in values to represent truth and falsehood. True represents true and false represents
false. A condition can always be evaluated to one of these.

Understanding Comparison Operators


Conditions are often created by comparing values. You can compare values by using comparison
operators. It’s the equal to comparison operator, written as ==.

16
17
Using Indentation to Create Blocks
Notice that the second line of the if statement print("Access Granted") is indented. By indenting the
line, it becomes blocked. A block is one or more consecutive lines indented by the same amount.
Indenting sets lines off not only visually, but logically too. Together they form a single unit.
If statement summary
You can construct an if statement by:
using if, followed by a condition
followed by a colon,
followed by a block of one or more statements.
If the condition evaluates to True, then the statement that make up the block are executed.
If the condition evaluated to False then the program moves on to the next statement after the if
statement.

Task 26
Write a short program, for Python’s Password Protected Website, that allows the user entry/access if
the correct password is entered. The password is to be a mixture of numbers and letters. Also ask the
user for his/her first name and if they enter the correct password send them a welcome message that
uses this name. Then ask the user to press enter to exit the program. Save the file as task24.py.

Using the ELSE Clause


Sometimes you’ll want your program to “make a choice” based on a condition: do one thing if the
condition is true, do something else if it is false. The else clause, when used in an if statement, gives
you that power.

With the password program if you got it wrong nothing happened. We can modify the program to
improve it by adding in just one line of code – an else clause.

Task 27
Open password and add in the addition else clause and then run the program. Save the program as
granted_or_denied.py

# Password
# Demonstrates the if statement

print("Welcome to Lynfield System Security Inc.")


print("-- where security is our middle name\n")

password = input("Enter your password: ")

if password == "secret":
print("Access Granted")
else:
print("Access Denied")

input("\n\nPress the enter key to exit.")

You can create an else clause immediately following the if block with else followed by a colon, followed
by a block of if statements. The else clause must be in the same block as its corresponding if. That is,
the else and if must be indented the same amount.

Task 28
Modify your program saved as Task27 to add in a further condition if the user gets the wrong password.
Tell the user to Work harder as you will have to solve your own problems.

Task 29

18
Write a program that lets the user guess a number between 1 and 10. The number you want the person
to guess is 5. If the user guesses 5 then tell them “You guessed correctly.” If they got it wrong then tell
them “You guessed wrong.” Then tell them to press enter to end the program. Save the program as
Guess_my_number.py

Using the Elif Clause (see also random file for MyMagic8Ball)
It statements can check for a list of things instead of just 1. You can allow the user to choose from
among several possibilities in an if statement with the use of the elif clause. This comes in handy when
you have one variable that you want to compare to a bunch of different values. For example:

temp = int(Input(“What’s the temperature in Celsius?”))

if temp < 8:
print(“Brr, it’s a cold day ! ! !”)
elif temp > 8 and temp < 15:
print(“It’s a mild day”)
elif temp > = 15 and temp < 21:
print(“It’s a warm day”)
elif temp > = 21:
print(“It’s a hot day”)
else:
print(“Sorry, you must enter a number”)

Can you see that the word if is only used once? Every other time to check if something is True, Python
uses elif.

Task 30
Open the mood_computer.py file and run it a few times. Notice that it will randomly show you different
moods. Mood computer generates a random number to choose one of three faces to print using an if
statement with elif clauses.

Examining the elif clause


An if statement with elif clauses can contain a sequence of conditions for a program to evaluate. In
Mood computer, the lines containing the different conditions are:
if mood == 1:
elif mood == 2:
elif mood == 3:
Notice that you write the first condition using an if, but then test the remaining conditions using elif
(short for else if) clauses. You can have as many elif clauses as you want.

The program first checks to see if mood is equal to 1. If it is, then the happy face is printed. If not, the
program moves to the next condition and checks if mood is equal to 2. If it is, the neutral face is printed.
If not, the program checks if the mood is equal to 3. If so, the sad face is printed.

If none of the preceding conditions for mood turn out to be True, then the final else clause block runs
and "Illegal mood value! (You must be in a really bad mood).") appears on the screen. This should
never happen since mood will always be 1, 2, or 3.

Although the final else clause is not necessary it’s a good idea. It works as a catchall for when none of
the conditions within the statement are True.

Task 31
Modify the Guess my number game program (Task 29) to give the user more information if they get the
guess wrong. If they guessed a number that is higher than 5 then tell them “Too high.” or if they
guessed below 5 then tell them “Too low.” Hint use an if statement and elif conditions. Save the
program as Guess_my_number2.py
Part 7 Creating While Loops
19
We need to know how to tell a computer to do repeats. To do this we use a while loop. This runs code
while something is true and stops when it becomes false.

While Loops allow you to repeat something. Eg


• In a banking application, you might want to tell your program: while the user hasn’t entered a valid
account number, keep asking the user for the account number.
Below is an example of how to write lines using a while loop:

lines=0
while lines<50:
print ("I will not write code in History lessons.")
lines =lines+1
press enter twice after inputting the code. This will give you the result below.
I will not write code in History lessons.
I will not write code in History lessons.
I will not write code in History lessons. (this will print 50 lines)

There is another solution to the same problem of needing to print 50 lines –


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

The while loop code is longer but it 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. Try entering the code below and run
it.

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

Result
1
2
3 etc to 100.

Explanation of while loop counting to 100


First a variable was created and a value was assigned to it. Remember a variable is a space in the
computer’s memory where we can store a string or a integer. We create a variable by naming it. In this
example the variable was named number and with the equals operator we give it the value of ‘1’.

The next line of code while number <101: says ‘while the variable called number is less than 101 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 101.

The next line of code print (number) has no speech marks as we want the value of number not the
word number.

The last line of code number = number+1 is in the loop. It keeps adding 1 to number for each
passage through the loop. Don’t forget the variable’s value can be changed with the equals operator at
any time.

20
21
Task 32
Write some code in IDLE so that the computer counts up to 20 in twos to. Save and F5. Try running
the code with a different start number.

Task 33
Write some code that the computer outputs the 5 times table like this.
1x5=5
2x5=10
3x5=15

Hint: You will need two counter variables which you could call n and num. Then you should find out
how to write one line, and then make your loop do it 10 times.

Task 34
Type in the following program that demonstrates how to create a While Loop.

#Three Year-Old Simulator


#Demonstrates the while loop

print("Welcome to the 'Three-Year-Old Simulator'\n")


print("This programs simulates a conversation with a three-year-old child.")
print("Try to stop this madness.\n")

response =""
while response !="Because.":
response = input ("Why?\n")

print("Oh. Okay.")

input("\n\nPress the enter key to exit.")

Examining the while loop


The loop from the program is just two lines:
while response !="Because.":
response = input ("Why?\n")

In the while statement, the computer tests the condition and executes the block over and over until the
condition is false. That’s why it’s called a loop.

In this case the loop body is just response = input ("Why?\n"), which will continue to execute until the
user enters “Because.” At that point, response !="Because.": is false and the loop mercifully ends. Then
the program executes the next statement, print(“Oh. Okay.”)

Sentry Variable the program has a variable set which compares the user response the condition of the
while loop. In this program the sentry variable is response ="" and whatever the response is, then
is compared to the while response.

It is usually a good idea to set the variable to some type of empty value "".

The sentry variable should come just before the while loop. If the program doesn’t have a sentry
variable then the program will generate an error when it is run.

Make sure that it’s possible for the while condition to evaluate to True at some point; otherwise the
block will never run.

Task 35

22
Write an explanation of what is happening in this while loop. Suggestion: Type the code into Python
and run it a few times using different input until you understand what is happening.

Fred = input ("Please enter something")

while Fred != "X":


print (" This is what the user did input",Fred)
if Fred == "b":
print ("Yay its a booking")
Fred = input ("Please enter something")

Part 9 For Loops – i in range


Pieces of code often need to run again and again, in order to accomplish the goal for the program –
this is called iteration.

For Loops
A for loop repeats its loop body for each element of the sequence, in order. When it reaches the end of
the sequence, the loop ends.

Task 36
Try this code which shows one application of the for loops

#for loops
#Demonstrates the loop with a string

word = input(“Enter a word.”)

print(“\nHere’s each letter in your word:”)


for letter in word:
print(letter)

print(“\n\nPress the enter key to exit.”)

The results using the word Loop

Enter a word: Loop

Here's each letter in your word:


l
o
o
p

Press the enter key to exit.

23
24
Explanation of for loop program
The loop is in just two lines:

for letter in word:


print(letter)

All sequences are made up of elements (an ordered list of things). A string is a sequence in which each
element is one character. In the case of the string “loop”, the first element is the character “l”, the
second is the “o”, and so on.

A for loop marches through (or iterates over) a sequence one element at a time. In the above program
the loop iterates over the string “loop” one character at a time. A for loop uses a variable that gets each
successive element of the sequence. In the loop, letter, is the variable that gets each successive
character of the “Loop”. Inside the loop body, the loop can then do something with each successive
element. In the loop body, I simple print letter. Now the variable you use to get each element of the
sequence is like any other variable – and it doesn’t exists before the loop is created.

So, when the loop beings, letter is created and gets the first character in word, which is “L”. Then, in the
loop body, the print statement displays L. Next, with the loop body finished, control jumps back to the
top of the loop and letter gets the next character in word, which is “o”. The computer displays o. and the
loop continues until each character in the string “loop” is displayed.

Using the for loop with numbers

Task 37
Type in the following code to see how this for loop works.

#counter
#Demonstrates the range() function

print("Counting:")
for i in range (10):
print(i, end=" ")

input("\n\nPress the enter key to exit.")

The results
Counting:
0123456789

Press the enter key to exit.

The explanation
This loop counts forward. The sequence the loop iterates over is generated by the return value in the
range() function. This range function returns a sequence of numbers. If you give a range a positive
integer it returns a sequence starting with 0, up to but not including, the number you gave it. So the
code, range (10), returns the sequence [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]. This should help you visualise what
happens in the loop: in the first iteration of the loop, i gets 0 and its value is printed then in the next
iteration, i gets 1 and its value is printed and so on until the final iteration, where i gets 9, its value is
printed, and the loop ends.

25
Task 38
Type in this code which gets the computer to count by fives.

#counting by 5s
#demonstrates for looks with 3 numbers in the range

print("Counting by fives:")
for i in range(0, 50, 5):
print (i, end=" ")
input("\n\nPress the enter key to exit.")

The Results
Counting by fives:
0 5 10 15 20 25 30 35 40 45

Press the enter key to exit.

The explanation
If you give range( ) three values, it will treat them as a start point, an endpoint and the number by which
to count. The start point is always the first value in our imagined sequence while the end point is never
included – there for the results show it starting at 0 and ending at 45 as the end point is never included.
If you wanted to include 50, you end point needs to be greater than 50 eg (0, 51, 5) would work.

Task 39
Write a program that prints every third number from 1 to 60.

Task 40
Write a program that prints “Hello World” ten times using a for loop.

Task 41
Write a program that counts backward from 10. The expected outcome is 10 9 8 7 6 5 4 3 2 1.

Task 42
Write a program that prints out the times table for the number the user inputs. You can do this with
three lines of code. Remember to ask the use to choose a number, set up a for loop and display the
result using the following print statement

print (number, "times ", i, " is ", number * i)


number is the variable used to ask the user for input. You may have called it a different number.

Part 10 Using the len() Function


Message Analyser Program

By using the len () you can print how long the message that the user inputs is. The code for this is

print(“\nThe length of your message is:”.len(message))

you can put any sequence you want to the len() function and it will return the length of the sequence. It
will count every character, including a space or an exclamation point.

26
Task 43
Try this code:

#message Analyser
#Demonstrates the in operator

message = input("Enter a message: ")

print("\nThe length of your message is:", len(message))

print("\nThe most common letter in the English language, 'e',")


if "e" in message:
print("is in your message.")

else:
print("is not in your message.")

input("\n\nPress the enter key to exit.")

The in Operator
The letter “e” is the most common letter in English. The program uses the following lines to test whether
‘e” is in the message the user entered:

if “e” in message:
print(“is in your message.”)
else:
print(“is not in your message.”)

The condition in the if statement is “e” in message. If message contains the character “e”, it’s true. If
message doesn’t contain “e”, it’s false.

Part 11 Lists
A list in Python is a container that holds a list of objects (words or numbers). For example below I a
shopping list for things that need to be bought.
shopping = [‘bread’, ‘cola’, ‘shampoo’, ‘donuts’, ‘cheese’]
To create a list give it a name (the same way you did for a variable) and put items of the list in square
brackets separated by commas.

To print the list in Python you tell it to print the name of the list eg print(shopping)

In programming languages counting usually starts from 0. Therefore the first item in the list is ) and the
second item is 1.

We can print out single items from a list by typing the list name followed by the item number in square
brackets.
Print(shopping[0] – this will print out bread which is the first item on the list.

Task 43
Create a list called avengers for the Avengers characters, Captain America, Thor, The Hulk and Iron
Man.
Print the list.
Print The Hulk only.
Print “the character who has a special hammer is” with the 2nd string in the list.
Print the code that concatenates that your favourite characters are the first and the fourth in the list.

27

You might also like