CSC1015F – Python Chapter2
description
Transcript of CSC1015F – Python Chapter2
![Page 2: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/2.jpg)
Programming languages A program is a sequence of instructions
telling a computer what to do.
Human languages still don’t work for this Ambiguous and imprecise E.g. “They are hunting dogs.”
Programming languages express computations in an exact and unambiguous way Precise SYNTAX (form) and SEMANTICS
(meaning)2
![Page 3: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/3.jpg)
Origins of the Python language
Created by Dutch computer programmer Guido van Rossum in the early 1990’s Benevolent Dictator for Life (BDFL)
Intellectual property now owned by the Python Software Foundation (PSF) We are using Python Version 3
Free and well documented runs everywhere Clean syntax
3
![Page 4: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/4.jpg)
Integrated Development Environment (IDE)
Graphical interface with menus and windows, much like a word processor
We recommend Wingware 101 free, scaled-down Python IDE designed for use in
teaching introductory programming classes. It omits many features found in Wing IDE Professional
and makes simplifications appropriate for beginners.
you are welcome to use any other tools – e.g. IDLE even a separate text editor and interpreter if you wish
to simply do things the hard way Michelle likes to do this sometimes…
4
![Page 5: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/5.jpg)
Python expressionsPrograms are made up of commands (or
statements) that a computer executes or evaluates.
One kind of statement is an expression statement, or expression.
5
![Page 6: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/6.jpg)
Elements of programs:Expressions Expressions are fragments of code that produce
or calculate new data values, such as Literals
e.g. 3.9, “hello”, 1 Variables
e.g. x Simple expressions combined with operators, e.g:
5+2 x**2 “bat”+”man”
e.g. mathematical expressions like: >>> 4 + 3 will be evaluated as 7.
6
![Page 7: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/7.jpg)
Python interactive shellThe >>> part is called a prompt, because it
prompts us to type something.
7
![Page 8: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/8.jpg)
Elements of programs: Variables and assigment
x=3x+4
x is a variable A variable is used to name a value so
that we can refer to it later
an assignment statement assigns a value to a variable
8
![Page 9: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/9.jpg)
Elements of programs:Assignment statements One of the most important kinds of statement
in Python. e.g.:x=5
x=x+1
Basic form:<variable> = <expr>
9
5x
6x
![Page 10: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/10.jpg)
Elements of programs: Names We name:
Modules Functions Variables
Examples of valid names: X y happy dazed_and_Confused Dazed_and_Confused2
10
![Page 11: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/11.jpg)
Elements of programs: Names
11
![Page 12: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/12.jpg)
Checkpointheight = 1.69weight = 71.5weight/(height*height)
From this Python code, give an example of: a variable an assignment statement a literal
12
![Page 13: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/13.jpg)
Comments And text on a line after the ‘#” symbol will be
ignored by the Python interpreter:
# algorithm to calculate BMIheight = 1.69weight = 71.5weight/(height*height) #calculates BMI
It is essential to include comments to explain your code to others (and your future self!)
13
![Page 14: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/14.jpg)
Elements of programs:Output statements The print function will display text to the
screen e.g. >>> print("Hello")>>> Hello
e.g. # algorithm to calculate BMI
height = 1.69
weight = 71.5
BMI = weight/(height*height) #calculates BMI
print("Body mass index = ",BMI)
14
![Page 15: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/15.jpg)
Checkpoint# file BobBill.pyBob="Bob"Bill="Bill"Bob=BillBill=Bill*3print(Bob,Bill)
From this code, give an example of: a variable a literal an expression an assignment statement15
![Page 16: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/16.jpg)
Checkpoint: What is the output of this code?
# file BobBill.pyBob="Bob"Bill="Bill"Bob=BillBill=Bill*3print(Bob,Bill)
16
![Page 17: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/17.jpg)
Elements of programs:More about print print is a built in function with a precise set
of rules for its syntax and semantics e.g. two forms:print(<expr>,<expr>,…,<expr>)
print()
By default, print puts a single blank space between the displayed values
17
![Page 18: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/18.jpg)
More about “print()” function To print a series of values separated by spaces:print("The values are", x, y, z)
To suppress or change the line ending, use the end=ending keyword argument. e.g.:
print("The values are", x, y, z, end=‘’)
To change the separator character between items, use the sep=sepchr keyword argument. e.g.
print("The values are", x, y, z,sep=’*’)
18
![Page 19: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/19.jpg)
Escape sequencesEscape sequences are special characters that
represent non-printing characters tabs, newlines e.g:
\a - bell (beep)\b – backspace\n – newline\t – tab\’ – single quote\” – double quote\v - vertical tab19
![Page 20: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/20.jpg)
Checkpoint: What is the exact output of this code?
x=20y=30z=40print(x)print(y,'\n',z)
20
![Page 21: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/21.jpg)
Checkpoint: What is the exact output of this code?
x=20y=30z=40print("The values are", x, y, z, end='!!!',sep='!***')
21
![Page 22: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/22.jpg)
Elements of programs:Input statements The purpose of an input statement is to get some
information from the user and store it into a variable.
In Python, input is accomplished using an assignment statement combined with a special expression called input. This template shows the standard form:<variable> = input(<prompt>)
Here, prompt is usually some text asking the user for inpute.g.
weather = input(“What is the weather like today?”)
22
![Page 23: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/23.jpg)
Elements of programs:Input statements
the input statement treats whatever the user types as an expression to be evaluated. e.g.
n = input("Please enter a number: ")
personA = input(“What is your name?”)
23
![Page 24: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/24.jpg)
Checkpoint: What is the exact output of this code?
name = input("What is your name? ")
print("Hellooooo", name*3, end='!!!',sep='…')
24
![Page 25: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/25.jpg)
Elements of programs:Input statements and numbers the input expression is evaluated as a string
(text) this must be converted into a number if you
are going to do math text (strings) and numbers are handled differently
by the computer – more about this later! eval() is a Python function that converts a
string into a number eval(“20”) -> 20
25
![Page 26: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/26.jpg)
Elements of programs:Input statements and numbers Useful example using eval…
# algorithm to calculate BMI, using input
height = input("Type in your height: ")
weight = input("Type in your weight: ")
height=eval(height) #change a string into a number
weight=eval(weight) #change a string into a number
BMI = weight/(height*height) #calculates BMI
print("Body mass index = ",BMI)
26
![Page 27: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/27.jpg)
Saving programs to file If you type them in directly, programs
definition are lost when you quit the shell
So, we usually type programs into a separate file, called a module, or script
#file: greet3.pyperson = “Bob”
threeTimes = person*3print("Hello", threeTimes)print("Oops.... ”)
27
![Page 28: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/28.jpg)
Where to use comments Brief description, author, date at top of
function. Brief description of purpose of each
method (if more than one). Short explanation of non-obvious parts of
code within methods.
#My very first program#Author: Michelle Kuttel#date 21/2/2012
28
![Page 29: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/29.jpg)
Simultaneous assignment Can assign several values at once:personA, personB, personC =“Tom”, “Dick”, “Harry”
x,y = 10,20
sum, diff = x+y, x-y
x,y = y,x
29
![Page 30: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/30.jpg)
Checkpoint: What is the output of this code?
x,y = 10,20
x,y = y,x
print(x,y)
30
![Page 31: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/31.jpg)
Python first functiondef hello():
print(“Hello”)
print(“I love CSC1015F”)
Defines a new function called hello Indentations show that the lines below
hello belong to the function Invoked like this:hello()
31
![Page 32: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/32.jpg)
Python second functiondef hello2():
name = input("What is your name? ")
print("Hellooooo", name*3, end='!!!',sep='…')
32
![Page 33: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/33.jpg)
Parameters Functions can have changeable
parameters (or arguments) that are placed within parenthesis. E.g.
def greet(person):
print(“hello”, person)
print(“How are you?”)
n = input(”What is your name?”)
greet(n)
33
![Page 34: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/34.jpg)
Checkpoint
34
![Page 35: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/35.jpg)
Checkpoint: What is the exact output of this code?
# function checkpoint OneTwoThree.py
def A(word1, word2, word3):
print(word3,word2,word1,sep='...',end='STOP')
A("green","orange","red")
35
![Page 36: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/36.jpg)
Checkpoint: What is the exact output of this code?
# function checkpoint OneTwoThree.py
def A(word1, word2, word3):
print(word3,word2,word1,sep='...',end='STOP')
print(“Testing…”)
x,y,z="green","orange","red"
A(x,y,z)
A(z*2,y*2,x*2)
36
![Page 37: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/37.jpg)
Example program: Miles-to-kilometres converter You’re visiting the USA and distances are all
quoted in miles I mile = 1.61 km
Write a program to do this conversion
Algorithm conforms to a standard pattern: Input, Process, Output (IPO) Ask user for input in miles, convert to kilometers,
output result by displaying it on the screen
37
![Page 38: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/38.jpg)
Algorithms and Pseudocode Pseudocode is just precise English that
describes what a program does Communicate the algorithm without all the
details e.g.
38
![Page 39: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/39.jpg)
Algorithms and Pseudocode Pseudocode is just precise English that
describes what a program does Communicates the algorithm without all the
details e.g.
Input the distance in miles (call it miles)Calculate kilometres as miles x 1.61Output kilometres
The next step is to convert this into a Python program39
![Page 40: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/40.jpg)
Miles.py#miles.py# A program to convert miles to kilometres# by: Michelle Kuttel
def main(): miles = eval(input("What is the distance in miles?
")) kilometres = miles* 1.61 print("The distance in kilometres
is",kilometres,"km.")
main()40
![Page 41: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/41.jpg)
Breakdown of Miles.py#miles.py
# A program to convert miles to kilometres
# by: Michelle Kuttel
def main(): miles = eval(input("What is the distance in miles? "))
kilometres = miles* 1.61
print("The distance in kilometres is",kilometres,"km.")
main()
Defines a function called main (which has a special meaning)41
![Page 42: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/42.jpg)
Breakdown of Miles.py#miles.py
# A program to convert miles to kilometres
# by: Michelle Kuttel
def main():
miles = eval(input("What is the distance in miles? "))
kilometres = miles* 1.61
print("The distance in kilometres is",kilometres,"km.")
main()
42
![Page 43: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/43.jpg)
Breakdown of Miles.pymiles = eval(input("What is the distance in
miles? "))
eval() is a Python function that converts a string into a number eval(“20”) -> 20
for now, think of a string as a word or sentence (more on strings later)
the input statement treats whatever the user types as an expression to be evaluated43
![Page 44: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/44.jpg)
Breakdown of Miles.py#miles.py
# A program to convert miles to kilometres
# by: Michelle Kuttel
def main():
miles = eval(input("What is the distance in miles? "))
kilometres = miles* 1.61 print("The distance in kilometres is",kilometres,"km.")
main()
An expression which assigns a value to the variable kilometres using the multiplication operator44
![Page 45: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/45.jpg)
Breakdown of Miles.py#miles.py
# A program to convert miles to kilometres
# by: Michelle Kuttel
def main():
miles = eval(input("What is the distance in miles? "))
kilometres = miles* 1.61
print("The distance in kilometres is",kilometres,"km.")
main()
An output statement
45
![Page 46: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/46.jpg)
Breakdown of Miles.py#miles.py
# A program to convert miles to kilometres
# by: Michelle Kuttel
def main():
miles = eval(input("What is the distance in miles? "))
kilometres = miles* 1.61
print("The distance in kilometres is",kilometres,"km.")
main()
Calls the main method automatically when this module is run46
![Page 47: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/47.jpg)
More Python statements in future lectures…
We also also have statements to:
Perform selections
Iterate (loop)
47
![Page 48: CSC1015F – Python Chapter2](https://reader030.fdocuments.in/reader030/viewer/2022012922/56814f32550346895dbcc4b2/html5/thumbnails/48.jpg)
This work is licensed under a Creative Commons Attribution-ShareAlike 2.5 South Africa License.
48