Python Programming Cheatsheet PDF

Summary

This document is a Python programming cheatsheet covering fundamental concepts such as string methods, f-strings, conditional statements, and loops. The document presents examples in Python code and clearly explains how each concept works through explanations and code outputs.

Full Transcript

# String Methods Cheatsheet - **.find(string)** Returns the index of the first instance of a given string ```python message = 'I hope it snows tonight!' message.find('snow') # Output: 10 ``` - **.upper()** Converts all characters in a string to uppercase ```python message = 'I hope it...

# String Methods Cheatsheet - **.find(string)** Returns the index of the first instance of a given string ```python message = 'I hope it snows tonight!' message.find('snow') # Output: 10 ``` - **.upper()** Converts all characters in a string to uppercase ```python message = 'I hope it snows tonight!' message.upper() # Output: 'I HOPE IT SNOWS TONIGHT!' ``` - **.replace(string to replace, replacement)** Substitutes a string with another ```python message = 'I hope it snows tonight!' message.replace('snow', 'rain') # Output: 'I hope it rains tonight!' ``` - **.split(optional string)** Splits a string into a list based on spaces or a delimiter ```python message = 'I hope it snows tonight!' message.split() # Output: ['I', 'hope', 'it', 'snows', 'tonight!'] ``` - **.lower()** Converts all characters in a string to lowercase ```python message = 'I hope it snows tonight!' message.lower() # Output: 'i hope it snows tonight!' ``` - **.strip(optional string)** Removes leading or trailing spaces or characters ```python message = 'I hope it snows tonight!' message.strip('!') # Output: 'I hope it snows tonight' ``` - **delimiter.join(list)** Combines list elements into a string, separated by a delimiter ```python word_list = ['I', 'hope', 'it', 'snows', 'tonight!'] ' '.join(word_list) # Output: 'I hope it snows tonight!' ``` # 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!') # Output: Chris is our favorite employee, of course! ``` # 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.') # Output: This board is good for intermediate_users. ``` **How it works:** 1. The `if` condition is evaluated first. If it evaluates to True, the `if` code is executed, and the rest of the `elif` and `else` blocks are skipped. 2. If the `if` condition is False, the `elif` condition is evaluated. If it evaluates to True, the `elif` code is executed, and the `else` block is skipped. 3. If both the `if` and `elif` conditions are False, the `else` code is executed. # 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}.') # Output: You can afford this but it's out of stock. ``` **How it works:** 1. The first `if` condition is evaluated. If True, the nested `if` condition is evaluated. If the nested `if` condition is True, the corresponding code block is executed. 2. The first if is evaluated, if it is true the nested else code is executed. 3. If the first `if` condition is False, the `else` code is executed. # 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. ## Example: Converting USD to Euro ```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) # Output: [5.27, 8.79, 17.59, 21.99, 87.99] ``` **How it works:** - The `for` loop iterates through each element in the `usd_list` and assigns each element to the variable `price`. - Inside the loop, the `round()` function calculates the corresponding euro price for each `price` value. - The calculated euro price is then appended to the `euro_list`. - After the loop has finished, the `print()` function displays the euro prices in euro_list. # 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. ## Example: Converting USD to Euro using Indices ```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) # Output: [5.27, 8.79, 17.59, 21.99, 87.99] ``` **How it works:** - The `for` loop iterates through the range of integers specified by `range(len(usd_list))`. - The range function provides a sequence of numbers from 0 to `len(usd_list) - 1`, which are the indices of the elements in `usd_list`. - Inside the loop, the variable `i` represents the current index. - The expression `usd_list[i]` accesses the element at index `i` in `usd_list`. - The `round()` function calculates the corresponding euro price for the element at the current index. - The calculated euro price is appended to the `euro_list` at the corresponding index. - After the loop has finished, the `print()` function displays the euro prices in the `euro_list`. # 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.") # Output: # 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. ``` **How it works:** - The `for` loop iterates through a range of integers with the same length as the `euro_list`. - Inside the loop, both `item_list[i]` and `euro_list[i]` use the same index `i` to access corresponding elements from the two lists. # The Enumerate Function The `enumerate` function will return both the index and item of each item in an iterable as it loops through. ## Example: Accessing index and item using enumerate ```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) # Output: # Snowboard 5.27 # Boots 8.79 # Helmet 17.59 # Goggles 21.99 # Bindings 87.99 ``` **How it works:** - The `enumerate` function takes a list as input and returns an iterator. The iterator yields a tuple for each element in the list, containing the index and the value of that element. - Inside the loop, the `index` and `element` variables are used to access the corresponding index and value. # While Loops The `while` loop will run while the condition is True. ## 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 * 0.05 # 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)}') # Output: # 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 continues to iterate as long as the condition `stock_portfolio < 1000000` is True. - The calculation updates the value of `stock_portfolio`. - Inside the loop, the `print()` function displays the stock portfolio balance at the end of each year. # Nested Loops Nested loops are loops within 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}.") # Output: # 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. ``` **How it works:** - The outer `for` loop iterates through each element in `item_list`. - For each item, the inner `for` loop then iterates through each size in `size_list` and prints a message combining the current item and size. - It will first iterate through the outer for loop all the way through before starting the inner loop again. # Keys The `.keys()` method returns the keys from a dictionary. It returns a view object that represents the keys as a list. ## Example: Accessing 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() # Output: dict_keys(['skis', 'snowboard', 'goggles', 'boots']) ``` - Iterating through the view object provides the same behavior as iterating through the dictionary keys directly. # Values The `.values()` method returns the values from a dictionary. ## Example: Accessing values 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.values() # Output: dict_values(([249.99, 10], [219.99, 0], [99.99, 0], [79.99, 7])) ``` - It returns a view object that represents the values as a list, which is more memory-efficient than creating a list. # Items The `.items()` method returns key-value pairs from a dictionary as a list of tuples. It returns a view object that represents the key-value pairs as a list of tuples. ## Example: Accessing Key-Value pairs 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.items() # Output: dict_items([('skis', [249.99, 10]), ('snowboard', [219.99, 0]), ('goggles', [99.99, 0]), ('boots', [79.99, 7])]) ``` # 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. ## Example: Accessing values using get ```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') # Output: [79.99, 7, 'in stock'] ``` - The `get()` method returns the value associated with the given key. # Update The `.update()` method appends key-value pairs to a dictionary. ## Example: Appending key-value pairs to a dictionary using update ```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']}) item_details # Output: {'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']} ``` - The `.update()` method takes a dictionary as an argument and adds the key-value pairs from that dictionary to the existing dictionary. # Zip The `zip()` function is commonly used to build dictionaries. It takes multiple iterables as arguments and returns an iterator that produces tuples. ## Example: Creating a dictionary using zip ```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)) item_dict # Output: {'skis': [249.99, 10, 'in stock'], 'snowboard': [219.99, 0, 'sold out'], 'goggles': [99.99, 0, 'sold out'], 'boots': [79.99, 7, 'in stock']} ``` - The `zip()` function combines corresponding elements from the `item_names` and `item_details` lists. - The resulting tuples from the zip object are used to create a dictionary. # Union The `union` function returns all unique values in both sets . ## Example: Creating a union of items ```python friday_items = {'snowboard', 'snowboard', 'skis', 'snowboard', 'sled'} saturday_items = {'goggles', 'helmet', 'snowboard', 'skis', 'goggles'} friday_items.union(saturday_items) # Output: {'goggles', 'helmet', 'skis', 'sled', 'snowboard'} ``` - The `union()` method takes another set as an argument. - It returns a new set containing all elements from both input sets with no duplicates. # Intersection The `intersection` function returns the values present in both sets. ## Example: Find the items common to both sets ```python friday_items = {'snowboard', 'snowboard', 'skis', 'snowboard', 'sled'} saturday_items = {'goggles', 'helmet', 'snowboard', 'skis', 'goggles'} friday_items.intersection(saturday_items) # Output: {'skis', 'snowboard'} ``` - The `intersection()` method takes another set as an argument. - It returns a new set containing only the elements that are present in both input sets. # Difference The `difference` function returns the values present in the first set, but not in the second set. ## Example: Finding the differences between two sets ```python friday_items = {'snowboard', 'snowboard', 'skis', 'snowboard', 'sled'} saturday_items = {'goggles', 'helmet', 'snowboard', 'skis', 'goggles'} friday_items.difference(saturday_items) # Output: {'sled'} ``` - The `difference()` method returns a new set containing elements that are present in the first set but not in the second set. - The order of the sets matters. # Symmetric Difference The `symmetric_difference` function returns all values not shared between sets. ## Example: Finding the symmetric difference ```python friday_items = {'snowboard', 'snowboard', 'skis', 'snowboard', 'sled'} saturday_items = {'goggles', 'helmet', 'snowboard', 'skis', 'goggles'} friday_items.symmetric_difference(saturday_items) # Output: {'goggles', 'helmet', 'sled'} ``` - The `symmetric_difference()` function returns a new set containing elements that are present in either the first or second set, but not in both. # Defining A Function ```python def concatenator(string1, string2): combined_string = string1 + ' ' + string2 return combined_string concatenator('Hello', 'World!') # Output: Hello World! ``` - The `def` keyword indicates that you're defining a function. - The function name is `concatenator`. - The code block within the function definition is indented. - The `return` statement specifies the value that the function will return. # 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!') # Output: Hello World! concatenator('World!', 'Hello') # Output: World! Hello ``` - The first value passed in the function will be `string1`, and the second will be `string2`. -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!') # Output: Hello World! concatenator(string2='World!', string1='Hello') # Output: Hello World! ``` - By specifying the value to pass for each argument, the order no longer matters. ## 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') # Output: Hola World! concatenator('Hola', 'Mundo!') # Output: Hola Mundo! ``` - Assign a default value by using `=` when defining the function. - Since a single argument was passed, the second argument defaults to `'World!'`. - By specifying a second argument, the default value is no longer used. ## *args arguments *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() concatenator('Hello', 'world', 'How', 'are', 'you?') # Output: Hello world! How are you? ``` - 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. ## **kwargs arguments **kwargs arguments pass any number of keyword arguments as dictionaries. ```python def concatenator(**words): new_string = '' for word in words.values(): new_string += (word + ' ') return new_string.rstrip() concatenator(a='Hello', b='there!', c='What’s', d='up?') # Output: Hello there! What’s up? ``` - Using `**` before the argument name allows users to enter any number of keyword arguments. - Since the arguments are passed as dictionaries, you need to use the `.values()` method to loop through them. # 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?') # Output: ('Hello world! How are you?', 'you?') sentence, last_word = concatenator('Hello', 'world!', 'How', 'are', 'you?') print(sentence) print(last_word) # Output: # Hello world! How are you? # you? ``` - The values to return must be separated by commas. This returns a tuple of specified values. - You can unpack the tuple into variables during the function call. # Map The `map()` function is an efficient way to apply a function to all items in an iterable. ```python def currency_formatter(number): return '$' + str(number) price_list = [5.99, 19.99, 24.99, 0, 74.99, 99.99] map(currency_formatter, price_list) # Output: <map at 0x7fa430944d90> list(map(currency_formatter, price_list)) # Output: ['$5.99', '$19.99', '$24.99', '$0', '$74.99', '$99.99'] ``` - The `map` function returns a `map` *object* which saves memory until we've told Python what to do with the object. - 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. ```python (lambda x: x**2) (3) # Output: 9 (lambda x: x**2, x**3) (3) # Output: NameError # Lambda functions cannot have multiple outputs or expressions (lambda x, y: x * y if y > 5 else x / y) (6, 5) # Output: 1.2 ``` - The `lambda` keyword indicates that you're defining a lambda function. - The lambda function takes two arguments: `x` and `y`. - The expression `x * y if y > 5 else x / y` is a conditional expression that calculates and returns a value based on the condition. The expression `x * y` is returned if the condition `y > 5` is True; otherwise, the expression `x / y` is returned. - The lambda function is immediately invoked and returns the value `1.2`. # Comprehensions Comprehensions can generate sequences from other sequences. ```python usd_list = [5.99, 19.99, 24.99, 0, 74.99, 99.99] exchange_rate = 0.88 euro_list = [round(price * exchange_rate, 2) for price in usd_list] euro_list # Output: [5.27, 8.79, 17.59, 21.99, 87.99] euro_list = [round(price * exchange_rate, 2) for price in usd_list if price < 10] euro_list # Output: [5.27, 0.0] ``` **How comprehensions work:** - The general syntax is: `new list = [expression for member in other iterable (if condition)]`. - The `for` clause specifies what iterable to iterate over. - The `if` clause (optional) sets a condition for which elements to include in the new list. - The `expression` is the operation that will be applied to each element in the iterable. You can use comprehensions to do the following: - Create new lists based on existing lists. - Filter elements from a list. - Perform calculations on each element in a list. - Leverage conditional logic to create powerful expressions.

Use Quizgecko on...
Browser
Browser