Created
July 25, 2026 21:30
-
-
Save steniowagner/2251daa17ecafb1d1408b39e1bb97d78 to your computer and use it in GitHub Desktop.
Python notes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # if can be used as an expression | |
| # Equivalent of C's '?:' ternary operator | |
| "yay!" if 0 > 1 else "nay!" # => "nay!" | |
| # You can look at ranges with slice syntax. | |
| # The start index is included, the end index is not | |
| # (It's a closed/open range for you mathy types.) | |
| li[1:3] # Return list from index 1 to 2 => [2, 4] | |
| li[2:] # Return list starting from index 2 => [4, 3] | |
| li[:3] # Return list from beginning until index 3 => [1, 2, 4] | |
| li[::2] # Return list selecting elements with a step size of 2 => [1, 4] | |
| li[::-1] # Return list in reverse order => [3, 4, 2, 1] | |
| # Use any combination of these to make advanced slices | |
| # li[start:end:step] | |
| # You can also do extended unpacking | |
| a, *b, c = (1, 2, 3, 4) # a is now 1, b is now [2, 3] and c is now 4 | |
| # Note keys for dictionaries have to be immutable types. This is to ensure that | |
| # the key can be converted to a constant hash value for quick look-ups. | |
| # Immutable types include ints, floats, strings, tuples. | |
| invalid_dict = {[1,2,3]: "123"} # => Yield a TypeError: unhashable type: 'list' | |
| valid_dict = {(1,2,3):[1,2,3]} # Values can be of any type, however. | |
| # Look up values with [] | |
| filled_dict = {"one": 1, "two": 2, "three": 3} | |
| filled_dict["one"] # => 1 | |
| # Get all keys as an iterable with "keys()". We need to wrap the call in list() | |
| # to turn it into a list. We'll talk about those later. Note - for Python | |
| # versions <3.7, dictionary key ordering is not guaranteed. Your results might | |
| # not match the example below exactly. However, as of Python 3.7, dictionary | |
| # items maintain the order at which they are inserted into the dictionary. | |
| list(filled_dict.keys()) # => ["three", "two", "one"] in Python <3.7 | |
| list(filled_dict.keys()) # => ["one", "two", "three"] in Python 3.7+ | |
| # Get all values as an iterable with "values()". Once again we need to wrap it | |
| # in list() to get it out of the iterable. Note - Same as above regarding key | |
| # ordering. | |
| list(filled_dict.values()) # => [3, 2, 1] in Python <3.7 | |
| list(filled_dict.values()) # => [1, 2, 3] in Python 3.7+ | |
| # Check for existence of keys in a dictionary with "in" | |
| "one" in filled_dict # => True | |
| 1 in filled_dict # => False | |
| # Looking up a non-existing key is a KeyError | |
| filled_dict["four"] # KeyError | |
| # Use "get()" method to avoid the KeyError | |
| filled_dict.get("one") # => 1 | |
| filled_dict.get("four") # => None | |
| # The get method supports a default argument when the value is missing | |
| filled_dict.get("one", 4) # => 1 | |
| filled_dict.get("four", 4) # => 4 | |
| # "setdefault()" inserts into a dictionary only if the given key isn't present | |
| filled_dict.setdefault("five", 5) # filled_dict["five"] is set to 5 | |
| filled_dict.setdefault("five", 6) # filled_dict["five"] is still 5 | |
| # Adding to a dictionary | |
| filled_dict.update({"four":4}) # => {"one": 1, "two": 2, "three": 3, "four": 4} | |
| filled_dict["four"] = 4 # another way to add to dict | |
| # Remove keys from a dictionary with del | |
| del filled_dict["one"] # Removes the key "one" from filled dict | |
| # From Python 3.5 you can also use the additional unpacking options | |
| {"a": 1, **{"b": 2}} # => {'a': 1, 'b': 2} | |
| {"a": 1, **{"a": 2}} # => {'a': 2} | |
| # Sets store ... well sets | |
| empty_set = set() | |
| # Initialize a set with a bunch of values. | |
| some_set = {1, 1, 2, 2, 3, 4} # some_set is now {1, 2, 3, 4} | |
| # Similar to keys of a dictionary, elements of a set have to be immutable. | |
| invalid_set = {[1], 1} # => Raises a TypeError: unhashable type: 'list' | |
| valid_set = {(1,), 1} | |
| # Add one more item to the set | |
| filled_set = some_set | |
| filled_set.add(5) # filled_set is now {1, 2, 3, 4, 5} | |
| # Sets do not have duplicate elements | |
| filled_set.add(5) # it remains as before {1, 2, 3, 4, 5} | |
| # Do set intersection with & | |
| other_set = {3, 4, 5, 6} | |
| filled_set & other_set # => {3, 4, 5} | |
| # Do set union with | | |
| filled_set | other_set # => {1, 2, 3, 4, 5, 6} | |
| # Do set difference with - | |
| {1, 2, 3, 4} - {2, 3, 5} # => {1, 4} | |
| # Do set symmetric difference with ^ | |
| {1, 2, 3, 4} ^ {2, 3, 5} # => {1, 4, 5} | |
| # Check if set on the left is a superset of set on the right | |
| {1, 2} >= {1, 2, 3} # => False | |
| # Check if set on the left is a subset of set on the right | |
| {1, 2} <= {1, 2, 3} # => True | |
| # Check for existence in a set with in | |
| 2 in filled_set # => True | |
| 10 in filled_set # => False | |
| # Make a one layer deep copy | |
| filled_set = some_set.copy() # filled_set is {1, 2, 3, 4, 5} | |
| filled_set is some_set # => False | |
| # Here is an if statement. Indentation is significant in Python! | |
| # Convention is to use four spaces, not tabs. | |
| # This prints "some_var is smaller than 10" | |
| if some_var > 10: | |
| print("some_var is totally bigger than 10.") | |
| elif some_var < 10: # This elif clause is optional. | |
| print("some_var is smaller than 10.") | |
| else: # This is optional too. | |
| print("some_var is indeed 10.") | |
| # Match/Case β Introduced in Python 3.10 | |
| # It compares a value against multiple patterns and executes the matching case block. | |
| command = "run" | |
| match command: | |
| case "run": | |
| print("The robot started to run πββοΈ") | |
| case "speak" | "say_hi": # multiple options (OR pattern) | |
| print("The robot said hi π£οΈ") | |
| case code if command.isdigit(): # conditional | |
| print(f"The robot execute code: {code}") | |
| case _: # _ is a wildcard that never fails (like default/else) | |
| print("Invalid command β") | |
| # Output: "the robot started to run πββοΈ" | |
| """ | |
| For loops iterate over lists | |
| prints: | |
| dog is a mammal | |
| cat is a mammal | |
| mouse is a mammal | |
| """ | |
| for animal in ["dog", "cat", "mouse"]: | |
| # You can use format() to interpolate formatted strings | |
| print("{} is a mammal".format(animal)) | |
| """ | |
| "range(number)" returns an iterable of numbers | |
| from zero up to (but excluding) the given number | |
| prints: | |
| 0 | |
| 1 | |
| 2 | |
| 3 | |
| """ | |
| for i in range(4): | |
| print(i) | |
| """ | |
| "range(lower, upper)" returns an iterable of numbers | |
| from the lower number to the upper number | |
| prints: | |
| 4 | |
| 5 | |
| 6 | |
| 7 | |
| """ | |
| for i in range(4, 8): | |
| print(i) | |
| """ | |
| "range(lower, upper, step)" returns an iterable of numbers | |
| from the lower number to the upper number, while incrementing | |
| by step. If step is not indicated, the default value is 1. | |
| prints: | |
| 4 | |
| 6 | |
| """ | |
| for i in range(4, 8, 2): | |
| print(i) | |
| """ | |
| Loop over a list to retrieve both the index and the value of each list item: | |
| 0 dog | |
| 1 cat | |
| 2 mouse | |
| """ | |
| animals = ["dog", "cat", "mouse"] | |
| for i, value in enumerate(animals): | |
| print(i, value) | |
| """ | |
| While loops go until a condition is no longer met. | |
| prints: | |
| 0 | |
| 1 | |
| 2 | |
| 3 | |
| """ | |
| x = 0 | |
| while x < 4: | |
| print(x) | |
| x += 1 # Shorthand for x = x + 1 | |
| # Handle exceptions with a try/except block | |
| try: | |
| # Use "raise" to raise an error | |
| raise IndexError("This is an index error") | |
| except IndexError as e: | |
| pass # Refrain from this, provide a recovery (next example). | |
| except (TypeError, NameError): | |
| pass # Multiple exceptions can be processed jointly. | |
| else: # Optional clause to the try/except block. Must follow | |
| # all except blocks. | |
| print("All good!") # Runs only if the code in try raises no exceptions | |
| finally: # Execute under all circumstances | |
| print("We can clean up resources here") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment