APS106 - Lecture notes PDF

Title APS106 - Lecture notes
Author HXVNTER XII
Course Fundamentals of Computer Programming
Institution University of Toronto
Pages 20
File Size 567.7 KB
File Type PDF
Total Downloads 44
Total Views 151

Summary

Lecture notes for Prof. Beck for python, APS106 in 2020. ...


Description

Week 2 - Lecture 1: Functions, Inputs, Outputs Source code: ● The human-readable form. ● Translated into machine language: Translation is done by compilers/interpreters/ assemblers ○ Compilers translate source code into either object code or machine code (object code needs further processing to become machine code). ■ Machine code consists of a CPU's native instructions and it is ready for execution. ○ Interpreters execute source code line-by-line decoding each instruction and carrying out its prescribed behaviour. (Python) Syntax: ● refers to its structure, the set of correct “sentences” in that language. ●

Syntax Error: Because of something you typed, your statement is meaningless. ○ Example: missing second bracket, 12 = x, 3+* 5

Semantic: ● Gives the meaning of every correct construction. ●

Semantic Error: Follows the Python syntax rules but it is something that Python can't do. ○ For example: a division by zero, multiplying a string by an integer.

Logical: ● Logical Error: When you code follows the syntactic rules and Python can do everything you ask it to but what you are asking it is wrong. The logic of your code is wrong. ○ Example: Celsius equation is wrong, gives wrong output.

Programming “grammar” -> parsed -> syntax tree ● A syntax tree is used by a compiler and/or interpreter to produce machine code, which is used to execute the program. Backus-Naur Form(BNF): ● Main notation used to represent grammars ○ ::=(|[list_of_things])* ■ is defined as or, optionally, any of a list of things, all of this possibly repeated several times. Function: ● A block of organized (reusable) code that is used to perform an activity.





Python has built-in functions, but programmers can also create their own userdefined functions. General form of a function call: function_name(arguments) ○ Execution: ■ 1.Evaluate the arguments(the values passed to the function) ■ 2.Call the function passing in the arguments

Types of Functions: ● Help: To get information about a particular function, call help and pass the function as the argument. ●

Print: Python has a built-in function named print for displaying messages to the user. ○ Each pair of arguments is separated by a comma and a space is inserted between them in display ○ Print doesn’t allow any styling of the output: no colors, no italics, no bold face. All output is plain text. ○ The general form of a print function call: print(arguments) ○ Example: print(“hello”)

Triple quote strings: ● Can span multiple times ○ Example: print(‘’’Zero to a hunned’’’) Input: ● Python has a built-in function named input for reading text from the user ○ You can see a list by using the function dir: dir(__builtin__) ● The general form of an input function call: input(argument) ● Argument is the prompt, and can be omitted ● The value returned by the input function is always a string Importing Functions ● Groups of functions are saved in modules ● Modules need to be imported before they can be used

● ●

The general form of an import statement is: importmodule_name To access a function within a module: module_name.function_name ○ The dot is an operator: ■ 1.lookuptheobject that the variable to the left of the dot refers to and, in that object ■ 2. Find the name that occurs to the right of the dot ○ Example: math.sqrt(16), math.log(100)

Week 2 - Lecture 2: Functions, Inputs, Outputs Defining Functions:

● ● ● ● ●

Def: a keyword indicating a function definition Function_name: the function name Parameters: the parameter(s) of the function, 0 or more,separated by a comma. A parameter is a variable whose value will be supplied when the function is called Body: 1 or more statements, often ending with a return statement The general form of a function definition: ○ deffunction_name(parameters): ['''function_docstring'''] function_body [return[expression]]

Function body: ● consists of one or more statements ● The code block/body within every function starts with a colon (:) and is indented. ● The first statement of a function can be an optional statement - the documentation string of the function, a.k.a. the docstring. ● The statement return[expression] exits if a function is passing back a value to the caller. Using Functions - Terminology: ● Argument: a value given to a function ● Pass: to provide to a function ● Call: ask Python to execute a function ● Return: pass back a value Function Design Recipe:



6 steps to consider when designing a function: 1.Examples(what does the function do?) Ex: celcius = (fahrenheit - 32) * 5 / 9 float Return the celcius degrees Equivalent to fahrenheit degrees. ‘’’ 5.Body (write the code) One or more statements of code used to generate the desired outputs. The return statement is usually the very last line in body Ex: celsius = (fahrenheit - 32) * 5 / 9 return celsius 6.Test(verify the function on examples)

Engineering Design Process: 1.) Define the Problem 2.) Define Test Cases 3.) Generate Many Creative Solutions a.) Algorithm Plan b.) Programming Plan 4.) Select a Solution 5.) Implement the solution 6.) Perform final testing Week 2 Practice Problem on Week 2 Lecture 3

Week 3 - Lecture 1: Objects and Methods Objects(Instances): ● For example, a song that has specific lyrics, beats per minute, etc., or a specific game of a particular sport... ● Everything is an object: Python keeps track of every value, variable, function, etc., as an object. ● There is a function that you can call to confirm this: >>>isinstance(4,object) True

>>>isinstance(“Hello”,object) True Methods: ● A function available for a specific object, because of its type. ● Each Python object has certain functions that can only be applied to that object, these functions are referred to as methods. ● The general form for calling a method is: object_name.method_name(arguments) ● Since methods are applied to objects, we need to provide the object name with a “.”before the method name. Advantages of using Methods: ● Provides another way to structure/organize your code. ● When you call a method the object data is passed implicitly(skips passing as parameters) ● Generally easier to understand and maintain the code. Classes Definition Syntax: ● It is a compound statement (Python Grammar) Class Object: ● When a class is defined, a class object is created. ● Class objects support two kinds of operations: ○ Attribute reference ○ Class instantiation Attribute references: ● It uses the standard syntax used for all attribute references in Python. object.attribute_name my_first_class.msg_len returns an integer object. My_first_class.my_function returns a function object. Class instantiation: ● It uses the function notation. x = my_first_class() creates a new instance of the class my_first_class, an instance object, and assigns this object to the variable named x. Instance objects: ● Only support attribute references ● There are two kinds of valid instance attribute names: ○ Data attributes ○ Methods ● Data attribute: details in week 9 and 10

Method Objects: ● Methods are bound function objects. Methods are always bound to an instance object (eg. an instance of a user-defined class)

Strings: ● Backslash (\): You can include a special character (like ' or ") by using the escape character: \. Using \ means "consider the next character as part of the string, not a special character." ○ Used to put a “ in a string. ○ To put a backslash in a string, put two. Two backslashes outputs one, four backslashes outputs two, etc. ● Escape sequence:







○ String operators: ○ Strings have operators like +,*,etc… ○ - and / are not defined. ○ Example: s = "The" + "beginning" print(s) Thebeginning s = "the" * 4 print(s) Thethethethe Find function: Finds where a letter is located on a string.

Converting between int, str, and float: ● Str: The builtin function str takes any value and returns a string representation of that

value.





print(str(4.27)) 4.27 Int: If function int is called with a string that contains anything other than digits, a ValueError happens. x = int("123") print(x + 1) 124 Float: If function float is called with a string that can't be converted, a ValueError happens. print(float("435")) 435.0

Week 3 - Lecture 2: Strings and String Methods String indexing and slicing: ● Index: A position within the string. ○ Positive indices count from the left-hand side with the first character at index 0, the second at index 1, and so on. ○ Negative indices count from the right-hand side with the last character at index -1, the second last at index -2, and so on. ●

The first character of the string is at index 0 and can be accessed using this bracket notation: s = "Learn to Program" print(s[0]) L print(s[3] + s[6]) rt print(s[6:len(s)]) to Program

String Methods: ● Dir function: To find out which methods are inside strings. ● Upper and lower method: Return a copy of the string converted to upper/lowercase. print(white_rabbit.lower()) ● Find method: Finds where a string is located str1.find(str2 ● Replace method: returns a copy of the string in which the occurrences of old have been replaced with new, optionally restricting the number of replacements to count. (If count is not specified, then all of them are replaced.

replace(old,new,count) Modifying strings: ● Remember we cannot modify strings. We can only create a new string and have change where the original variable points to. ○ A way to “modify”: s = "Learn to Program" s = s[:5] + "ed" + s[5:] print(s) Learned to Program Week 3 Practice Problem on Week 3 Lecture 3

Week 4 - Lecture 1: Booleans, conditionals, and if-statements Booleans: ● The Python type bool has only two possible values: True and False. ● There real power of bool comes when they are combined with comparison operators.



Difference between one equal sign and two equal signs: ● = : An assignment. You assign the value of the thing on the right-hand side (rhs) to the thing on the left-hand side (lhs). ● == : A comparison. It compares the value of the thing on the rhs to the value of the thing on the lhs and returns True if they are the same and False if they are different. If statements: ● if statements can be used to control which instructions are executed by creating a “branch” in the code. ● if statement evaluates a Boolean expression, and if it is True, then it runs the code under it, otherwise it skips it. if condition: block



if statements are always followed by a colon (:), this is how Python knows you are going to create a new block of code. Indenting four spaces tells Python what lines of code are in that block. You must indent a block!!



The general form of an if-else is: if condition: block1 else: block2

Logical operators: ● There are also three logical operators that allow us to combine Boolean values to produce Boolean values: and, or, and not. ○ And operator: evaluates to True if and only if both of its operands are True.



■ Or operator: evaluates to True if one (or both) of its operands are True.



■ Not operator: evaluates to True if and only if its operand is False.



■ Example: grade1 = 80 grade2 = 40 passed = grade1 >= 50 and grade2 >= 50

failed = True if not passed: print("Failed") else: print("Passed") ○



Or operator: evaluates to True if and only if at least one operand is True. ■ So if the first operand is True, it is unnecessary to look at the second operand: it is already known that the expression will produce True. ■ If the first operand of or evaluates to True, it doesn't even look at the second one.

Order of Precedence for Logical Operators ○ The order of precedence for logical operators is: not, and, then or. ○ We can override precedence using parentheses and parentheses can also be added to make things easier to read and understand. For example, the not operator is applied before the or operator in the following code.

Exclamation mark: ● ! : means "not equal to" and is a logical comparison. ○ Break down the logical expression here: 2 and 1 - 2 != 3 2 and -1 != 3 2 and True True. Boolean as a subtype of integer: ● bool is also a subtype of int, where True == 1 and False == 0. print(True + 1) 2 print(False - 1) -1 print((False + 3) * 4 - True) 11 print(True) print(int(True)) True 1

Week 4 - Lecture 2: Advanced comparisons, else & elif, nested ifs String Comparisons: ● The equality and inequality operators can be applied to strings.

print('a' == 'a') True print('ant' == 'ace') False print('a' != 'b') True ●

Each character in a string is actually represented by integers. ○ For example in ASCII the characters ‘a’ and ‘w’ are encoded as 97 and 119 respectively. The comparison 'a' > 'w' would translates to 97 > 119 to give the result False. ○ Capitalization matters, and capital letters are less than lowercase letters.



Ord function: To obtain the ASCII (integer) representation, we can use the built-in function ord(). print(ord("a")) 97



Chr function: To convert from the ASCII integer representation back to a string, we can use the built-in function chr(). print(chr(97)) A



'ord' and 'chr' are, of course, inverses of each other (i.e., like addition and subtraction). print(ord(chr(97))) 97

Testing for substrings: ● Operator in: checks whether a string appears anywhere inside another one (that is, whether a string is a substring of another). print("c" in "aeiou") False Summary table:

Most general form of if statements: if expression1: body1 elif expression2: body2 elif expression3: body3 . . . else:

bodyN ●

Elif: stands for "else if", so this forms a chain of conditions. To execute an if-statement: ○ evaluate each expression in order from top to bottom ■ If an expression produces True, execute the body of that clause and then skip the rest. ■ If there is an else, and none of the expressions produce True, then execute the body of the else.

Difference between if-elif to if-if: ● If-elif: If the if is not true it goes to the elif. If it produces true in if, it ignores elif. ● If-if: it produces the second if whether the first if is true or not. Nested ifs: ● It is possible to place an if statement within the body of another if statement. precipitation = True temperature = -5 if precipitation: if temperature > 0: print("Bring your umbrella") else: print("Wear your snow boots") Wear your snow boots ●

The message 'Bring your umbrella!' is printed only when both of the if statement conditions are True. The message 'Wear your snow boots and winter coat!' is printed only when the outer if condition is True, but the inner if condition is False.

Week 4 Practice Problem on Week 4 Lecture 3

Week 5 - Lecture 1: Lists Lists ● ●



One way to store these collections of data is using Python's type list. The general form of a list is: [element1, element2, ..., elementN] grades = [80, 90, 70] print(grades[0]) 80 The in operator can also be applied to check whether a value is an item in a list.

print(90 in grades) True ●

Lists can also mix elements of different types. For example, a street address can be represented by a list of [int, str]: street_address = [10, 'Main Street']

Built in functions for lists: ● Several of Python's built-in functions can be applied to lists, including: ●

len(list): return the number of elements in list (i.e. the length) print(len(grades)) 3



min(list): return the value of the smallest element in list. print(grades) print(min(grades)) [80, 90, 70] 70



max(list): return the value of the largest element in list. print(max(grades)) 90



sum(list): return the sum of elements of list (list items must be numeric). print(sum(grades)) 240

Nested Lists: ● Lists can contain items of any type, including other lists! These are called nested lists. grades = [['Assignment 1', 80], ['Assignment 2', 90], ['Assignment 3', 70]] print(grades) print(grades[0]) [['Assignment 1', 80], ['Assignment 2', 90], ['Assignment 3', 70]] ['Assignment 1', 80] ●

To access a nested item, first select the sublist, and then treat the result as a regular list. ○ For example, to access 'Assignment 1', we can first get the sublist and then use it as we would a regular list: sublist = grades[0] print(sublist) ['Assignment 1', 80] print(sublist[0]) Assignment 1

print(sublist[1]) 80 ○

Both sublist and grades[0] contain the memory address of the ['Assignment 1', 80] list. We can access the items directly like this: print(grades[0][0]) Assignment 1 print(grades[1][0]) Assignment 2

Mutability ● We say that lists are "mutable": they can be modified. ○ All the other types we have seen so far (str, int, float and bool) are "immutable": they cannot be modified. classes = ['chem', 'bio', 'cs', 'eng'] print(classes) classes[2] = 'math' print(classes) ['chem', 'bio', 'cs', 'eng'] ['chem', 'bio', 'math', 'eng'] classes[1] = [1,2,3] print(classes) [17, [1, 2, 3], 'math', 'eng'] Aliasing: ● Aliases: When two variables refer to the same objects ● If one list is modified, its aliases are also modified. In fact, there is only one list. List(): ● A list "constructor". It will construct a new list based on the passed sequence. ○ Using the built-in function id() we can track what happens to the memory as we create lists. ● This can be used to modify a list and still keeping the original version. lst_b = lst_a # make an alias lst_c = list(lst_a) # make a copy! print(id(lst_a)) print(id(lst_b)) print(id(lst_c)) 4456744392 4456744392 4456746952

lst_c[0] = 342 print(lst_a) print(lst_b) print(lst_c) [1, 2, 3, 4] [1, 2, 3, 4] [342, 2, 3, 4] Modifying Lists: ● list.append(object): Append object to the end of list. Do not use to add more than one (list). colors = ['yellow', 'blue'] colors.append('red') print(colors) ['yellow', 'blue', 'red'] ●

list.extend(list): Append the items in the list parameter to the list. colors.extend(['pink', 'green']) print(colors) ['yellow', 'blue', 'red', 'pink', 'green']



list.pop(index): Remove the item at the end of the list; optional index to remove from anywhere. c = colors.pop(1) print(colors) print(c) ['yellow', 'red', 'pink'] Blue



list.remove(object): Remove the first occurrence of the object; error if not there. c = colors.remove('red') print(colors) print(c) ['yellow', 'pink'] None



list.reverse(): Reverse the list. grades = [95, 65, 75, 85] grades.reverse() print(grades) [85, 75, 65, 95]



list.sort(): Sort the list from smallest to largest.

grades.sort() print(grades) [65, 75, 85, 95] ●

list.insert(int, object): Insert object at the given index, moving items to make room. grades.insert(3, 80) print(grades) [65, 75, 85, 80, 95]

Getting Information from Lists: ● list.count(object): Return the number of times object occurs in list. letters = ['a', 'a', 'b', 'c'] print(letters.count('a')) 2 ●

list.index(object): Return the index of the first occurrence of object; error if not there. print(letters.index('a')) 0

Week 5 - Lecture 2: Loops For Loops: ● The general form of a for loop is: for item in iterable: Body ○

Where "iterable" can be a set of items such as characters, strings, numbers, lists, etc.



Similar to if statements, there are two things to note here: ○ There must be a colon (:) at the end of the for statement. ○ The body must be indented.



To concatenate nu...


Similar Free PDFs