CSCA08_SummaryForMidterm.docx

18 Pages
586 Views
Unlock Document

Department
Computer Science
Course
CSCA08H3
Professor
Brian Harrington
Semester
Fall

Description
The Python Keywords: and as assert break class continue def del elif else except exec finally for from global if inport in is lambda nonlocal not or pass raise return try while with yield True False None Variables: Avariable is a name that refers to a value. Note: Don‟t name a variable with Python keywords Local Variables: An assignment statement in a function creates a local variable, or a temporary variable which only exists inside the function and you cannot use it outside. def square(x): y = x * x return y The variable y is a local variable and it only exists while the function square is being executed – we call this its lifetime. When the execution of the function terminates (returns), the local variables are destroyed. Formal parameters are also local and act like local variables. Global Variables Local Scope: All the variables that are defined as local variables. Global Scope Expressions: An expression is a combination of values, variables, operators, and calls to functions Note: Expressions need to be evaluated; if you ask Python to print an expression, the interpreter will evaluate the expression and display the result Statements: Astatement is an instruction that the Python interpreter can execute. e.g.Assignment Statements, While Statements, For Statements, If Statements, Import Statements… Assignment Statements: Create new variables and also give them values to refer to It links a name, on the left hand side of the operator, with a value, on the right. Notes: „n = 17‟reads „n is assigned 17‟ or „n gets the value 17‟ or „n is a reference to the object 17‟ or „n refers to the object 17‟ Don‟t say „n equals 17‟ Assignment Token: The assignment token, „=‟, should not be confused with equality, „==‟. Reassignment and Updating Variables: x = 1 x = 2 # This is reassignment x = 1 # initialize x before updating variables x = x + 1 # This is updating variables # updating a variable by adding 1 is called an increment or bumping a variable # subtracting 1 is called a decrement y = 1 y = y -1 input(): The input function allows the user to provide a prompt string Format: input(„Message that will be shown in the screen‟) Note: the input function returns a string value no matter what the user inputs. Data Type: int (integer), str (string), bool (boolean), float, list, tuple, object Primitive Data Type: int, float and bool are considered to be simple or primitive data types because their values are not composed of any smaller parts. They cannot be broken down. Collection Data Type: Types that are comprised of smaller pieces are called collection data types, like strings and lists. type(): Helps evaluating what class a value falls into. Type Conversion Functions: The functions int(), float() and str() will (attempt to) convert their arguments into types int, float and str respectively. >>> int(3.14) 3 >>> int(3.9999) 3 # int() doesn‟t round to the closest int isinstance(): isinstance(object, class) Return whether an object is an instance of a class or of a subclass thereof. isinstance(object, type) Return whether an object is of a type or not. isinstance(object, tuple) isinstance(x, (A, B, …)) is a shortcut for isinstance(x, A) or isinstance(x, B) or … >>> isinstance(1, int) True Operators: Special tokens that represent computations i.e. +, -, /, //(asterisk -> multiplica, **)(exponentiatio, ( )(parenthesis -> grouping)…… Operands: Values the operator works on ‘/’and ‘//’: The division operator, „/‟, always evaluates to a floating point result; The integer division, „//‟, gives the biggest integer which is smaller than the result e.g. >>> 7 / 4 1.75 >>> 7 // 4 1 >>> 7 % 4 3 ‘%’: The modulus operator, or the remainder operator, works on integers and yields the remainder when the first operand is divided by the second. Note: a == a//b*b + a%b Application: check whether one number is divisible by another – if x % y is 0, x is divisible by y; extract the right-most digit(s) from a number e.g. >>> 123 % 10 3 >>> 123 % 100 23 Order of Operations: the order of evaluation depends on the rules of precedence (the same one in math). i.e. ** > (* = /) > (+ = -) note: the right-most ** gets done first. E.g. 2**3**2 = 2**(3**2) Functions: Anamed sequence of statements that belong together. Function Definitions: def name(parameters): #The header line statements #The code block Parameters: In the def, the parameter list is more specifically known as the formal parameters. When we use the function, we provide values to the formal parameters; these values, called arguments or actual parameters, are passed to the function by the user. Docstrings: The triple-quoted string after the function header used as documentation of functions. It is retrievable at runtime with the expression .__doc__ def my_function(parameters): statements my_function.__doc__ Return Statement: The „return y‟above is a return statement. The return statement not only causes the function to return a value, but it also returns the flow of control back to the place in the program where the function call was made. Note: If we accidentally used print where we mean return, the function will return the value None by default. Function Call: To make a function run we need a function call, or a function invocation. Function calls contain the name of the function to be executed followed by a list of values, called arguments, which are assigned to the parameters in the function definition. name(arguments) Fruitful Functions: Functions that return values. E.g. range(), int(), abs(), max()… abs(): Abuilt-in function for computing the absolute value of a number. max(): Take in more than one arguments (values or expressions) and return the maximum value. >>> max(7, 11, 3*11) 33 Note: max() also works on lists of values. min() The Accumulator Pattern: The pattern of iterating the updating of a variable. def square(x): runningtotal = 0 # we need a variable to remember the ‘running total’ # It should be initialized with a value of zero for counter in range(x): # the iteration is performed x times runningtotal = runningtotal + x # the variable, runningtotal, is referred to the accumulator return runningtotal Problem Solving: Functional Decomposition: The process of breaking a problem into smaller subproblems. Note: functions can call other functions Generalization: An important computer science problem solving technique. E.g. Assume we want to write a function to draw a square. The generalization step is to realize that a square is just a special kind of rectangle. The Flow of Execution: 1 def pow(b, p): # (1) 2 y = b ** p 3 return y 4 5 def square(x): 6 a = pow(x, 2) 7 return a 8 9 n = 5 10 result = square(n) #(2) 11 print(result) #(3) The order in which these lines of code are processed in Python: 1, 5, 9, 10, 6, 2, 3, 7, 11 Note: (1)Python must at least process the function headers before skipping over the functions (2)Python will not execute the functions until after they are called (3)Python must execute the function square before moving on to line 11 TypeError: Type errors most often occur when an expression tries to combine two objects with types that should not be combined. Strings: Empty String: „‟, or “”, is still considered to be a string. It is simply a sequence of zero characters. Strings are Immutable In Python you are not allowed to modify the individual characters in the collection. >>> greeting = „Hello, Cinny‟ >>> greeting[0] = „O‟ # ERROR! TpyeError: „str‟does not support item assignment #You can achieve your goal in this way >>> greeting = „Hello, Cinny‟ >>> new_greeting = „O‟+ greeting[1:] >>> new_greeting „Oello, Cinny‟ Operations on Strings: In general, you cannot perform mathematical operations on strings, even if the strings look like numbers. But the „+‟and „*‟operators do work with strings. Concatenation (+): joining the two operands by linking them end-to-end Note: The space is part of the string and I necessary to produce the space between the concatenated strings yourself >>> „big‟+ „apples‟ „bigapples‟ >>> „big‟+ „ apples‟ „big apples >>> print(„big‟+ „ apples‟) big apples Repetition (*) : one of the operands has to be a string and the other has to be an integer Note: the repetition is done before the concatenation >>> „Go‟* 3 „GoGoGo‟ >>> „You‟+ „ Go‟* 3 „You Go Go Go‟ Comparison (==)(>)(=): to see if two strings are the same or to put words in lexicographical order (similar to the alphabetical order in a dictionary, except that all the uppercase letters come before all the lowercase letter.) >>> „Dog‟< „Doghouse‟ True >>> „dog‟< „Dog‟ False >>> „dog‟< „Doghouse‟ False ord(char) and chr(int): Each character in Python is assigned unique integer value so that Python can compare them to find their order („A‟is 65, „B‟is 66, „5‟is 53). You can find out the so called ordinal value for a given character using a character function called ord(char). And chr(int) can converts integers into their character equivalent. Note: the space character has an ordinal value (32). Even though you don‟t see it, it‟s an actual character. >>> ord(„A‟) 65 >>> chr(65) „A‟ len(): returns the number of characters in a string. >>> len(„hello‟) 5 Index Operator: index 0 1 2 3 4 H e l l o index -5 -4 -3 -2 -1 The indexing operator, x[index], selects a single character from a string. The characters are accessed by their position or index value. Note: Indexing returns a string >>> „Hello‟[1] „e‟ >>> „Hello‟[-5] „H‟ Index: x[index] The expression in brackets is called an index. An index specifies a member of an ordered collection. It can be any integer expression so long as it evaluates to a valid index value. Slice Operator: A substring of a string is called a slice. string[n:m] returns the part of the string from the n‟th character to the m‟th character, including the first but excluding the last - [n,m). in and not in operators: Test if one string is a substring of another Note: a string is a substring of itself; the empty string is a substring of any other string String Methods: object.method(arguments) Strings are also objects. Each string instance has its own attributes and methods. upper(): a method that can be invoked on any string object to create a new string in which all
More Less

Related notes for CSCA08H3

Log In


OR

Join OneClass

Access over 10 million pages of study
documents for 1.3 million courses.

Sign up

Join to view


OR

By registering, I agree to the Terms and Privacy Policies
Already have an account?
Just a few more details

So we can recommend you notes for your school.

Reset Password

Please enter below the email address you registered with and we will send you a link to reset your password.

Add your courses

Get notes from the top students in your class.


Submit