Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

2021 PSP Week 3 Introduction Programming Lecture New

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

2021 PSP Week 3 Introduction Programming Lecture New

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

2021-2022 – Semester 1

Problem Solving and


Programming

Week 3 Lecture – Introduction to Programming


Gore Jiang
Suggestions for the course

• Please do speak in English in class

• Use your laptops and phones based on


instructions

• Please do not look at irrelevant things in class


Content

• Programming Language
• How does programs run ?
• Python
• From Problem Solving to a Program
• Strings
What is Programming?
• Programming is not just about learning a
programming language and coding
• Writing a program is only one part of a whole
software engineering process
• Programming requires you to :
1. Understand the problem and what we want to
achieve
2. Come up with a solution to the problem
3. Write the program to implement the design
4. Test the program to see if it works up to specification
• We practice 1 and 2, let’s focus on step 3
http://www.automatedtrader.net/Files/news/periodic-table.jpg
Compiling, Interpreting, and
Running Programs
When we program, the code that we write is known as
source code. How do we get from that to …

Output from a running program?


Compiling, Interpreting, and
Running Programs
• A computer cannot directly execute the source
code that we write.
• In order to be executed it must be converted
into machine code.

Source Machine
Code Code
Compiling, Interpreting, and
Running Programs
• There are two basic ways of doing this:
• Code can be interpreted.
Each line of source code is read in turn, and then
converted into machine code instructions, which are
then executed.You need to have access to the source
code every time you run it.
• Code can be compiled.
The entirety of the source code is read and converted
into a separate machine code program which you can
run whenever you like.
In theory, once the program is compiled, you could
throw the source code away and still execute the
program (in practice this would be a very bad idea!).
Understanding What Happens
when a Program Runs
• When we are trying to understand what happens when
a program runs, we will “pretend” that the source code
is being directly executed by the machine.
• We need to know about compilation and interpretation
in order to understand how to prepare a program for
execution, and deliver it to a potential user.
• Trace tables are useful to understand the code
n1 n2 Output
30
30 20
30 20 50
What we need in a
programming language

• The language requires syntax:


• Vocabulary: a set of predefined words
• Grammar: a set of rules that must be followed to
build correct sentences

• We are going to review Python syntax today by


going through some of the algorithms
developed in Week 2
What we need in a
programming language
• Variables to store data • To communicate with
• Numbers the user
• Words • Input data
• Lists • Output results

• To process the • To tell the program


information how to run it
• Arithmetic operations • Sequence
• Comparisons • Selection
• Iteration
Variable in Python
• Many Programing languages require a declaration of the variable before
its use.
• Name of the variable and the type of data stored in that variable
• Java declaration
int n1;
• A variable does not need to be declared in Python
n1 = 20
name = "Mary"
• Syntax: The name of a variable must be just one word, cannot start with a
digit or contains special characters such as: +,*,/, %
• Convention: Use lower case for the name of the variables, use meaningful
names and use “camelCase” or underscore _ if you want to use a two-
word identifier
highestScore = 100
ISBN_number = ‘1234567890’
Input and Output
• User can be asked for the value of a variable. That can be done in
Python using the function input

• What in an algorithm looks like:


Read from keyboard
Input in variable

• In Python
name = input("enter your name: ")

• If the value given by the user is an integer or a real number, it


needs to be converted using the function int or double
n1= int(input("Enter a number: "))

• Information can be displayed using the function print


print("The sum is: ", n1+n2)
• Using python document to search any python function
Selection (Week 2)
Write a program that puts into max the larger of
x and y
Pseudocode: Python:

If (x > y) then if x > y:


set max to x max = x
else else:
set max to y max = y
Selection 2
Write a program that print out whether x or y is
the biggest, or they are the same
Pseudocode: Python:
if (x > y) then if x > y:
print x is the biggest print(x, “ is the biggest”)
else if (x < y) elif x < y:
print y is the biggest print(y, “ is the biggest”)
else else:
print both are the same print(“both are the same”)
Iteration in Python

Write a program that prints out the numbers from


1 to 9
Pseudocode: Set count to 1
While count is less than 10
print out count to screen
increment count

Python: count = 1
while count < 10:
print(count)
count = count + 1
Iteration in Python

Write a program that prints out the numbers from


1 to 9
Pseudocode: For count taking values 1 to 9
print count to screen

Python: for count in range(1,10):


print(count)
Case Study 1: ANAGRAM
(Week 2)
• An anagram number is a number that can be
multiplied by at least one single-digit number (other
than 1) to become an anagram of itself.
• Two numbers are anagrams of each other if they
can both be formed by rearranging the same
combination of digits.
• For example:
• 1246878 is an anagram number;
• multiplying by 6 gives 7481268 or by 7 gives 8728146.
• These numbers all contain one 1, 2, 4, 6, 7 and two 8s.
• 1246879 is not an anagram number
Top Level Design of the
ANAGRAM problem
Input number
Set factor to 2
Set factor_printed to False
While factor is less than 10
if number is an anagram then
set factor_printed to True
print factor
increment factor
If not factor_printed then
print no
ANAGRAM in Python
def isAnagram(n, f):
return True

number = int(input("Enter a number "))


factor = 2 Subprogram
factor_printed = False
while factor < 10:
if isAnagram(number, factor):
print(number, " is an anagram with factor ", factor)
factor_printed = True
factor += 1
if not factor_printed:
print("NO")
Running the Program

Bug:
isAnagram is
always true
Top Level Design of the
ANAGRAM problem
Input number
Set factor to 2
Set factor_printed to False
While factor is less than 10
if number is an anagram then
set factor_printed to True
print factor
increment factor
If not factor_printed then
print no
Designing the Sub-Problem
• IsAnagram receives the number and the factor
• Return True if the number is an anagram, False otherwise

Set new number by multiplying number by factor


Convert number to a list of digits
Convert the new number to a list of digits
Sort both lists
If the two list are the same then
return true
else
return false
Python Program

def isAnagram(number, factor):


newNumber =
number*factor
strN1 = str(number)
strN2 = str(newNumber)
sortN1= sorted(strN1)
sortN2= sorted(strN2)
if sortN1 == sortN2:
return True
• Or change if...else to:
else:
return sortN1 == sortN2
return False
Tracing the code http://pythontutor.com
Syntax Errors
• It is unavoidable to make mistakes when writing a
program.
• Syntax errors are those made when the rules of the
language are not followed

The program cannot run


and we may get a tip
from the compiler
Runtime Errors
• These types of errors are usually caused by a wrong operation
• Division by 0
• Attempting to open a file that does not exist
• Indexing beyond the end of a list or string
• These types of errors will make your program crash
Semantic Errors
• The program is syntactically correct but may be nonsense.
• The problem is in the meaning of the program. The output of the
program does not correspond to the expected result.

• As we progress we will see many errors. The interpreter helps us


with syntactic errors but we must run and test the program to find
semantic and running ones
Strings
Strings

• A string is a sequence of characters. We use quotes to show that


something is a string and not, for example, a variable name.

• Python uses single or double quotes


'this is a piece of text'
"this is also a piece of text"

• We can embed one within the other


"this phrase 'to be, or not to be' is a famous
quote"
Concatenation

• Two strings can be joined together with


concatenation. This is the use of the +
character.
• We are overloading the + character as it
already has another meaning when used with
numbers
s = 'Hello There'
name = ‘Daisy'
s = s + name
print(s)
Repeating Strings

• We can also overload the multiplication


operator * to allow us to repeat strings
repeated = "hello " * 3
print (repeated)
Strings test
Working with Strings

• A variable that is a string is an instance of the


String class and has some methods that can
be used to operate over the string
• Methods are like functions but they are
‘attached’ to the item they will act on.
• When we look at object orientation later in the
course we will see more of this but for now we
will just use methods to allow us to carry out
actions on string.
String method

• Given the variable:


s = 'This is a string'
• s.upper() – all to upper case
• s.lower() – all to lower case
• s.replace(old, new, [max]) – replace
(optional max, max changes to make)
• s.split() – convert the string in a list of words

in each case the methods return a new string


Strings
• A string is a sequence of characters, each of which can be accessed
using an index, starting from 0

• The length of a string is returned by the built-in function len

• But be careful…
Subscripts
• In many languages including python we can
address a single element of a string e.g.

a = "hello"
a[0] "h"
a[4] "o"

NOTE: the numbering starts from 0 not 1.


Slicing
• In python we can go further and address sets
of positions within a string

A = "hello"
A[1:3] "el"

Using this colon notation is called slicing.


This slicing operator returns all the characters
from position 1 to 3 excluded
Slicing
0 1 2 3 4
A = "H e l l o"
• So
a[1:2] "e"
a[2:4] "ll"

• We can either use 0 or omit a value for the first value


a[0:2] = a[ :2] "he"

• Similarly for the final value


a[3:5] = a[3: ] "lo"
Slicing
• We can also use negative numbers to go from
the right hand side
0 1 2 3 4
A = "H e l l o"
-5 -4 -3 -2 -1
Extend slicing
• We can also optionally give a third argument to a slice (Not often used)

The third argument is the step size


• Positive for from the left – allows us to jump characters
a[:4:2] 'hl'
• Negative– allows us to reverse a string.
a[::-1] 'olleh‘
gfed
Solving a problem: ISBN
Number, Case 2
• Write a program that identifies if an inputted
ISBN number is valid.
• An algorithm to solve the problem
read in ISBN
set total to 0
Calculate total by multiplying each digit by its position
if total is multiple of 11 then
print valid ISBN number
else
print invalid ISBN
Implementation of the main
problem
def calculateTotal(isbn):
return 0

isbn = input("Please enter the ISBN number")


total = calculateTotal(isbn)
if total % 11 == 0:
print(isbn + " is a valid ISBN number")
else:
print(isbn + " in not a correct ISBN number")
Thinking about the subproblem
• CalculateTotal receives the ISBN number and returns
the total
• How is the total calculated?
• CalculateTotal(156881111X)
• total = 1 * 10 + 5 * 9 + 6 * 8 + 8*7 + 8*6 +1* 5 +
1*4+1*3+1*2+10*1=231
10 9 8 7 6 5 4 3 2 1
1 5 6 8 8 1 1 1 1 X

• However a string or list always starts from left to right,


unless we use negative indices
0 1 2 3 4 5 6 7 8 9
1 5 6 8 8 1 1 1 1 X
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
More thoughts

• The number consists of a list of digits


• we can convert it into a string

• To calculate the number we need to multiply


the digit by its position
• We can work with negative positions, or
• We can reverse the string

• We need to check if the element in the last


position is a number, or X
Design of the sub-problem

total = 0
for every digit in ISBN
if digit is a number
total = total+ digit*position
else
total = total + 10
return total
Python program

def calculateTotal(ISBN):
total = 0;
for pos in range(-10,0):
if ISBN[pos]>='0' and ISBN[pos] <= '9':
total = total + int(ISBN[pos])* -pos
else:
total += 10
return total
Trace Table
Summary

• Programming in Python
• How to move from design to implementation
• Learning the syntax of the language
Homework
• Review week 3 lecture and complete the exercises
• Preparation for week 3 quiz (5 marks)
• Time&Location: Week 3, seminar 2
• Time limit: 20mins

• Check and mark your week 2 coursework (10


marks)
• Time&Location: Week 3, seminar 2 (After week 3 quiz)
• You should submit before the Deadline (18:00 Oct. 19th)

• Questions?
Thank You!

You might also like