0% found this document useful (0 votes)
713 views32 pages

CMPUT 175 Lecture #1

This document provides an overview of the CMPUT 175 course. It includes a review of programming concepts learned in CMPUT 174 such as variables, data types, control structures, functions, files, recursion, and object-oriented programming. The document discusses programming fundamentals like the definition of a program, inputs and outputs, and interpreters vs compilers. It also covers Python topics such as values and variables, naming conventions, references vs copies, and data types and operators.

Uploaded by

deep81204
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
713 views32 pages

CMPUT 175 Lecture #1

This document provides an overview of the CMPUT 175 course. It includes a review of programming concepts learned in CMPUT 174 such as variables, data types, control structures, functions, files, recursion, and object-oriented programming. The document discusses programming fundamentals like the definition of a program, inputs and outputs, and interpreters vs compilers. It also covers Python topics such as values and variables, naming conventions, references vs copies, and data types and operators.

Uploaded by

deep81204
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CMPUT 175

Introduction to Foundations
of Computing
Crash course on Python
Quick revision of CMPUT 174 material

You should view the vignettes:


Values and types Tuples and lists
Variables Sets
If-statements Files
Pre-test Post-test For-loops Dictionaries
While-loops String Formatting
January 10, 2024 © Osmar R. Zaïane : University of Alberta 1
Objectives
Revision of Programming concepts learned in
CMPUT 174
Review of Basic Python from CMPUT 174
What is programming
Variables and containers
Control structures
Functions
Files
Recursion
Object orientation

January 10, 2024 © Osmar R. Zaïane : University of Alberta 2


Programming
A program is a sequence of instructions that specifies
how to perform a computation. Instructions are in a
programming language or machine code.
Access data (Input); process data; provide results
(Output)
Process data: basic operations; conditional operations,
repeated operations
Line by line 10100100100
or portions Interpreter 10010001001

Program Step-by-step executor


source
whole
code program
10100
011101
Compiler 001001

Byte code or
machine code
January 10, 2024 © Osmar R. Zaïane : University of Alberta 3
Programming
A program is a sequence of instructions that specifies
how to perform a computation. Instructions are in a
programming language or machine code.
Access data (Input); Process data; Provide results
(Output)
Process data: basic operations; conditional operations,
repeated operations
Kind of Input

variable

January 10, 2024 © Osmar R. Zaïane : University of Alberta 4


Programming
A program is a sequence of instructions that specifies
how to perform a computation. Instructions are in a
programming language or machine code.
Access data (Input); Process data; Provide results
(Output)
Process data: basic operations; conditional operations,
repeated operations

January 10, 2024 © Osmar R. Zaïane : University of Alberta 5


Object Orientation
Classes
Class

Objects

Class
One
Methods of Invoking a method for Object
a class an Object (instance) instance
(behaviour) from the
Class

January 10, 2024 © Osmar R. Zaïane : University of Alberta 6


Values and Variables
There are values stored in main memory
Values have types:
String: "this is a string"
Integer: 175
Float: 3.1415926535897931
Boolean: True
List: ["CMPUT", 175, 91, ‘A’, 6]
etc.
Values can be stored, accessed and manipulated via
variables
Variables are names referring to values
Python is dynamic: variables exist automatically in the first
scope where they are assigned.
January 10, 2024 © Osmar R. Zaïane : University of Alberta 7
Variable Names
In Python variable names should start with a letter
Variable names can be arbitrarily long and could
contain letters and numbers as well as the
underscore “_”
Python variable names are case sensitive
Myvariable is different from myVariable
Python keywords can not be used as variable
names and del from not while
as elif global or with
assert else if pass yield
break except import print
class exec in raise
continue finally is return
def for lambda try

January 10, 2024 © Osmar R. Zaïane : University of Alberta 8


More about Variable Names
a = b * c vs. increase = salary * percent

Longer identifiers may be preferred: more


informative and less cryptic.
Longer identifiers add clutter making it difficult to
read code.
Shorter identifiers may be preferred as more
expedient to type and perhaps easier to read code.
Too short of an identifier makes it difficult to
understand and very difficult to uniquely distinguish
using automated search and replace tools.
January 10, 2024 9
More about Variable Names
There are many naming convention for
naming variables
You can use multi-word identifiers
hyphenated
weekly_pay = hours_worked * pay_rate
snake_case
Camel Case / Medial Capitals
weeklyPay = hoursWorked * payRate Lower
camel case

WeeklyPay = HoursWorked * PayRate Upper


camel case
PascalCase
January 10, 2024 eBay, iPhone, DreamWorks, WordPerfect, FedEx 10
Variables are references
value
myVar = “CMPUT 174” myVar
“CMPUT 174”

myVar = “CMPUT 175” myVar


“CMPUT 174”

myVar2 = “CMPUT 175”


myVar2
“CMPUT 175”

A value is
assigned to a What happens to the first
variable value "CMPUT 174"? Garbage
collector
January 10, 2024 © Osmar R. Zaïane : University of Alberta 11
Aliasing
x=y does not make a copy of y
x=y makes x reference the same object y references
a a
>>>a=[1,2,3] >>>a=[1,2,3]
>>>b=[1,2,3] [1,2,3]
>>>b=a
>>>a is b [1,2,3]
b >>>a is b b
False [1,2,3] True
Reference
lost after
assignment
a
Beware >>> a=1; b=a
1
>>> a=[1,2,3]; b=a >>> print(b)
>>> a.append(4); 1 b
>>> print(b) >>> a=a+1; print(b) 2
[1,2,3,4] 1 New object
created
January 10, 2024 © Osmar R. Zaïane : University of Alberta 12
Aliasing can cause problems
Use aliasing
firstVar only as a second
firstVar= “CMPUT” name for a
secondVar=firstVar “CMPUT” mutable object.
secondVar

firstVar=firstVar+ “ 175” “CMPUT 175” New string object created


firstVar

“CMPUT”
secondVar

January 10, 2024 © Osmar R. Zaïane : University of Alberta 13


Types and Operators
Integer and Float (int, float, long, complex)
Operators +, -, *, /, //, %, and ** perform addition,
subtraction, multiplication, division, integer division,
modulo and exponentiation respectively
10+23 33
67-5 62
3*60+20 200
210/60 3.5
7//3 2
Conversion functions:
7%3 1 abs(x)  absolute value of x
2**10 1024 int(x)  converts x into integer
float(x)  converts x into floating point
str(x)  converts x into a string
14
January 10, 2024 © Osmar R. Zaïane : University of Alberta
Types and Operators
Boolean
Operators and, or, not for conjunction, disjunction and
negation
Comparison operators
== equality >>> False or True
!= not equal True
< less than >>> not (False or True)
> greater than False
<= less than or equal >>> 7==2013
>= greater than or equal False
>>> 7!=2013
True
>>> (2013>=7) and (2013<=2020)
True

15
January 10, 2024 © Osmar R. Zaïane : University of Alberta
Types and Operators
String is a sequence of characters [immutable]
Values of strings are written using quotations
"CMPUT"
Characters are indexed starting from 0.
myVar="CMPUT"; myVar[2] returns 'P'
Operator + performs concatenation
"ABC"+"CDE" results into "ABCCDE" >>> myVar="CMPUT"
>>> myVar.lower()
Sequence operations 'cmput'
count(item) center(w,char) >>> myVar.find('P')
2
find(item) ljust(w) >>> myVar.split('P')
split(char) rjust(w) ['CM', 'UT']
lower() strip() >>> " CMPUT ".strip()
'CMPUT'
upper() replace(old,new,max)
16
January 10, 2024 © Osmar R. Zaïane : University of Alberta
Types and Operators
List is a sequence of values of any type [mutable]
Elements in a list are numbered starting from 0
Accessing an element of a list via its index k[index]
Operators + and * concatenate and repeat sequences
respectively
[1,2,3] + [4,5,6] results into [1,2,3,4,5,6]
[1,2,3] * 3 results into [1,2,3,1,2,3,1,2,3]
Operator : slices in a list
k=[1,2,3,4,5,6]; k[2:4] results into [3,4]
k=[1,2,3,4,5,6]; k[2:] results into [3,4,5,6]
k=[1,2,3,4,5,6]; k[:4] results into [1,2,3,4]
Membership operator in asks whether an item is in a list
3 in [1,2,3,4,5,6] returns True
Length of a list with operator len
len([1,2,3,4,5,6]) returns 6 17
January 10, 2024 © Osmar R. Zaïane : University of Alberta
Methods on Lists
append(item) adds an item at end of list
L.remove(4)
insert(i,item) inserts item at ith position of list print(L)
pop() removes and returns last item in list [1,3]
pop(i) removes and returns ith element in list L.reverse()
print(L)
del(i) removes i element in list
th
[3,1]
remove(item) removes 1st occurrence of item
L=[1,2,3,4] L.insert(3,65) L.pop()
sort() modifies listL.append(175)
to be sorted [1,2,3,65,4,175] 175
reverse() modifies[1,2,3,4,175]
list to be in reverse order
del L[2]
count(item) returns the number ofprint(L)
L.pop(1) occurrences ofprint(L)
item in list
2 [1,3,65,4]
index(item) returns the index of 1st occurrence of[1,3,4]item
January 10, 2024 © Osmar R. Zaïane : University of Alberta 18
Lists and Strings
list >>> list("CMPUT")
['C', 'M', 'P', 'U', 'T']

split >>> "1,2,3,,5".split(',')


['1', '2', '3', '', '5']
join >>> "the cat sat on the mat".split()
['the', 'cat', 'sat', 'on', 'the', 'mat']
>>> "the,cat,sat,on,the,mat".split(‘,’,3)
['the', 'cat', 'sat', 'on,the,mat']

>>> ' '.join(['1', '2', '3', '4', '5'])


'1 2 3 4 5'
>>> ''.join(['1', '2', '3', '4', '5'])
'12345'
>>> '**'.join(['1', '2', '3', '4', '5'])
'1**2**3**4**5'

January 10, 2024 © Osmar R. Zaïane : University of Alberta 19


Tuples and Sets
List is mutable heterogeneous sequence of values
[2, True, "cat", [1,2,3], 3.5]
A tuple is an immutable list (2, True, "cat", [1,2,3], 3.5)
Like for strings, you would get an error if you try to
change the content of a tuple.
A set is an unordered collection of immutable objects
{2, True, "cat", 3.5}
A set does not support indexing (is not sequential)
Sets support methods such as union (|), intersection (&),
issubset (<=) and difference (-), as well as add(item),
remove(item), clear() and pop().

January 10, 2024 © Osmar R. Zaïane : University of Alberta 20


Dictionaries
Dictionaries are collections of associated pairs of items
A pair consists of a key and a value (key: value)
Capitals={"AB":"Edmonton","BC":"Victoria","ON":"Toronto"}
Values are accessed via their keys Capitals["AB"]
Dictionaries are mutable
New elements can be added Capitals["QC"]="Quebec"
Elements in a dictionary do not have an order
keys() returns a list of keys of dictionary
values() returns a list of values of dictionary
items() returns a list of pairs (key, value) of dictionary
in returns True or False whether the key exists
BC:Victoria AB:Edmonton QC:Quebec ON:Toronto
January 10, 2024 © Osmar R. Zaïane : University of Alberta 21
How to Imagine
Dictionaries
BC:Victoria AB:Edmonton QC:Quebec ON:Toronto

0 1 2 3
Array Victoria Edmonton Quebec Toronto
D[1] Index
BC AB QC ON
Dictionary Victoria Edmonton Quebec Toronto
D["AB"]

January 10, 2024 © Osmar R. Zaïane : University of Alberta 22


Use of Dictionaries
A record A key indexed collection
prices = {
aStudent = {
"AB66": 12.5,
"firstname": "Alphonse",
"XY12": 45.99,
"lastname": "Areola",
"BZ43": 34.97
"age": 28
}
}
prices["XY12"] 45.99
aStudent["firstname"] "Alphonse"
studentMarks = {
"12345": "88;95;75;94;100;89.5;91",
"12987": "67;45.5;;86;;76;79",
aStudent["age"] = 29
"12558": "85.5;86;91;72;78;83;90",
aStudent["heightNweight"] = [1.95, 88]
"12257": "69;55;78;86;68;75;79"
}
aStudent = {
"firstname": "Alphonse", studentMarks["12987"]
"lastname": "Areola",
"age": 29, "67;45.5;;86;;76;79"
"heightNweight": [1.95, 88]
} The key in a dictionary is unique.
You cannot duplicate the key.
January 10, 2024 © Osmar R. Zaïane : University of Alberta 23
Input
var=input(“Please enter a string”)
Value entered is a string. Explicit type
conversion required

>>> a=input('Enter number ')


int() Enter number 34
float() >>> b=a*2; print(b)
3434
>>> a=float(a);b=a*2;print(b)
68.0

January 10, 2024 © Osmar R. Zaïane : University of Alberta 24


Output
print("CMPUT 175")
>>> print("CMPUT 175")
CMPUT 175
>>> print("CMPUT","175")
CMPUT 175
>>> print("CMPUT"+"175")
CMPUT175
>>> print("CMPUT","175", sep="-")
CMPUT-175
>>> print("CMPUT","175", end="-")
CMPUT 175->>>

print("the class of",stdName,"is",classNumb)


January 10, 2024 © Osmar R. Zaïane : University of Alberta 25
String Formatting
print(string expression % (values))
print("%s is %d years old."% (sName,age))
%d or %i Integer
%u unsigned integer
%f floating point
%c single character
%s string
>>> user = 'username'
>>> host = 'host'
>>> '%s@%s' % (user, host)
'username@host'
January 10, 2024 © Osmar R. Zaïane : University of Alberta 26
String Formatting
print("The rental costs $%5.2f"%(price))
Format modifiers
Number %15d field width (right-justified)
- %-15d left-justified in field width
0 %015d pre-fill with leading zeros
. %15.2f decimal point
>>> print ("%d"%(40))
40
You can also use format() function >>> print ("%10d"%(40))
40
{:05.2f} instead of %05.2f >>> print ("%010d"%(40))
a=23; b=100 0000000040
“My numbers are {1} and {0}”.format(a, b)
My numbers are 100 and 23
January 10, 2024 © Osmar R. Zaïane : University of Alberta 27
F-String Formatting
python = 3.6
| 3.6|
print(f"|{python:10}|") |3.6 |
| 3.6|
print(f"|{python:<10}|") | 3.6 |
|=======3.6|
print(f"|{python:^10}|") 175
175.28
print(f"|{python:=>10}|") +175.279

number=175; variable=175.2792
print(f"{number:10d}") >>> user = 'username'

print(f"{variable:.2f}") >>> f'{user}@{host}'


>>> host = 'host'

'username@host'
print(f"{variable:+.3f}")
January 10, 2024 © Osmar R. Zaïane : University of Alberta 28
Control structures:
Conditionals
if condition: if condition:
statements statements
elif condition:
statements
if condition: elif condition:
statements statements …
else: else:
statements statements

January 10, 2024 © Osmar R. Zaïane : University of Alberta 29


Control structures: Loops
while condition:
statements

for var in sequence:


statements

continue

break
January 10, 2024 © Osmar R. Zaïane : University of Alberta 30
with open(filename, "r") as f:
Files f.read()
File closed automatically at the end of “with”

f = open(filename, "r") #opens the file for reading


f.read([byteCount]); f.readline()
f.readlines() #returns a list where elements are lines
f.write(string) #writes string in file
f.close() #closes the file
f.tell() #returns the current position in file
f.seek([offset[,from]) #sets the file’s current position at offset

w=
Read only  "r" r=
Read and write  "r+"
Write only  "w" a=
Append to the end of file  "a"
Append a "b" for binary file
January 10, 2024 © Osmar R. Zaïane : University of Alberta 31
Functions and Procedures
def name(arg1,arg2,…):
statements

return # return from procedure


return expression # return from function

>>> def sqr(x): >>> def hello(x):


... return x**2 ... print ("Hello %s"%(x))
... ... return
>>> y= sqr(6) ...
>>> print (y) >>> hello("CMPUT175")
36 Hello CMPUT175
A function returns a value. A procedure executes commands.
Both a function or a procedure can be called multiple times in a program.

January 10, 2024 © Osmar R. Zaïane : University of Alberta 32

You might also like