Python Base Exam Summary PDF
Document Details
Uploaded by SteadyHaiku8410
Tags
Summary
This document provides a summary of various Python programming concepts, including string methods, f-strings, conditional statements (if-elif-else), nested if statements, looping over items and indices, and functions. The document is suitable for learning Python programming for undergraduate students.
Full Transcript
# String Method Cheatsheet - **.find(string)** Returns the index of the first instance of a given string - message.find('snow') - 10 - **.upper()** Converts all characters in a string to uppercase - message.upper() - 'I HOPE IT SNOWS TONIGHT!' - **.replace(string to replace,...
# String Method Cheatsheet - **.find(string)** Returns the index of the first instance of a given string - message.find('snow') - 10 - **.upper()** Converts all characters in a string to uppercase - message.upper() - 'I HOPE IT SNOWS TONIGHT!' - **.replace(string to replace, replacement)** Substitutes a string with another - message.replace('snow', 'rain') - 'I hope it rains tonight!' - **.split(optional string)** Splits a string into a list based on spaces or a delimiter - message.split() - ['I', 'hope', 'it', 'snows', 'tonight!'] - **.lower()** Converts all characters in a string to lowercase - message.lower() - i hope it snows tonight! - **.strip(optional string)** Removes leading or trailing spaces or characters - message.strip('!') - 'I hope it snows tonight' - **delimiter.join(list)** Combines list elements into a string, separated by a delimiter - '.join(word_list) - 'I hope it snows tonight!' **NOTE:** There are many more string methods than covered; to review those, or get additional detail on the methods covered, visit the official Python documentation: https://docs.python.org/3/library/stdtypes.html#string-methods # F-Strings You can include variables in strings by using f-strings. This allows you to change the output text based on changing variable values. - Add an f before the quotation marks to indicate an f-string and place the variable names into the string by using curly braces {}. - ```python name = 'Chris' role = 'employee' print(f"{name} is our favorite {role}, of course!") ``` - Chris is our favorite employee, of course! - ```python name = 'Anand' role = 'customer' print(f"{name} is our favorite {role}, of course!") ``` - Anand is our favorite customer, of course! **Note that the f-string code doesn't change, but the output does change if the variables get assigned new values.** # The Elif Statement The elif statement lets you specify additional criteria to evaluate when the logical condition in an if statement is not met. ## Example: Determining experience level for a snowboard ```python price = 499.99 expert_threshold = 500 intermediate_threshold = 300 if price > expert_threshold: print('This board is for experienced users.') elif price > intermediate_threshold: print('This board is good for intermediate_users.') else: print('This should be suitable for a beginner.') ``` - This board is good for intermediate_users. **How this code works?** - If the price is greater than `expert_threshold`, print "This board is for experienced users." - If the price is not greater than `expert_threshold` but is greater than `intermediate_threshold`, print "This board is good for intermediate_users." - If the price is not greater than `intermediate_threshold`, print "This should be suitable for a beginner." # Nested If Statements Nested if statements let you specify additional criteria to evaluate after a logical condition in an if statement is met. ## Example: Trying to purchase a product ```python price = 499.99 budget = 500 inventory = 0 if budget > price: if inventory > 0: print('You can afford this and we have it in stock!') else: # equivalent to if inventory <= 0 print("You can afford this but it's out of stock.") else: print(f'Unfortunately, this board costs more than ${budget}.') ``` - You can afford this but it's out of stock. **How does this code work?** - If the `budget` is greater than the `price`: - If the `inventory` is greater than 0, print "You can afford this and we have it in stock!" - If the `inventory` is not greater than 0, print "You can afford this but it's out of stock." - If the `budget` is not greater than the `price`, print "Unfortunately, this board costs more than $`budget`." # Looping Over Items Looping over items will run through the items of an iterable. The loop will run as many times as there are items in the iterable. ```python exchange_rate = 0.88 usd_list = [5.99, 9.99, 19.99, 24.99, 99.99] euro_list = [] for price in usd_list: euro_list.append(round(price * exchange_rate, 2)) print (euro_list) ``` - [5.27, 8.79, 17.59, 21.99, 87.99] **The for loop here is looping over the items, (elements) of usd_list, so the loop code block runs 5 times (length of the list):** 1. price = usd_list[0]= 5.99 2. price = usd_list[1]= 9.99 3. price = usd_list[2]= 19.99 4. price = usd_list[3]= 24.99 5. price = usd_list[4]= 99.99 **PRO TIP:** To create a new list (or other data type) with loops, first create an empty list, then append values as your loop iterates. # Looping Over Indices Looping over indices will run through a range of integers. You need to specify a range (usually the length of an iterable). This range can be used to navigate the indices of iterable objects. ```python exchange_rate = 0.88 usd_list = [5.99, 9.99, 19.99, 24.99, 99.99] euro_list = [] for i in range(len(usd_list)): euro_list.append(round(usd_list[i] * exchange_rate, 2)) print(euro_list) ``` - [5.27, 8.79, 17.59, 21.99, 87.99] **The for loop here is looping over indices in a range the size of the euro_list, meaning that the code will run 5 times (length of the list):** 1. i=0 2. i= 1 3. i= 2 4. i= 3 5. i= 4 **PRO TIP:** If you only need to access the elements of a single iterable, it's a best practice to loop over items instead of indices. # Looping Over Multiple Iterables Looping over indices can help with looping over multiple iterables, allowing you to use the same index for items you want to process together. ## Example: Printing the price for each inventory item ```python euro_list = [5.27, 8.79, 17.59, 21.99, 87.99] item_list = ['Snowboard', 'Boots', 'Helmet', 'Goggles', 'Bindings'] for i in range(len(euro_list)): print(f"The {item_list[i].lower()} costs {euro_list[i]} euros.") ``` - The snowboard costs 5.27 euros. - The boots costs 8.79 euros. - The helmet costs 17.59 euros. - The goggles costs 21.99 euros. - The bindings costs 87.99 euros. **The for loop here is looping over indices in a range the size of the euro_list, meaning that the code will run 5 times (length of the list)** For the first run: - i = 0 - item_list[i]= Snowboard - euro_list[i] = 5.27 # PRO TIP - Enumerate The `enumerate()` function will return both the index and item of each item in an iterable as it loops through. ```python for index, element in enumerate(euro_list): print(index, element) ``` - 0 5.27 - 1 8.79 - 2 17.59 - 3 21.99 - 4 87.99 **PRO TIP:** Use enumerate if you want to loop over an index, it is slightly more efficient and considered best practice, as we are looping over an index derived from the list itself, rather than generating a new object to do so. ```python euro_list = [5.27, 8.79, 17.59, 21.99, 87.99] item_list = ['Snowboard', 'Boots', 'Helmet', 'Goggles', 'Bindings'] for index, element in enumerate(euro_list): print(item_list[index], element) ``` - Snowboard 5.27 - Boots 8.79 - Helmet 17.59 - Goggles 21.99 - Bindings 87.99 **We're using the index of the euro_list to access each element from the item_list, and then printing each element of the euro_list.** # While Loops ## Example: Run a calculation until a goal is reached ```python # starting portfolio balance is 800000 stock_portfolio = 800000 year_counter = 0 while stock_portfolio < 1000000: # calculate annual investment income investment_income = stock_portfolio * .05 #5% interest rate # add income to end of year portfolio balance stock_portfolio += investment_income # add one each year year_counter += 1 print(f'At the end of year {year_counter}: + f'My balance is ${round(stock_portfolio, 2)}') ``` - At the end of year 1: My balance is $840000.0 - At the end of year 2: My balance is $882000.0 - At the end of year 3: My balance is $926100.0 - At the end of year 4: My balance is $972405.0 - At the end of year 5: My balance is $1021025.25 **The while loop here will run while stock_portfolio is less than 1m. stock_portfolio starts at 800k and increases by 5% of its value in each run:** 1. 800k < 1m is TRUE 2. 840k < 1m is TRUE 3. 882k < 1m is TRUE 4. 926k < 1m is TRUE 5. 972k < 1m is TRUE 6. 1.02m < 1m is FALSE (exit) # Nested Loops ## Example: Printing items along with their sizes ```python item_list = ['Snowboard', 'Boots'] size_list = ['small', 'medium', 'large'] for item in item_list: for size in size_list: print(f"{item} is available in {size}.") ``` - Snowboard is available in small. - Snowboard is available in medium. - Snowboard is available in large. - Boots is available in small. - Boots is available in medium. - Boots is available in large. **You exit a nested loop when all its loops are completed** # Keys The `.keys()` method returns the keys from a dictionary. - ```python item_details = {'skis': [249.99, 10, 'in stock'], 'snowboard': [219.99, 0, 'sold out'], 'goggles': [99.99, 0, 'sold out'], 'boots': [79.99, 7, 'in stock']} item_details.keys() ``` - dict_keys(['skis', 'snowboard', 'goggles', 'boots']) - .keys() returns a view object that represents the keys as a list (this is more memory efficient than creating a list). - ```python for item in item_details.keys(): print(item) ``` - skis - snowboard - goggles - boots - this view object can be iterated through, which has the same behavior as looping through the dictionary keys directly . - ```python key_list = list(item_details.keys()) print(key_list) ``` - ['skis', 'snowboard', 'goggles', 'boots'] - This view object can be converted into a list or a tuple if needed. # Values The `.values()` method returns the values from a dictionary. - ```python item_details = {'skis': [249.99, 10], 'snowboard': [219.99, 0], 'goggles': [99.99, 0], 'boots': [79.99, 7]} item_details.values() ``` - dict_values([[`249.99`, 10], [`219.99`, 0], [`99.99`, 0], [`79.99`, 7]]) - .values() returns a view object that represents the values as a list (this is more memory efficient than creating a list). - ```python price_list = [] for attribute in item_details.values(): price_list.append(attribute[0]) print(price_list) ``` - [249.99, 219.99, 99.99, 79.99] - This view object can be looped through as well. Here we're grabbing the first element from each of the lists returned by .values() and appending them to a new list. # Items The `.items()` method returns key-value pairs from a dictionary as a list of tuples. - ```python item_details = {'skis': [249.99, 10], 'snowboard': [219.99, 0], 'goggles': [99.99, 0], 'boots': [79.99, 7]} item_details.items() ``` - dict_items((('skis', [`249.99`, 10]), ('snowboard', [`219.99`, 0]), ('goggles', [`99.99`, 0]), ('boots', [`79.99`, 7]))) - .items() returns a view object that represents the key-value pairs as a list of tuples. - ```python for key, value in item_details.items(): print(f'The {key} costs {value[0]}.') ``` - The skis costs 249.99. - The snowboard costs 219.99. - The goggles costs 99.99. - The boots costs 79.99. - You can unpack the tuple to retrieve individual keys and values. In this case, the variable 'key' is assigned to the key in the tuple, and 'value' is assigned to the dictionary value. # Get The `.get()` method returns the values associated with a dictionary key. It won't return a KeyError if the key isn't found. You can specify an optional value to return if the key is not found. - ```python item_details = {'skis': [249.99, 10, 'in stock'], 'snowboard': [219.99, 0, 'sold out'], 'goggles': [99.99, 0, 'sold out'], 'boots': [79.99, 7, 'in stock']} item_details.get('boots') ``` - [`79.99`, 7, 'in stock'] - .get() returns the value associated with the 'boots' key. - ```python item_details['bindings'] ``` - KeyError: 'bindings' - It won't return a KeyError if the key isn't found. - ```python item_details.get('bindings') ``` - None - You can specify an optional value to return if the key is not found. - ```python item_details.get('bindings', "Sorry we don't carry that item.") ``` - "Sorry we don't carry that item." - The difference between using .get() and simply entering the key directly is that .get() will not return an error if they key is not found. You can specify an optional value to return if the key is not found: - **.get(key, value if key not found)** # Update The `.update()` method appends key-value pairs to a dictionary. - ```python item_details = {'skis': [249.99, 10, 'in stock'], 'snowboard': [219.99, 0, 'sold out'], 'goggles': [99.99, 0, 'sold out'], 'boots': [79.99, 7, 'in stock']} item_details.update({'bindings': [139.99, 0, 'out of stock']}) print(item_details ) ``` - {'skis': [249.99, 10, 'in stock'], 'snowboard': [219.99, 0, 'sold out'], 'goggles': [99.99, 0, 'sold out'], 'boots': [79.99, 7, 'in stock'], 'bindings': [139.99, 0, 'out of stock']} - ```python new_items = { 'scarf': [19.99, 100, 'in stock'), 'snowpants': 'N/A'} item_details.update(new_items) print(item_details) ``` - {'skis': [249.99, 10, 'in stock'], 'snowboard': [219.99, 0, 'sold out'], 'goggles': [99.99, 0, 'sold out'], 'boots': [79.99, 7, 'in stock'], 'bindings': [139.99, 0, 'out of stock'], 'scarf': [19.99, 100, 'in stock'], 'snowpants': 'N/A'} - `.update() appends new key-value pairs to a dictionary. In this case, a single pair for a key of 'bindings'. - **.update(key:value pairs)** - This is the preferred way to combine dictionaries. As a reminder, dictionary values do not need to be the same type; note that the value for 'snowpants' is 'N/A', while the values for the rest of the keys are lists # Zip The `zip()` function is commonly used to build dictionaries. - ```python item_details = [[`249.99`, 10, 'in stock'], [`219.99`, 0, 'sold out'], [`99.99`, 0, 'sold out'], [`79.99`, 7, 'in stock']] item_names = ['skis', 'snowboard', 'goggles', 'boots'] item_dict= dict(zip(item_names, item_details)) print(item_dict) ``` - {'skis': [`249.99`, 10, 'in stock'], 'snowboard': [`219.99`, 0, 'sold out'], 'goggles': [`99.99`, 0, 'sold out'], 'boots': [`79.99`, 7, 'in stock']} - When creating a dictionary from the zip object, the elements of the first iterable become the keys, and the second become the values. - ```python dict(zip(item_list, price_list, inventory)) ``` - ValueError: dictionary update sequence element #0 has length 3; 2 is required - Note that you can only create a dictionary from a zip object with two iterables. - ```python item_dict = dict(zip(item_list, zip(price_list, inventory))) print(item_dict) ``` - {'skis': (`249.99`, 10), 'snowboard': (`219`, 0), 'goggles': (`99`, 0), 'boots': (`99.99`, 7)} - But you can zip iterables together within the second argument. # Union ## Union returns all unique values in both sets. - ```python friday_items = {'snowboard', 'snowboard', 'skis', 'snowboard', 'sled'} saturday_items = {'goggles', 'helmet', 'snowboard', 'skis', 'goggles'} print(friday_items.union(saturday_items)) ``` - {'goggles', 'helmet', 'skis', 'sled', 'snowboard'} - All values from both sets are returned, without duplicates. - ```python sunday_items = {'coffee'} print(friday_items.union(saturday_items).union(sunday_items) ) ``` - {'coffee', 'goggles', 'helmet', 'skis', 'sled', 'snowboard'} - All values from the three sets are returned by chaining two union operations. # Intersection ## Intersection returns the values present in both sets - ```python friday_items = {'snowboard', 'snowboard', 'skis', 'snowboard', 'sled'} saturday_items = {'goggles', 'helmet', 'snowboard', 'skis', 'goggles'} print(friday_items.intersection(saturday_items)) ``` - {'skis', 'snowboard'} - Only the values in both sets are returned, without duplicates. - ```python sunday_items = {'coffee'} print(friday_items.intersection(saturday_items).intersection(sunday_items)) ``` - set() - Since no value is present in all three sets, an empty set is returned. # Difference ## Difference returns the values present in set 1, but not set 2 (the order matters) - ```python friday_items = {'snowboard', 'snowboard', 'skis', 'snowboard', 'sled'} saturday_items = {'goggles', 'helmet', 'snowboard', 'skis', 'goggles'} print(friday_items.difference(saturday_items)) ``` - {'sled'} - 'sled' is the only value in friday_items that is NOT in saturday_items. - ```python print(saturday_items.difference(friday_items)) ``` - {'goggles', 'helmet'} - If you reverse the order, the output changes - 'goggles' and 'helmet' are in saturday_items but NOT in friday_items. Note that the subtraction sign can be used instead of difference. (saturday_items - friday_items). # Symmetrical Difference ## Symmetrical difference returns all values not shared between sets. - ```python friday_items = {'snowboard', 'snowboard', 'skis', 'snowboard', 'sled'} saturday_items = {'goggles', 'helmet', 'snowboard', 'skis', 'goggles'} print(friday_items.symmetric_difference(saturday_items)) ``` - {'goggles', 'helmet', 'sled'} - 'sled' is only in set 1, and 'goggles' and 'helmet' are only in set 2. # Defining a Function ## Example: Defining a function that concatenates two words, separated by a space. ```python def concatenator(string1, string2): combined_string = string1 + ' ' + string2 return combined_string concatenator('Hello', 'World!') ``` - 'Hello World!' **Here we are defining a function called `concatenator`, which accepts two arguments, combines them with a space, and returns the result.** **When we call this function with two string arguments, the combined string is returned.** ```python def concatenator(string1, string2): return string1 + ' ' + string2 ``` - Note that we don't need a code block before `return`. Here we are combining strings in the `return` statement. # Argument Types ## Positional arguments Positional arguments are passed in the order they were defined in the function. - ```python def concatenator(string1, string2): return string1 + ' ' + string2 concatenator('Hello', 'World!') ``` - 'Hello World!' - ```python concatenator('World!', 'Hello') ``` - 'World! Hello' - The first value passed in the function will be string 1, and the second will be string2. - **Therefore, changing the order of the inputs changes the output** ## Keyword arguments Keyword arguments are passed in any order by using the argument's name - ```python def concatenator(string1, string2): return string1 + ' ' + string2 concatenator('Hello', 'World!') ``` - 'Hello World!' - ```python concatenator(string2='World!', string1='Hello') ``` - 'Hello World!' - **By specifying the value to pass for each argument, the order no longer matters.** - ```python concatenator(string2='World!', 'Hello') ``` - SyntaxError: positional argument follows keyword argument - **Keyword arguments cannot be followed by positional arguments.** - ```python concatenator('Hello', string2='World!') ``` - 'Hello World!' - **Positional arguments can be followed by keyword arguments (the first argument is typically reserved for primary input data).** ## Default arguments Default arguments pass a preset value if nothing is passed in the function call. - ```python def concatenator(string1, string2='World!'): return string1 + ' ' + string2 concatenator('Hola') ``` - 'Hola World!' - **Assign a default value by using '=' when defining the function.** - ```python concatenator('Hola', 'Mundo!') ``` - 'Hola Mundo!' - **Since a single argument was passed, the second argument defaults to 'World!' By specifying a second argument, the default value is no longer used.** - ```python def concatenator(string1='Hello', string2): return string1 + ' ' + string2 ``` - SyntaxError: non-default argument follows default argument - **Default arguments must come after arguments without default values.** ## *args *args* arguments pass any number of positional arguments as tuples. - ```python def concatenator(*args): new_string = '' for arg in args: new_string += (arg + ' ') return new_string.rstrip() ``` - **Using '*' before the argument name allows users to enter any number of strings for the function to concatenate. ** - **Since the arguments are passed as a tuple, we can loop through them or unpack them. ** - ```python concatenator('Hello', 'world!', 'How', 'are', 'you?') ``` - 'Hello world! How are you?' - ```python def concatenator(*words): new_string = '' for word in words: new_string += (word + ' ') return new_string.rstrip() ``` - **It's not necessary to use 'args' as long as the asterisk is there. Here we are using 'words' as the argument name, and only passing through two words. ** - ```python concatenator('Hello', 'world!') ``` - 'Hello world!' ## **kwargs **kwargs* arguments pass any number of keyword arguments as dictionaries. - ```python def concatenator(**words): new_string = '' # empty string for word in words.values(): new_string += (word + ' ') return new_string.rstrip() ``` - **Using '**' before the argument name allows users to enter any number of keyword arguments for the function to concatenate. Note that since the arguments are passed as dictionaries, you need to use the `.values()` method to loop through them. ** - ```python concatenator(a='Hello', b = 'there!', c="What's", d='up?') ``` - "Hello there! What's up?" - **PRO TIP:** Use **kwargs arguments to unpack dictionaries and pass them as keyword arguments** - ```python def exponentiator(constant, base, exponent): return constant * (base**exponent) ``` - The `exponentiator` function has three arguments: `constant`, `base`, and `exponent`. - ```python param_dict = { 'constant': 2, 'base': 3, 'exponent': 2} exponentiator(**param_dict) ``` - 18 - **Note that the dictionary keys in 'param_dict' match the argument names for the function. By using *** to pass the dictionary to the function, the dictionary is unpacked, and the value for each key is mapped to the corresponding argument.** # Return Values Functions can return multiple values. - ```python def concatenator(*words): sentence = '' for word in words: sentence += word + ' ' last_word = words[-1] return sentence.rstrip(), last_word concatenator('Hello', 'world!', 'How', 'are', 'you?') ``` - ('Hello world! How are you?', 'you?') - **The values to return must be separated by commas. This returns a tuple of the specified values.** - ```python sentence, last_word = concatenator('Hello', 'world!', 'How', 'are', 'you?') print(sentence) print(last_word) ``` - Hello world! How are you? - you? - **You can unpack the tuple into variables during the function call. The variable 'sentence' is assigned to the first element returned in the tuple, so if the order was switched, it would store you?.** # Return Values as Iterables Functions can return multiple values as other types of iterables as well. - ```python def concatenator(*words): sentence = '' for word in words: sentence += word + ' ' last_word = words[-1] return [sentence.rstrip(), last_word] concatenator('Hello', 'world!', 'How', 'are', 'you?') ``` - ['Hello world! How are you?', 'you?'] - **Wrap the comma-separated return values in square brackets to return them inside a list** - ```python def concatenator(*words): sentence = '' for word in words: sentence += word + ' ' last_word = words[-1] return {sentence.rstrip(): last_word} concatenator('Hello', 'world!', 'How', 'are', 'you?') ``` - {'Hello world! How are you?': 'you?'} - **Or use dictionary notation to create a dictionary (this could be useful as input for another function).** # Map The `map()` function is an efficient way to apply a function to all items in an iterable. - **`map(function, iterable)`** - ```python def currency_formatter(number): return '$' + str(number) price_list = [5.99, 19.99, 24.99, 0, 74.99, 99.99] print(map(currency_formatter, price_list)) ``` - <map at 0x7fa430944d90> - The map function returns a map object - which saves memory until we've told Python what to do with the object. - ```python print(list(map(currency_formatter, price_list))) ``` - ['$5.99', '$19.99', '$24.99', '$0', '$74.99', '$99.99'] - You can convert the map object into a list or other iterable. # Lambda Functions Lambda functions are single line, anonymous functions that are only used briefly. - **`lambda arguments: expression`** - ```python (lambda x: x**2) (3) ``` - 9 - Lambda functions can be called on a single value, but typically aren't used for this. - ```python (lambda x: x**2, x**3)(3) ``` - NameError - They cannot have multiple outputs or expressions. - ```python (lambda x, y: x * y if y> 5 else x / y) (6, 5) ``` - 1.2 - They can take multiple arguments and leverage conditional logic. - ```python price_list = [5.99, 19.99, 24.99, 0, 74.99, 99.99] exchange_rate = 0.88 converted = map(lambda x: round(x * exchange_rate, 2), price_list) print(list(converted)) ``` - [5.27, 17.59, 21.99, 0.0, 65.99, 87.99] - They are usually leveraged in combination with a function like map() or in a comprehension. # Comprehensions Comprehensions can generate sequences from other sequences. - **`new_list = [expression for member in other_iterable (if condition)]`** - **Example: Creating a list of Euro prices from USD prices** - **Before, you needed a for loop to create the new list.** - ```python usd_list = [5.99,