CMPSC 121 Final: Python Final Review
Premium

14 Pages
70 Views

Department
Computer Science
Course Code
CMPSC 121
Professor
Steven Shaffer

This preview shows pages 1,2,3. Sign up to view the full 14 pages of the document.
Description
Python Final Review Variables: Valid variables that could be used in python…. - Lowercase or uppercase letters - Numbers (0-9) - Underscores *Cannot included spaces or special characters in variable. Special built-in functions are also prohibited as shown below…. False None True and as assert break class continue def del return try while for yield with nonlocal from in import finally elif else if global except lambda not or Escape characters: Different combinations involving the backslash symbol (\) can be used to manipulate a print statement. Example: Escape Sequence Explanation Example code Output print('\\home\\users\\') \\ Backslash (\) \home\users\ \' Single quote (')print('Name: John O\'Donald') John O'Donald \" Double quote print("He said, \"Hello friend!\".") He said, "Hello (") friend!". \n Newline print('My name...\nIs John...') My name... Is John... print('1. Bake cookies\n\t1.1. Preheat 1. Bake cookies \t Tab (indent) oven') 1.1. Preheat oven Python Operators: Arithmetic operator Description + addition - subtraction and negation * multiplication / division // floored division (rounds down) % modulo (remainder) ** exponentiation Strings: A string is a text that is surrounded by a quotation mark. You can find the length of a string by using – len() . Once a string is created in a variable, you cannot change it by adding another code. Strings are immutable. *Whitespaces are included when counting for the length OUTPUT: 14 A programmer can access the location of a string by using the brackets ([ ]). This method is called string indexing. String Concatenation: The process of combining one or more strings together… INPUT OUTPUT String_1 = “Hello, ” String_2 = “my name is….” Concatenated_string = String_1 + String_2 Hello, my name is… print(Concatenated_string) Lists: A list can be used to store elements. Elements are separated by a comma (,). An element can be a string, integer or a float. An element’s position in a list can be represented by its indexes. Example: The numbers represents each element’s index Lists are mutable, meaning that it could be changed with the use of these built-in functions… New elements are added to a list using the append() list method. Elements can be removed using the pop() or remove() methods. Refer examples in the bottom Adding elements to a list: • list.append(value): Adds value to the end of list. Example: my_list.append('abc') Removing elements from a list: • list.pop(i): Removes the element at the first index from list. Example: my_list.pop(1) • list.remove(v): Removes the first element whose value is v. Example: my_list.remove('abc') Sequence type operations: Operation Description len(list) Find the length of the list. list1 + list2 Produce a new list by concatenating list2 to the end of list1. min(list) Find the element in list with the smallest value. max(list) Find the element in list with the largest value. sum(list) Find the sum of all elements of a list (numbers only). list.index(val) Find the index of the first element in list whose value matches val. list.count(val) Count the number of occurrences of the value val in list. Tuple: A tuple is similar to a list, but the elements inside it cannot be changed. Dictionaries: A dictionary is represented by the dict object type. A dict map keys to values. A key is like the word "cat" from the English dictionary example. A value describes some data associated with a key, such as a definition. A key can be any immutable type, such as a number, string, or tuple; a value can be any type. Example: caffeine_content_mg = { 'Mr. Goodbar chocolate': 122, 'Red Bull': 33, 'Monster Hitman Sniper energy drink': 270, 'Lipton Brisk iced tea - lemon flavor': 2, 'dark chocolate coated coffee beans': 869, 'Regular drip or percolated coffee': 60, 'Buzz Bites Chocolate Chews': 1639} Adding new entries to a dictionary: • dict[k] = v: Adds the new key-value pair k-v, if dict[k] does not already exist. Example: students['John'] = 'A+' Editing existing entries in a dictionary: • dict[k] = v: Updates the existing entry dict[k], if dict[k] already exists. Example: students['Jessica'] = 'A+' Removing entries from a dictionary: • del dict[k]: Deletes the entry dict[k] Example: del students['Rachel'] Dict method Description Code example Output my_dict = {'Bob': 1, 'Jane': 42} my_dict.clear() Removes all items {} from the dictionary my_dict.clear() print(my_dict) Merges dictionary my_dict with another my_dict = {'Bob': 1, dictionary my_dict2. 'Jane': 42} Existing entries in {'Bob': 1, my_dict1.update(my_dict2) my_dict.update({'John': 'Jane': 42, my_dict1 are 50}) 'John': 50} overwritten if the same keys exist in print(my_dict) my_dict2. Removes and returns my_dict = {'Bob': 1, the key value from 'Jane': 42} my_dict.pop(key, default) the dictionary. If keyal = my_dict.pop('Bob') {'Jane': 42} does not exist, then default is returned. print(my_dict) Data Types: Python’s most common data types Type Notes int Numeric type: Used for variable-width integers. (integers) float Numeric type: Used for floating-point numbers. (decimals) string Sequence type: Used for text. (Separated by a quotation mark) list Sequence type: A mutable container with ordered elements. tuple Sequence type: An immutable container with ordered elements. dict Mapping type: A container with key-values associated elements. Type Conversions: A type conversion allows a programmer to change one type to another, such as an int to a float. The interpreter automatically performs common conversions like this... *We use these functions. If we want to do a
More Less
Unlock Document

Only pages 1,2,3 are available for preview. Some parts have been intentionally blurred.

Unlock Document
You're Reading a Preview

Unlock to view full version

Unlock Document

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