Docsity

Python programming companion, Lecture notes of Computer science

Toggle sidebar
bg1
Python programming companion
Pedagogy
Back in the 1980’s I have fond memories of typing in programs from computer magazines, to see what they
would do. Inevitably, at 10 years old, I wasn’t very accurate copying the listings and there were errors. I
had to study the program carefully, and correct my mistakes.
The programs would eventually run, and I would be delighted that the computer did something it couldn’t
do before. The programs were very simple, so I began experimenting with changing a few variables (not
that I understood what they were back in the day) to see what would happen. This intrigued me, and
having picked up the ā€œProgrammers guideā€ and ā€œProgramming keywordsā€ for Locomotive Basic that had
come with my computer, I began to experiment with adding in extra little bits to the code, to see what
would happen. Gradually I became more confident. I began to want more knowledge of keywords, to
solve a particular problem I had. Using the programming keywords as a handy reference I learned the
commands I could use, their syntax, and I gradually memorised them. Programming was challenging and
fun.
As I became more confident I began setting myself bigger challenges, writing code from scratch, and
learning more through the process. I began to learn of more appropriate techniques, and my programs
became more sophisticated. As I learned new languages, I would begin to read programming books, but
skip much of the text to look at the code examples, transitioning my knowledge of keywords from one
language to another.
It is this learning journey to becoming a confident programmer I want to share with my students:
ļ‚· Typing up code, seeing what happens: the confidence from not starting from a blank screen.
ļ‚· Modifying the code to do something different: beginning to understand what the code means.
ļ‚· Attempting challenges using only the commands learned: applying new knowledge gained.
ļ‚· Beginning to write bigger programs with less support: becoming independent.
This guide facilitates that journey in Python: a good starting point for the basics of algorithms before
getting into event driven and object-oriented approaches. However, this is not the end. The guide will
continue to be developed with an increasing number of challenges. The aim being for students not to solve
every challenge, but to choose for themselves: a personalised approach to a common goal.
There is a console Visual Basic version of this guide too.
Codes used in this companion
In the code, a continuation of the same line is indicated with an arrow symbol: →
The difficulty of a challenge is graded by  icons. Students can choose what challenges to complete
depending on their confidence. ā€˜G’ indicates that it is probably suitable for GCSE, ā€˜A’ indicates that the
challenge is suitable for A’level. The expectation is that students will complete the challenges in two
languages, one at GCSE, and one at A’level.
Enjoy!
David Hillyard
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d

Partial preview of the text

Download Python programming companion and more Lecture notes Computer science in PDF only on Docsity!

Python programming companion

Pedagogy

Back in the 1980’s I have fond memories of typing in programs from computer magazines, to see what they would do. Inevitably, at 10 years old, I wasn’t very accurate copying the listings and there were errors. I had to study the program carefully, and correct my mistakes.

The programs would eventually run, and I would be delighted that the computer did something it couldn’t do before. The programs were very simple, so I began experimenting with changing a few variables (not that I understood what they were back in the day) to see what would happen. This intrigued me, and having picked up the ā€œProgrammers guideā€ and ā€œProgramming keywordsā€ for Locomotive Basic that had come with my computer, I began to experiment with adding in extra little bits to the code, to see what would happen. Gradually I became more confident. I began to want more knowledge of keywords, to solve a particular problem I had. Using the programming keywords as a handy reference I learned the commands I could use, their syntax, and I gradually memorised them. Programming was challenging and fun.

As I became more confident I began setting myself bigger challenges, writing code from scratch, and learning more through the process. I began to learn of more appropriate techniques, and my programs became more sophisticated. As I learned new languages, I would begin to read programming books, but skip much of the text to look at the code examples, transitioning my knowledge of keywords from one language to another.

It is this learning journey to becoming a confident programmer I want to share with my students:

ļ‚· Typing up code, seeing what happens: the confidence from not starting from a blank screen. ļ‚· Modifying the code to do something different: beginning to understand what the code means. ļ‚· Attempting challenges using only the commands learned: applying new knowledge gained. ļ‚· Beginning to write bigger programs with less support: becoming independent.

This guide facilitates that journey in Python: a good starting point for the basics of algorithms before getting into event driven and object-oriented approaches. However, this is not the end. The guide will continue to be developed with an increasing number of challenges. The aim being for students not to solve every challenge, but to choose for themselves: a personalised approach to a common goal.

There is a console Visual Basic version of this guide too.

Codes used in this companion

In the code, a continuation of the same line is indicated with an arrow symbol: → The difficulty of a challenge is graded by  icons. Students can choose what challenges to complete depending on their confidence. ā€˜G’ indicates that it is probably suitable for GCSE, ā€˜A’ indicates that the challenge is suitable for A’level. The expectation is that students will complete the challenges in two languages, one at GCSE, and one at A’level.

Enjoy!

David Hillyard

Getting started in Python

  1. Open IDLE (Python). This guide is written for version 3.
  2. Choose File… New File…
  3. A new window will open into which you write your code.
  4. The program must be saved before it will run.
  5. To run your program press F5.
  6. When you save your program, make sure to add .py extension to the filename. This will not only make it easier to find your programs, but will also ensure the text formatting is not lost in the editor.

Objective 1: Key learning points

Understand how to output text strings

ļ‚· Text is known as a string in programming and must be enclosed in double quotes. ļ‚· Strings can be joined together using a comma or plus symbol. This is known as concatenation. ļ‚· When a program is run it is called executing the program. ļ‚· A set of instructions that execute one after another is known as a sequence. ļ‚· Comments can be inserted into the code using a hash symbol. These are helpful to make notes within the program so that the code can be understood again at a later date or by another programmer.

Objective 1: Key words

print()

Example code: print(x)

Purpose: to output x to the screen followed by a carriage return.

To disable the carriage return, use: print(x,end='')

Objective 1: Challenges

Visual dice challenge

Difficulty:  G

Write a program that will output the number 5 on a dice like this:

oooooooooooo

o o

o # # o

o # o

o # # o

o o

oooooooooooo

ASCII art challenge

Difficulty:  G

ASCII (pronounced: as-key) art is a graphic design technique of making pictures using only the 95 printable characters on a keyboard.

Write a program that outputs your name in ASCII Art.

You may find it easier to create the final output in Notepad first and then copy the lines into the programming language.

Objective 2: Key learning points

How to input strings and numbers into variables

ļ‚· Data is input by a user into a variable. ļ‚· Variables have a data type: string, integer or float as examples, indicating how much memory they will use and the type of data they will store. ļ‚· Python does not require variables to be declared before they can be used.

Objective 2: Key words

input

Example code: x = input("Enter your name:")

Purpose: to store text input at the keyboard into a variable, x which can be used later in the program without inputting again.

int

Example code: x = int(x)

Purpose: convert variable x to an integer. Most useful to convert a string input to a number because the character ā€œ5ā€ is not the same as the number 5 to a computer.

Combining input and int enables the input of a number. E.g.

x = int(input("Enter your age:"))

float

Example code: x = float(x)

Purpose: convert variable x to a floating point (decimal) number. Most useful to convert a string input to a number with decimal places because the characters ā€œ5.5ā€ are not the same as the number 5.5 to a computer.

Objective 2: Challenges

Simple adder challenge

Difficulty:  G

Write a program that asks the user for two numbers, adds them together and outputs for example: You entered numbers 5 and 12 They add up to 17

Test marks challenge

Difficulty:  G

Write a program that will ask the user to enter three test marks out of 100 and output the average.

Temperature converter challenge

Difficulty:  G

Write a program to enter a temperature in degrees Fahrenheit and display the equivalent temperature in degrees Centigrade.

The formula for conversion is Centigrade = (Fahrenheit – 32) * (5/9)

Height & weight challenge

Difficulty:  G

Write a program to convert a person’s height in inches into centimetres and their weight in stones into

kilograms. [1 inch = 2.54 cm and 1 stone = 6.364 kg]

Toy cars challenge

Difficulty:  G

A worker gets paid £9/hour plus £0.60 for every toy car they make in a factory. Write a program that allows the worker to enter the number of hours they have worked and the number of trains they have made. The program should output their wages for the day.

Fish tank volume challenge

Difficulty:  G

Write a program that will ask the user to enter the length, depth and height of a fish tank in cm. Calculate the volume of water required to fill the tank and display this volume in litres and UK gallons.

To calculate volume in litres, multiply length by depth by height and divide by 1000.

Objective 3:

Understand string manipulation functions

In this objective you learn how to extract and change data that has been input.

Tasks

  1. Try entering the following commands and see what happens:

#Working with strings forename=input("Enter your surname: ") forename_uppercase=forename.upper() print("Your name in capital letters is:",forename_uppercase)

  1. Change the program to ask for an email address, outputting the string in lowercase using .lower() instead of .upper().
  2. Try entering the following commands and see what happens:

#Len returns the number of characters in a string surname = input("Enter your surname: ") length_name = len(surname) print("There are",length_name,"letters in your name.")

  1. Try entering the following commands and see what happens:

#[:?] returns a number of characters to the left of a string sentence = "I saw a wolf in the forest. A lonely wolf." characters = sentence[:5] print(characters)

  1. Change the program to output the last 12 characters in the sentence using [-12:] instead of [:5].
  2. Try entering the following commands and see what happens:

#[start:end] returns a number of characters in the middle of a string sentence = "I saw a wolf in the forest. A lonely wolf." characters = sentence[20:26] print(characters)

  1. Try entering the following commands and see what happens:

#find returns the location of one string inside another sentence = "I saw a wolf in the forest. A lonely wolf." print(sentence) word = input("Enter the word to find: ") position = sentence.find(word) print("The word",word,"is at character",position)

[:?]

Example code: x = y[:z]

Purpose: To return characters to the left of a string.

x becomes the characters. y is the string to extract characters from. z is the number of characters to extract from the left.

[-?:]

Example code: x = y[-z:]

Purpose: To return characters to the right of a string.

x becomes the characters. y is the string to extract characters from. z is the number of characters to extract from the right.

[?:?]

Example code: x = y[w:z]

Purpose: To extract characters from the middle of a string.

x becomes the middle characters of y, starting from position w, up to z number of characters.

.find()

Example code: x = y.find(z)

Purpose: To find the position of substring z in y.

X becomes the position in the string y where z can be found. E.g. x = ā€œHello Worldā€.find(ā€Worldā€) returns 6 as the letter W is the sixth character in the string (starting at zero).

Objective 3: Challenges

Initials & surname challenge

Difficulty:  G

Write the program from the flowchart below to ask for a person’s forename and surname, outputting their first initial and the rest of their name in capitals. E.g. ben white = B WHITE

Start

Input forename

Input surname

Set initial = to first letter of forename

Set upperinitial = to uppercase of initial

Set uppersurname = to uppercase of surname

Output upperinitial and uppersurname

Stop

Objective 4:

Understand how to use selection statements In this objective you learn how to make different parts of your program run depending on the value of variables.

Tasks

  1. Try entering the following commands and see what happens:

#Using selection statements to check variables #Ask user for the number number = int(input("Enter a number 1-3:")) #Check the value of the number if number == 1: print("Number one") if number == 2: print("Number two") if number == 3: print("Number three")

== allows you to check if a variable equals a value.

  1. Try entering the following commands and run the program three times with the test data: 6, 51 and 70.

Pay careful attention to the indentation with tabs, these are not spaces.

#Works out whether a candidate passed or failed score = int(input("Enter score:")) if score > 40: print("You passed") else: print("You failed")

Note how the program only executes instructions if the condition is true i.e. the score is more than 40, and how it is possible to use an else statement to run an alternative set of commands if the condition is false.

  1. Change the program so that you have to score over 50 to pass.

TAB

TAB

  1. Try entering the following commands and run the program three times with the test data: 6 & 4, 51 & 51.

#Returns whether two numbers are the same num1 = int(input("Enter a number: ")) num2 = int(input("Enter a number: ")) if num1 != num2: print("The numbers are not the same")

else: print("The numbers are the same")

Note != means does not equal.

  1. Try entering the following commands and run the program three times with the test data: 1, 3, 5.

#Using logic operators choice = input("Enter a number 1-3: ") if choice > "0" and choice < "3": print("Valid input") else: print("Invalid input")

Note how ā€˜and’ can be used to check if both conditions are true. You can also use ā€˜or’ if only one condition needs to be true and ā€˜not’ as an alternative to does not equal.

Note how the number was input as a string, not an integer, yet greater than and less than operators still work to check if the input was between 1 and 2. That’s because the ASCII value of the character is being checked, not the actual number. This approach is helpful as it prevents the program crashing if a character is input instead of a number.

Objective 4: Key learning points

How to use selection statements

ļ‚· Checking the value of a variable and executing instructions depending on the outcome of the check is known as a selection. ļ‚· The instructions that are executed as a result of a selection is known as a program branch. ļ‚· The logical checking of a variable against another value is known as a condition. ļ‚· Elif commands can be used instead of multiple if statements. ļ‚· Code for each program branch must be indented. ļ‚· It is good practice to comment a selection to explain its purpose. ļ‚· One ā€˜If’ can be placed inside another ā€˜If’, this is known as nesting.

Objective 4: Key words

If… else: …

Example code: If (x>0 and x<5) or x=10: … else: …

x is the variable being checked. Multiple variables can be checked in one condition. Use brackets to express order of priority. In the example code, x must be between 0 and 5 or equal to 10 for the condition to be true. Else is optional and is used to branch if the condition is false. All program branches must be indented.

Logical operators that can be used in conditions include:

== equals < less than and both conditions must be true != does not equal <= less than or equal to or one condition must be true

greater than not condition is not true = greater than or equal to

elif

Example code: if x == 3: … elif x < 3: … elif x >= 10 and x <= 20: … else: …

x is the variable being checked. elif is used as an alternative to multiple if statements.

Objective 4: Challenges

Under age challenge

Difficulty:  G

Write a program that asks for your age. If you are over 18 it outputs the message, ā€œOver 18ā€, otherwise it outputs, ā€œUnder 18ā€.

Water temperature challenge

Difficulty:  G

Write a program that reads in the temperature of water in a container in Centigrade and displays a message stating whether the water is frozen (zero or below), boiling (100 or greater) or neither.

Vocational grade challenge

Difficulty:  G

Write a program that allows you to enter a test mark out of 100. The program outputs ā€œFAILā€ for a score less than 40, ā€œPASSā€ for a score of 40 or more, ā€œMERITā€ for a score of 60 or more and ā€œDISTINCTIONā€ for a score of 80 or more.

Extended visual dice challenge

Difficulty:  G

Write a program that asks for a number and outputs that number as a graphical dice. E.g.

oooooooooooo

o o

o # o

o # o

o # o

o o

oooooooooooo