├── .gitignore ├── README.md ├── classes.py ├── dictionaries.py ├── errors.py ├── functions.py ├── if_statements.py ├── lists.py ├── loop_clauses.py ├── loops.py ├── match.py ├── modules.py ├── numbers.py ├── sets.py ├── strings.py └── tuples.py /.gitignore: -------------------------------------------------------------------------------- 1 | project.py 2 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Python Course for Beginners 2 | 3 | Welcome to the supporting doc's to my 'Python Course For Beginners' 4 | 5 | ![Python course for beginners](https://static.didcoding.com/media/tutorials/Python_course.jpg "Python Course For Beginners") 6 | 7 | Feel free to use this repo as a 'cheat sheet' 8 | 9 | ## Get your own copy of this repo 10 | 1. Navigate to your development directory on you machine 11 | 2. Open a Git terminal 12 | 3. Use the following commands to clone this repo: 13 | 14 | ``` 15 | git clone git@github.com:bobby-didcoding/python-course-for-beginners.git 16 | ``` 17 | 18 | ## More references 19 | checkout Python's documentation pages here 20 | 21 | ## About us 22 | We create easy to follow coding tutorials on our YouTube channel and on our main website. You should come and have a look :) 23 | -------------------------------------------------------------------------------- /classes.py: -------------------------------------------------------------------------------- 1 | # Python classes 2 | 3 | ''' 4 | Classes provide a means of bundling data and functionality together. Creating a 5 | new class creates a new type of object, allowing new instances of that type to be 6 | made. 7 | 8 | Python classes provide all the standard features of Object Oriented Programming. 9 | The class inheritance mechanism allows multiple base classes, a derived class 10 | can override any methods of its base class or classes, and a method can call 11 | the method of a base class with the same name. 12 | 13 | The simplest form of class definition looks like this: 14 | class ClassName: 15 | 16 | . 17 | . 18 | . 19 | 20 | 21 | Class definitions, like function definitions (def statements) must be executed 22 | before they have any effect. 23 | ''' 24 | 25 | #basics 26 | 27 | class MyClass: 28 | """A simple example class""" 29 | i = 12345 30 | 31 | def f(self): 32 | return 'hello world' 33 | 34 | MyClass.i # return the int 35 | MyClass.f # returns a function object 36 | MyClass.__doc__ # magic method/dunder method that return the text literal 37 | 38 | x = MyClass() #instantiates the class 39 | x.i # return the int 40 | x.f() # calls the class method 41 | 42 | ''' 43 | Notice how self is passed as the first arg!! 44 | We pass the methods instance object in as the first arg! 45 | so x.f() is the equivalent of MyClass.f(x) 46 | Note: 'self' has no special meaning to Python - it's just convention 47 | ''' 48 | 49 | #Class with special initial state - we user __init__ 50 | #allows us to pass args to the class for greater flexibility 51 | class MyClass: 52 | """A simple example class""" 53 | def __init__(self, my_int:int): 54 | self.i = my_int 55 | 56 | def f(self): 57 | new = self.i ** 3 58 | return new 59 | 60 | x = MyClass(4) #instantiates the class 61 | x.i # return the int 62 | x.f() # calls the class method 63 | 64 | #Instance objects 65 | #We can add and delete attributs to our object 66 | 67 | x.counter = 1 # Add a data attribute and assign a value 68 | while x.counter < 10: 69 | x.counter = x.counter * 2 70 | #first loop x.counter == 2 71 | #second loop x.counter == 4 72 | #third loop x.counter == 8 73 | #forth loop x.counter == 16 74 | #fifth loop does not start as x.counter > 10 75 | 76 | print(x.counter) #prints 16 77 | del x.counter # delete the data attribute 78 | print(x.counter) # AttributeError 79 | 80 | #Class and Instance Variables 81 | class Dog: 82 | kind = 'canine' # class variable shared by all instances 83 | def __init__(self, name): 84 | self.name = name# instance variable unique to each instance 85 | self.tricks = [] 86 | def add_trick(self, trick): 87 | self.tricks.append(trick) 88 | 89 | d = Dog('Fido') 90 | e = Dog('Buddy') 91 | d.kind 92 | e.kind 93 | d.name 94 | e.name 95 | d.add_trick('roll over') 96 | e.add_trick('play dead') 97 | d.tricks 98 | 99 | #Inheritance 100 | 101 | ''' 102 | class DerivedClassName(Base1, Base2, Base3): 103 | 104 | . 105 | . 106 | . 107 | 108 | 109 | Execution of a derived class definition proceeds the same as for a base 110 | class. When the class object is constructed, the base class is remembered. 111 | This is used for resolving attribute references: if a requested attribute 112 | is not found in the class, the search proceeds to look in the base class. 113 | This rule is applied recursively if the base class itself is derived from 114 | some other class. 115 | 116 | Derived classes may extend or override methods of their base classes. 117 | ''' 118 | 119 | class Mapping: 120 | ''' 121 | Private variable example. 122 | checkout __update - this is called name mangling 123 | Is done without regard to syntactical position 124 | ''' 125 | def __init__(self, iterable): 126 | self.items_list = [] 127 | self.iterable = iterable 128 | 129 | def update(self): 130 | for item in self.iterable: 131 | self.items_list.append(item) 132 | 133 | class MappingSubclass(Mapping): 134 | def update(self, keys, values): 135 | # provides new signature for update() 136 | # but does not break __init__() 137 | for item in zip(keys, values): 138 | self.items_list.append(item) 139 | 140 | m = MappingSubclass([1,2,3,4]) 141 | m.items_list 142 | m.update(["one","two","three"], ["these", "are", "values"]) 143 | m.items_list 144 | -------------------------------------------------------------------------------- /dictionaries.py: -------------------------------------------------------------------------------- 1 | #Using python to manipulate dictionary 2 | 3 | ''' 4 | Python knows a number of compound data types, 5 | used to group together other values. One of the 6 | most used is a dictionary 7 | Others include: 8 | tuple 9 | list 10 | set 11 | 12 | Dictionaries are used to store data values in key:value pairs. 13 | 14 | some_dict = { 15 | 'a_key': 'a_value', 16 | 'a_key_2': 'a_value_2', 17 | 'a_key_3': ['a_list', 'as', 'a value'], 18 | 'a_key_4': {'a_dict': 'as a value'} 19 | } 20 | 21 | Dictionaries are mutable - this means that item values can be changed 22 | 23 | Dictionaries have a bunch of methods available. 24 | clear() Removes all the elements from the dictionary 25 | copy() Returns a copy of the dictionary 26 | fromkeys() Returns a dictionary with the specified keys and value 27 | get() Returns the value of the specified key 28 | items() Returns a list containing a tuple for each key value pair 29 | keys() Returns a list containing the dictionary's keys 30 | pop() Removes the element with the specified key 31 | popitem() Removes the last inserted key-value pair 32 | setdefault() Returns the value of the specified key. If the key does not exist: 33 | insert the key, with the specified value 34 | update() Updates the dictionary with the specified key-value pairs 35 | values() Returns a list of all the values in the dictionary 36 | ''' 37 | 38 | #The basics 39 | some_dict = { 40 | 'a_key': 'a_value', 41 | 'a_key_2': 'a_value_2', 42 | 'a_key_3': ['a_list', 'as', 'a value'], 43 | 'a_key_4': {'a_dict': 'as a value'} 44 | } 45 | some_dict 46 | 47 | 48 | some_dict[0] # this will return an error as you need to ref the key by name 49 | some_dict['a_key'] 50 | some_dict['a_key_4'] 51 | 52 | 53 | #Create a dict copy 54 | some_dict.copy() 55 | 56 | #altering a dict 57 | some_dict['a_key'] = 'new_value' 58 | some_dict['a_key'] 59 | 60 | #Length 61 | len(some_dict) 62 | 63 | #show all keys and values 64 | some_dict.keys() 65 | some_dict.values() 66 | 67 | 68 | #Dict comprehension 69 | {x: x**2 for x in (2, 4, 6)} 70 | 71 | #built-in function dict() 72 | x = dict(a=1, b=2, c=3, d=4)# creates a dictionary object 73 | x -------------------------------------------------------------------------------- /errors.py: -------------------------------------------------------------------------------- 1 | #Handling errors 2 | 3 | ''' 4 | Python has (at least) two distinguishable kinds of errors: 5 | syntax errors and exceptions. 6 | 7 | Syntax errors: Also known as parsing errors, are perhaps the 8 | most common kind of complaint you get while you are still learning Python. 9 | 10 | Exceptions: Errors detected during execution are called exceptions and are not 11 | unconditionally fatal: you will soon learn how to handle them in Python programs. 12 | 13 | Here are all of Pythons built-in exception 14 | ArithmeticError Raised when an error occurs in numeric calculations 15 | AssertionError Raised when an assert statement fails 16 | AttributeError Raised when attribute reference or assignment fails 17 | Exception Base class for all exceptions 18 | EOFError Raised when the input() method hits an "end of file" condition (EOF) 19 | FloatingPointError Raised when a floating point calculation fails 20 | GeneratorExit Raised when a generator is closed (with the close() method) 21 | ImportError Raised when an imported module does not exist 22 | IndentationError Raised when indentation is not correct 23 | IndexError Raised when an index of a sequence does not exist 24 | KeyError Raised when a key does not exist in a dictionary 25 | KeyboardInterrupt Raised when the user presses Ctrl+c, Ctrl+z or Delete 26 | LookupError Raised when errors raised cant be found 27 | MemoryError Raised when a program runs out of memory 28 | NameError Raised when a variable does not exist 29 | NotImplementedError Raised when an abstract method requires an inherited class to override the method 30 | OSError Raised when a system related operation causes an error 31 | OverflowError Raised when the result of a numeric calculation is too large 32 | ReferenceError Raised when a weak reference object does not exist 33 | RuntimeError Raised when an error occurs that do not belong to any specific expections 34 | StopIteration Raised when the next() method of an iterator has no further values 35 | SyntaxError Raised when a syntax error occurs 36 | TabError Raised when indentation consists of tabs or spaces 37 | SystemError Raised when a system error occurs 38 | SystemExit Raised when the sys.exit() function is called 39 | TypeError Raised when two different types are combined 40 | UnboundLocalError Raised when a local variable is referenced before assignment 41 | UnicodeError Raised when a unicode problem occurs 42 | UnicodeEncodeError Raised when a unicode encoding problem occurs 43 | UnicodeDecodeError Raised when a unicode decoding problem occurs 44 | UnicodeTranslateError Raised when a unicode translation problem occurs 45 | ValueError Raised when there is a wrong value in a specified data type 46 | ZeroDivisionError Raised when the second operator in a division is zero 47 | ''' 48 | #Basic examples 49 | 10 * (1/0) 50 | 4 + spam*3 51 | '2' + 2 52 | 53 | #Handling exceptions 54 | 55 | while True: 56 | try: 57 | x = int(input("Please enter a number: ")) 58 | break 59 | #Add multiple exceptions in a tuple (RuntimeError, TypeError, NameError) 60 | except (RuntimeError, TypeError, NameError, ValueError): 61 | print("Oops! That was no valid number. Try again...") 62 | 63 | 64 | def this_fails(): 65 | x = 1/0 66 | 67 | try: 68 | this_fails() 69 | except ZeroDivisionError as err: 70 | print('Handling run-time error:', err) 71 | 72 | 73 | ''' 74 | The try/except statement has an optional else clause, which, when present, 75 | must follow all except clauses. It is useful for code that must be executed 76 | if the try clause does not raise an exception. 77 | 78 | If a finally clause is present, the finally clause will execute as the last 79 | task before the try statement completes. The finally clause runs whether or 80 | not the try statement produces an exception. The following points discuss 81 | more complex cases when an exception occurs. 82 | ''' 83 | def divide(x, y): 84 | try: 85 | result = x / y 86 | except ZeroDivisionError: 87 | print("division by zero!") 88 | except TypeError: 89 | print("Must be int!") 90 | else: 91 | print("result is", result) 92 | finally: 93 | print("executing finally clause") 94 | 95 | divide(2, 1) 96 | divide(2, 0) 97 | divide("2", "1") -------------------------------------------------------------------------------- /functions.py: -------------------------------------------------------------------------------- 1 | #Python functions 2 | 3 | ''' 4 | Think of a function as a little named container for a group of your code! 5 | 6 | To run the code in a function, you must call the function. 7 | 8 | A function can be called from anywhere after the function is defined. 9 | 10 | example... 11 | >>>def demo_func(param:int): 12 | ... """This is just a demo 13 | ... function. 14 | ... """ 15 | ... calc = param + 4 16 | ... return calc 17 | 18 | >>>demo_func(6) 19 | 10 20 | 21 | Functions can return a value using a return statement. Functions are 22 | a common feature among all programming languages 23 | 24 | The keyword def introduces a function definition. It must be followed 25 | by the function name and the parenthesized list of formal parameters. 26 | The statements that form the body of the function start at the next line, 27 | and must be indented. 28 | 29 | def demo_func(param:int): 30 | """This is just a demo 31 | function. 32 | """ 33 | calc = param + 4 34 | return calc 35 | 36 | There are 3 forms of function arguments 37 | 1) Position only arguments 38 | 2) Positional or keyword arguments 39 | 3) Keyword only arguments (named parameters) 40 | ''' 41 | 42 | #basics 43 | def demo_func(param:int): 44 | """This is just a demo 45 | function. 46 | """ 47 | calc = param + 4 48 | return calc 49 | 50 | demo_func(6) 51 | 52 | 53 | #function arguments 54 | def standard_arg(arg): 55 | print(arg) 56 | 57 | def pos_only_arg(arg, /): 58 | print(arg) 59 | 60 | def kwd_only_arg(*, arg): 61 | print(arg) 62 | 63 | def combined_example(pos_only, /, standard, *, kwd_only): 64 | print(pos_only, standard, kwd_only) 65 | ''' 66 | def combined_example(pos_only, /, standard, *, kwd_only): 67 | -------- -------- --------- 68 | | | | 69 | | Positional or keyword | 70 | | | 71 | -- Positional only --Keyword only 72 | ''' 73 | standard_arg(2) 74 | pos_only_arg(2) 75 | kwd_only_arg(arg=2) 76 | combined_example(2, 2, kwd_only=2) 77 | combined_example(2, standard=2, kwd_only=2) 78 | 79 | ''' 80 | As guidance: 81 | 82 | Use positional-only if you want the name of the parameters to not 83 | be available to the user. This is useful when parameter names have 84 | no real meaning, if you want to enforce the order of the arguments 85 | when the function is called or if you need to take some positional 86 | parameters and arbitrary keywords. 87 | 88 | Use keyword-only when names have meaning and the function definition 89 | is more understandable by being explicit with names or you want to 90 | prevent users relying on the position of the argument being passed. 91 | 92 | For an API, use positional-only to prevent breaking API changes if 93 | the parameter’s name is modified in the future. 94 | ''' 95 | 96 | -------------------------------------------------------------------------------- /if_statements.py: -------------------------------------------------------------------------------- 1 | #Python control flows - If statement 2 | 3 | ''' 4 | Python uses the usual flow control statements known 5 | from other languages, with some twists. 6 | Perhaps the most well-known statement type is the 7 | if statement. 8 | 9 | 10 | Think of an if statement as a way to check to see if 11 | conditions are met! 12 | 13 | If a condition is met, do something... 14 | else do something different! 15 | 16 | 'elif' stands for 'else if' 17 | 18 | both elif and else are optional! 19 | 20 | Note: I will be defining a function to demo :) 21 | ''' 22 | 23 | #The basics 24 | def number_play(x): 25 | if x < 0: 26 | x = 0 27 | print('Negative changed to zero') 28 | elif x == 0: 29 | print('Zero') 30 | elif x == 1: 31 | print('Single') 32 | else: 33 | print('More') 34 | 35 | number_play(-1) 36 | number_play(0) 37 | number_play(1) 38 | number_play(2) 39 | -------------------------------------------------------------------------------- /lists.py: -------------------------------------------------------------------------------- 1 | #Using python to manipulate lists 2 | 3 | ''' 4 | Python knows a number of compound data types, 5 | used to group together other values. The most 6 | versatile of which is a list. 7 | Others include: 8 | tuple 9 | dictionary 10 | set 11 | 12 | Lists are written as a list of comma-separated 13 | values (items) between square brackets 14 | 15 | Lists are mutable - this means that items can be changed 16 | 17 | List have a bunch of methods available. 18 | append() Adds an element at the end of the list 19 | clear() Removes all the elements from the list 20 | copy() Returns a copy of the list 21 | count() Returns the number of elements with the specified value 22 | extend() Add the elements of a list (or any iterable), to the end of the current list 23 | index() Returns the index of the first element with the specified value 24 | insert() Adds an element at the specified position 25 | pop() Removes the element at the specified position 26 | remove() Removes the first item with the specified value 27 | reverse() Reverses the order of the list 28 | sort() Sorts the list 29 | ''' 30 | 31 | #The basics 32 | squares = [1, 4, 9, 16, 25] 33 | squares 34 | 35 | #Indexing 36 | ''' 37 | +---+---+---+---+---+---+---+---+---+ 38 | | D | i | d | C | o | d | i | n | g | 39 | +---+---+---+---+---+---+---+---+---+ 40 | 0 1 2 3 4 5 6 7 8 41 | -9 -8 -7 -6 -5 -4 -3 -2 -1 42 | ''' 43 | 44 | squares[0] # indexing returns the item 45 | squares[-1] 46 | squares[-3:] # slicing returns a new list 47 | 48 | 49 | #Create a list copy 50 | squares[:] 51 | 52 | #Concatenation (glue together) 53 | squares + [36, 49, 64, 81, 100] 54 | 55 | #Alter items 56 | cubes = [1, 8, 27, 65, 125] # something's wrong here 57 | 4 ** 3 # the cube of 4 is 64, not 65! 58 | cubes[3] = 64 # replace the wrong value 59 | cubes 60 | 61 | #list methods 62 | cubes.append(216) # add the cube of 6 63 | cubes.append(7 ** 3) # and the cube of 7 64 | cubes 65 | 66 | #Length 67 | letters = ['a', 'b', 'c', 'd'] 68 | len(letters) 69 | 70 | 71 | #Nesting 72 | a = ['a', 'b', 'c'] 73 | n = [1, 2, 3] 74 | x = [a, n] 75 | x 76 | x[0] 77 | x[0][1] 78 | 79 | 80 | #List comprehension 81 | y = [] 82 | for x in range(10): 83 | y.append(x**2) 84 | 85 | y 86 | y = [x**2 for x in range(10)] 87 | y 88 | 89 | #built-in function list() 90 | x = list(('bobby', 'at', 'didcoding','dot', 'com')) # creates a list object 91 | x 92 | -------------------------------------------------------------------------------- /loop_clauses.py: -------------------------------------------------------------------------------- 1 | #Python control flows - Loop clauses 2 | 3 | ''' 4 | Python has a few statements and clauses that we can use in loops. 5 | These are: 6 | break 7 | continue 8 | else 9 | pass 10 | 11 | Loop statements may have an else clause; it is executed when the 12 | loop terminates through exhaustion of the iterable (with for) or 13 | when the condition becomes false (with while), but not when the 14 | loop is terminated by a break statement. 15 | ''' 16 | 17 | #Break statement 18 | for n in range(2, 10): #equivalent of...for n in [2,3,4,5,6,7,8,9]: 19 | for x in range(2, n): #first loop is for x in range(2, 2): 20 | if n % x == 0: 21 | print(n, 'equals', x, '*', n//x) 22 | break 23 | #the else runs when no break clause occurs 24 | else: 25 | print(n, 'is a prime number') 26 | 27 | 28 | #Continue statement 29 | for num in range(2, 10): #equivalent of...for n in [2,3,4,5,6,7,8,9]: 30 | if num % 2 == 0: 31 | print("Found an even number", num) 32 | continue #Will continue with the next loop 33 | print("Found an odd number", num) 34 | 35 | 36 | #Pass statement 37 | class MyPassClass: 38 | pass 39 | 40 | 41 | def my_pass_def(*args): 42 | pass #Needs looking at -------------------------------------------------------------------------------- /loops.py: -------------------------------------------------------------------------------- 1 | #Python control flows - Loops 2 | 3 | ''' 4 | Python’s for statement iterates over the items of any sequence 5 | (a list or a string), in the order that they appear in the 6 | sequence. 7 | 8 | The built-in Range function 'range()' comes in handy if you do need 9 | to iterate over a sequence of numbers. It generates arithmetic progressions: 10 | 11 | range(start, stop, step) 12 | start 13 | The value of the start parameter (or 0 if the parameter was not supplied) 14 | stop 15 | The value of the stop parameter 16 | step 17 | The value of the step parameter (or 1 if the parameter was not supplied) 18 | ''' 19 | 20 | #The basics 21 | words = ['cat', 'window', 'defenestrate'] 22 | for w in words: 23 | print(w, len(w)) 24 | 25 | # Create a sample collection 26 | users = { 27 | 'Quinn': 'active', 28 | 'Éléonore': 'inactive', 29 | 'John': 'active' 30 | } 31 | 32 | # Strategy: Iterate over a copy 33 | for user, status in users.copy().items(): 34 | if status == 'inactive': 35 | del users[user] 36 | 37 | # Strategy: Create a new collection 38 | active_users = {} 39 | for user, status in users.items(): 40 | if status == 'active': 41 | active_users[user] = status 42 | 43 | 44 | #using the range function 45 | for i in range(5): 46 | print(i) 47 | 48 | #...remember range(start, stop, step) 49 | list(range(5, 10)) 50 | list(range(0, 10, 3)) 51 | list(range(-10, -100, -30)) 52 | 53 | a = ['Mary', 'had', 'a', 'little', 'lamb'] 54 | for i in range(len(a)): 55 | print(i, a[i]) 56 | 57 | #using the built-in sum function 58 | sum(range(4)) -------------------------------------------------------------------------------- /match.py: -------------------------------------------------------------------------------- 1 | #Python control flows - Match statement 2 | 3 | ''' 4 | Hot off the press in Python 3.10 5 | 6 | Structural pattern matching has been added in the form of a match 7 | statement and case statements of patterns with associated actions. 8 | Patterns consist of sequences, mappings, primitive data types as 9 | well as class instances. Pattern matching enables programs to extract 10 | information from complex data types, branch on the structure of data, 11 | and apply specific actions based on different forms of data. 12 | 13 | A match statement takes an expression and compares its value to 14 | successive patterns given as one or more case blocks. 15 | 16 | Note: We have a class in this demo. Don't get too caught up in how it 17 | works! We have a class video in this course :) 18 | ''' 19 | 20 | #basics 21 | def http_error(status): 22 | match status: 23 | case 400: 24 | return "Bad request" 25 | case 404: 26 | return "Not found" 27 | case 418: 28 | return "I'm a teapot" 29 | case _: 30 | return "Something's wrong with the internet" 31 | 32 | def http_error(status): 33 | match status: 34 | case 400 | 401 | 403 | 404: 35 | return "Not allowed" 36 | case 418: 37 | return "I'm a teapot" 38 | case _: 39 | return "Something's wrong with the internet" 40 | 41 | 42 | #Patterns can look like unpacking assignments, and can be used to bind variables: 43 | # point is an (x, y) tuple 44 | def http_error(point): 45 | match point: 46 | case (0, 0): 47 | print("Origin") 48 | case (0, y): 49 | print(f"Y={y}") 50 | case (x, 0): 51 | print(f"X={x}") 52 | case (x, y): 53 | print(f"X={x}, Y={y}") 54 | case _: 55 | raise ValueError("Not a point") 56 | 57 | point_tuple = (0,0) 58 | point_tuple = (0,123) 59 | point_tuple = (123,0) 60 | point_tuple = (123,456) 61 | 62 | 63 | 64 | #Match class 65 | from dataclasses import dataclass 66 | @dataclass 67 | class Point: 68 | x: int 69 | y: int 70 | 71 | def where_is(point): 72 | match point: 73 | case Point(x=0, y=0): 74 | print("Origin") 75 | case Point(x=0, y=y): 76 | print(f"Y={y}") 77 | case Point(x=x, y=0): 78 | print(f"X={x}") 79 | case Point(): 80 | print("Somewhere else") 81 | case _: 82 | print("Not a point") 83 | 84 | where_is(Point(0, 0)) 85 | where_is(Point(0, 10)) 86 | where_is(Point(10, 0)) 87 | where_is(Point(10, 10)) -------------------------------------------------------------------------------- /modules.py: -------------------------------------------------------------------------------- 1 | #Modules 2 | 3 | ''' 4 | In Python we are able to write a long program and save as a module. This 5 | is known as creating a script. We are able to import modules across modules 6 | and into the Python interpreter. This negates the need to keep repeating 7 | ourselves. 8 | DRY!....Don't repeat yourself 9 | 10 | Pythons standard library can be found here https://docs.python.org/3/library/ 11 | ''' 12 | 13 | 14 | from functions import demo_func 15 | 16 | def func_1(arg:int): 17 | x = [y for y in range(2, 10, 2)] 18 | x.append(arg) 19 | print(x) 20 | 21 | def func_2(number:int, power:int): 22 | print(pow(number,power)) 23 | -------------------------------------------------------------------------------- /numbers.py: -------------------------------------------------------------------------------- 1 | #Using python as a calculator 2 | 3 | ''' 4 | We can use the interpreter to take an input and return an output! 5 | 6 | Arithmetic Opperators: 7 | We have a whole bunch of opperators at our disposal 8 | + Addition 9 | - Subtraction 10 | * Multiplication 11 | / Division 12 | // Floor division 13 | % Modulus (remainder of x / y) | use divmod(a, b) 14 | ** Exponentiation (power of) | can also use pow(x , y) instead of x**y 15 | 16 | Assignment Opperators: 17 | = Equals 18 | 19 | Number Types: 20 | int (2, 3, 458, 678) 21 | float (2.2, 3.5, 5.666675678) 22 | 23 | Build in Function: 24 | round() Rounds a numbers with the specified number of 25 | decimals i.e. round(number, decimals) 26 | 27 | 28 | lastly, Python has a handy way of making big int's easier to read 29 | 4000000000 can be written as 30 | 4_000_000_000 31 | ''' 32 | 33 | 34 | #The basics 35 | 2 + 2 # simple addition 36 | 5 - 2 # simple subtraction 37 | 7 * 10 # simple multiplication 38 | 39 | #Division and Modulus 40 | 10 / 4 # classic division returns a float 41 | 10 // 4 # floor division discards the fractional part 42 | 10 % 4 # the % operator returns the remainder of the division 43 | divmod(10,4) 44 | 45 | #Fancy sums 46 | 50 - 5*6 47 | (50 - 5*6) / 4 48 | 5 * 3 + 2 # floored quotient * divisor + remainder 49 | 50 | #Exponentiation (power of) 51 | 5 ** 2 # 5 squared 52 | 2 ** 7 # 2 to the power of 7 53 | pow(2,7) 54 | 55 | #Using variables 56 | width = 60 57 | height = 3 * 7 58 | width * height 59 | 60 | 61 | #In interactive mode, the last printed expression is assigned to the variable _. 62 | tax = 12.5 / 100 63 | price = 100.50 64 | price * tax #this is assigned to '_' and we use it in the next expression 65 | price + _ #We reference '_' but this expression is now assigned to '_' 66 | round(_, 2) 67 | -------------------------------------------------------------------------------- /sets.py: -------------------------------------------------------------------------------- 1 | #Using python to manipulate sets 2 | 3 | ''' 4 | Python knows a number of compound data types, 5 | used to group together other values. 6 | They are: 7 | tuple 8 | dictionary 9 | set 10 | list 11 | 12 | A Set is an unordered collection with no duplicate elements. Like a dictionary, 13 | a set is defined by a curly bracket. 14 | 15 | Sets are mutable - this means that items can be changed. 16 | 17 | Set has a whole bunch of methods available. 18 | add() Adds an element to the set 19 | clear() Removes all the elements from the set 20 | copy() Returns a copy of the set 21 | difference() Returns a set containing the difference between two or more sets 22 | difference_update() Removes the items in this set that are also included in another, specified set 23 | discard() Remove the specified item 24 | intersection() Returns a set, that is the intersection of two or more sets 25 | intersection_update() Removes the items in this set that are not present in other, specified set(s) 26 | isdisjoint() Returns whether two sets have a intersection or not 27 | issubset() Returns whether another set contains this set or not 28 | issuperset() Returns whether this set contains another set or not 29 | pop() Removes an element from the set 30 | remove() Removes the specified element 31 | symmetric_difference() Returns a set with the symmetric differences of two sets 32 | symmetric_difference_update() Inserts the symmetric differences from this set and another 33 | union() Return a set containing the union of sets 34 | update() Update the set with another set, or any other iterable 35 | ''' 36 | 37 | #The basics 38 | basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} 39 | print(basket)# show that duplicates have been removed 40 | 41 | 'orange' in basket # fast membership testing 42 | 'crabgrass' in basket 43 | 44 | # Demonstrate set operations on unique letters from two words 45 | a = set('abracadabra') 46 | b = set('alacazam') 47 | a # unique letters in a 48 | a - b # letters in a but not in b 49 | a | b # letters in a or b or both 50 | a & b # letters in both a and b 51 | a ^ b # letters in a or b but not both 52 | 53 | 54 | #Set comprehension 55 | a = {x for x in 'abracadabra' if x not in 'abc'} 56 | 57 | #built-in function set() 58 | x = set(('bobby','bobby', 'at', 'didcoding','dot', 'com')) # creates a set object 59 | x -------------------------------------------------------------------------------- /strings.py: -------------------------------------------------------------------------------- 1 | #Using python to manipulate strings 2 | 3 | ''' 4 | Python can be used to manipulate strings, which can 5 | be expressed in several ways. 6 | 7 | They can be enclosed in single quotes ('...') 8 | or double quotes ("...") 9 | 10 | '\' can be used to escape quotes 11 | 12 | Python strings cannot be changed — they are immutable. 13 | 14 | We will also look at the built in function called len() 15 | This function returns the length of a string: 16 | 17 | Strings have a bunch of methods available. 18 | capitalize() Converts the first character to upper case 19 | casefold() Converts string into lower case 20 | center() Returns a centered string 21 | count() Returns the number of times a specified value occurs in a string 22 | encode() Returns an encoded version of the string 23 | endswith() Returns true if the string ends with the specified value 24 | expandtabs() Sets the tab size of the string 25 | find() Searches the string for a specified value and returns the position of where it was found 26 | format() Formats specified values in a string 27 | format_map() Formats specified values in a string 28 | index() Searches the string for a specified value and returns the position of where it was found 29 | isalnum() Returns True if all characters in the string are alphanumeric 30 | isalpha() Returns True if all characters in the string are in the alphabet 31 | isascii() Returns True if all characters in the string are ascii characters 32 | isdecimal() Returns True if all characters in the string are decimals 33 | isdigit() Returns True if all characters in the string are digits 34 | isidentifier() Returns True if the string is an identifier 35 | islower() Returns True if all characters in the string are lower case 36 | isnumeric() Returns True if all characters in the string are numeric 37 | isprintable() Returns True if all characters in the string are printable 38 | isspace() Returns True if all characters in the string are whitespaces 39 | istitle() Returns True if the string follows the rules of a title 40 | isupper() Returns True if all characters in the string are upper case 41 | join() Converts the elements of an iterable into a string 42 | ljust() Returns a left justified version of the string 43 | lower() Converts a string into lower case 44 | lstrip() Returns a left trim version of the string 45 | maketrans() Returns a translation table to be used in translations 46 | partition() Returns a tuple where the string is parted into three parts 47 | replace() Returns a string where a specified value is replaced with a specified value 48 | rfind() Searches the string for a specified value and returns the last position of where it was found 49 | rindex() Searches the string for a specified value and returns the last position of where it was found 50 | rjust() Returns a right justified version of the string 51 | rpartition() Returns a tuple where the string is parted into three parts 52 | rsplit() Splits the string at the specified separator, and returns a list 53 | rstrip() Returns a right trim version of the string 54 | split() Splits the string at the specified separator, and returns a list 55 | splitlines() Splits the string at line breaks and returns a list 56 | startswith() Returns true if the string starts with the specified value 57 | strip() Returns a trimmed version of the string 58 | swapcase() Swaps cases, lower case becomes upper case and vice versa 59 | title() Converts the first character of each word to upper case 60 | translate() Returns a translated string 61 | upper() Converts a string into upper case 62 | zfill() Fills the string with a specified number of 0 values at the beginning 63 | ''' 64 | 65 | #The basics 66 | 'spam eggs' # single quotes 67 | 'doesn\'t' # use \' to escape the single quote... 68 | "doesn't" # ...or use double quotes instead 69 | '"Yes," they said.' 70 | "\"Yes,\" they said." 71 | 72 | 73 | #New line 74 | s = 'First line.\nSecond line.' # \n means newline 75 | s # without print(), \n is included in the output 76 | 77 | print(s) # with print(), \n produces a new line 78 | 79 | #Raw string 80 | print('C:\some\name') # here \n means newline! 81 | print(r'C:\some\name') # note the r before the quote 82 | 83 | 84 | #String literals 85 | print("""\ 86 | Usage: thingy [OPTIONS] 87 | -h Display this usage message 88 | -H hostname Hostname to connect to 89 | """) 90 | 91 | 92 | #Concatenated 93 | 3 * 'un' + 'ium' 94 | 'Did' 'Coding' 95 | text = ('Put several strings within parentheses ' 96 | 'to have them joined together.') 97 | text 98 | #This only works with two literals though, 99 | #not with variables or expressions: 100 | prefix = 'Did' 101 | prefix 'Coding' 102 | prefix + 'Coding' 103 | 104 | #Indexing 105 | ''' 106 | +---+---+---+---+---+---+---+---+---+ 107 | | D | i | d | C | o | d | i | n | g | 108 | +---+---+---+---+---+---+---+---+---+ 109 | 0 1 2 3 4 5 6 7 8 110 | -9 -8 -7 -6 -5 -4 -3 -2 -1 111 | ''' 112 | 113 | word = 'Didcoding' 114 | word[0] # character in position 0 115 | word[5] # character in position 5 116 | word[0:2] # characters from position 0 (included) to 2 (excluded) 117 | word[2:5] # characters from position 2 (included) to 5 (excluded) 118 | word[:2] # character from the beginning to position 2 (excluded) 119 | word[4:] # characters from position 4 (included) to the end 120 | word[-2:] # characters from the second-last (included) to the end 121 | word[:2] + word[2:] 122 | word[:4] + word[4:] 123 | 124 | 125 | #changing strings 126 | word[0] = 'P' 127 | 'P' + word[1:] 128 | word[:2] + 'di' 129 | 130 | #Sting length 131 | s = 'bobby-didcoding' 132 | len(s) 133 | 134 | 135 | #Handy built-in functions 136 | ''' 137 | When you don’t need fancy output but just want a quick display 138 | of some variables for debugging purposes, you can convert any 139 | value to a string with the repr() or str() functions. 140 | 141 | The str() function is meant to return representations of values 142 | which are fairly human-readable, while repr() is meant to generate 143 | representations which can be read by the interpreter 144 | 145 | You also have format(). 146 | The format() method formats the specified value(s) and insert them 147 | inside the string's placeholder '{}'. 148 | 149 | ''' 150 | x=20 151 | y=400 152 | repr((x, y, ('spam', 'eggs'))) 153 | str((x, y, ('spam', 'eggs'))) 154 | 155 | 156 | print('{0} and {1}'.format('spam', 'eggs')) 157 | print('{1} and {0}'.format('spam', 'eggs')) -------------------------------------------------------------------------------- /tuples.py: -------------------------------------------------------------------------------- 1 | #Using python to manipulate tuples 2 | 3 | ''' 4 | Python knows a number of compound data types, 5 | used to group together other values. 6 | They are: 7 | tuple 8 | dictionary 9 | set 10 | list 11 | 12 | Tuples are written as a list of comma-separated 13 | values (items) between parentheses. 14 | 15 | 16 | Tuples are immutable - this means that items can not be changed. However, 17 | a tuple can contain mutable objects. 18 | 19 | Tuple has 2 methods available. 20 | count() Returns the number of elements with the specified value 21 | index() Returns the index of the first element with the specified value 22 | ''' 23 | 24 | #The basics - tuple packing 25 | t = 12345, 54321, 'hello!' 26 | t[0] 27 | t 28 | 29 | # Tuples may be nested: 30 | u = t, (1, 2, 3, 4, 5) 31 | u 32 | 33 | # Tuples are immutable: 34 | t[0] = 88888 35 | 36 | # but they can contain mutable objects: 37 | v = ([1, 2, 3], [3, 2, 1]) 38 | v 39 | 40 | #Indexing 41 | ''' 42 | +---+---+---+---+---+---+---+---+---+ 43 | | D | i | d | C | o | d | i | n | g | 44 | +---+---+---+---+---+---+---+---+---+ 45 | 0 1 2 3 4 5 6 7 8 46 | -9 -8 -7 -6 -5 -4 -3 -2 -1 47 | ''' 48 | 49 | t[0] # indexing returns the item 50 | t[-1] 51 | 52 | #trailing comma 53 | empty = () 54 | singleton = 'hello', 55 | len(empty) 56 | len(singleton) 57 | singleton 58 | 59 | #Unpacking a tuple 60 | x, y, z = t 61 | x 62 | y 63 | z 64 | 65 | #built-in function tuple() 66 | x = tuple(['bobby', 'at', 'didcoding','dot', 'com']) # creates a tuple object 67 | x 68 | 69 | #Tuple comprehension...Just use list comprehension with the tuple function 70 | tuple([x**2 for x in range(10)]) --------------------------------------------------------------------------------