mylist = [x*x for x in range(3)] och när kan den användas?empty_list = [] # Tuples are immutable, can contain different datatypes empty_tuple = () populated_tuple = (1, 2, "Kalle", 4.32) singleton_tuple = (3,) print(populated_tuple[2]) # Prints Kalle # Ranges are also immutable r1 = range(0,20,2) # Start stop step # Strings single_str = 'Single quotes allows "double quotes" to be embedded' double_str = "Single quotes allows 'single quotes' to be embedded" triple_str = '''Can be initiated with either single or double quotes and can span multiple lines, including all whitespaces.''' no_escape = r"This string doesn't escape where the \backslash character is encountered" concatenation = 'Literals' " can be concatenated" ''' in this way actually''' # Dictionaries, keys must be hashable >>> a = dict(one=1, two=2, three=3) >>> b = {'one': 1, 'two': 2, 'three': 3} >>> c = dict(zip(['one', 'two', 'three'], [1, 2, 3])) >>> d = dict([('two', 2), ('one', 1), ('three', 3)]) >>> e = dict({'three': 3, 'one': 1, 'two': 2}) >>> a == b == c == d == e True >>> empty_dict = {} my_dict = {'shit': 1337, 'man': 2021, 'dude':1991} all_keys = list(my_dict) leet = my_dict['shit'] # Dictionaries can be unpacked and used as arguments to a function dude = {a: 4, b: 5} function_that_takes_a_and_b(**dude) # Set types must contain hashable objects. They are not ordered and cannot be indexed >>> my_pants = {1, 2, 'shit', 'dude'} >>> 'shit' in my_pants True # Byte objects are very similar to strings, but each character has a value 0-255 # They are created in the same way, but with the prefix 'b' my_bytes = b'Yoman!' ten_zero_bytes = bytes(10) int_to_bytes = bytes([10]) int_to_bytes_again = bytes([10, 4, 21, 0, 255]) my_bytes = 'This is a string'.encode() my_str = my_bytes.decode() # Print formatted outputs print("Id: {0}, value: {1:02X}\n".format(my_id, my_hex_value)) # Print without newline print("No newline after this!", end='')
# Name mangling for double underscore and less than one trailing underscores class Foo(object): yo = None # => foo_object.yo _yo = None # => foo_object._yo __yo = None # => foo_object._Foo__yo __yo__ = None # => foo_object.__yo__ # To copy an object import copy inst2 = copy.copy(inst1)
import argparse def parse_arguments(): parser = argparse.ArgumentParser(description="Some description",epilog="Huh?") parser.add_argument('integers', metavar='N', type=int, nargs='+', help='an integer for the accumulator') parser.add_argument('--sum', dest='accumulate', action='store_const', const=sum, default=max, help='sum the integers (default: find the max)') parser.add_argument('-v', '--verbose', action='store_true', help='Verbose mode') args = parser.parse_args() return args def main(): args = parse_arguments() if args.verbose: print(dir(args)) if __name__ == '__main__': main()
import signal def signal_handler_C_c(sig, frame): print('C-c detected, exiting..') def main(): signal.signal(signal.SIGINT, signal_handler_C_c)
https://docs.python.org/3/tutorial/errors.html
# Catch exceptions a_list = ['yo', 'man'] try: print(a_list[3]) except IndexError: print("Index out of range! :(") a_list = ['yo', 'man'] try: print(a_list[3]) except Exception as e: print("Ett fel har uppstått...") print(e) print(type(e))
# Raise exceptions: raise ValueError("Passed array is not of the right shape")
Syntactic sugar based on functions that return function objects.
Good guide, much of the info here is stolen from this site.
# Given this function, which is called a decorator function def my_decorator(func): def wrapper(): print("I got decorated!") func() return wrapper # Then one could write something like this def boring(): print("Normal function") pimped_boring = my_decorator(boring) pimped_boring() # Or one could overwrite the boring function name def boring(): print("Normal function") boring = my_decorator(boring) # which is equivalent to write this short-cut syntax @my_decorator def boring(): print("Normal function")
# Given the two decorators def star(func): def inner(*args, **kwargs): print("*" * 30) func(*args, **kwargs) print("*" * 30) return inner def percent(func): def inner(*args, **kwargs): print("%" * 30) func(*args, **kwargs) print("%" * 30) return inner # Then @star @percent def printer(msg): print(msg) # is equivalent to def printer(msg): print(msg) printer = star(percent(printer))
class MyClass(object): def __init__(self): self._my_property_value = None # Placeholder variable, so getter function works self.my_property = 123 # Will call the proper setter function @property def my_property(self): return self._my_property_value @my_property.setter def my_property(self, value): if value < 0: self._my_property_value = -value * 10 else: self._my_property_value = value/10 my_instance = MyClass() my_instance.my_property = -30 print(my_instance.my_property) # Prints 300