Python

Python is a popular programming language. It was created by Guido van Rossum, and released in 1991.

It is used for:
web development (server-side),
software development,
mathematics,
system scripting.

Python
What can Python do?

Python can be used on a server to create web applications.
Python can be used alongside software to create workflows.
Python can connect to database systems. It can also read and modify files.
Python can be used to handle big data and perform complex mathematics.
Python can be used for rapid prototyping, or for production-ready software development.


Why Python?

Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
Python has a simple syntax similar to the English language.
Python has syntax that allows developers to write programs with fewer lines than some other programming languages.
Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick.
Python can be treated in a procedural way, an object-oriented way or a functional way.


Good to know
The most recent major version of Python is Python 3, which we shall be using in this tutorial. However, Python 2, although not being updated with anything other than security updates, is still quite popular.
In this tutorial Python will be written in a text editor. It is possible to write Python in an Integrated Development Environment, such as Thonny, Pycharm, Netbeans or Eclipse which are particularly useful when managing larger collections of Python files. Python Syntax compared to other programming languages
Python was designed for readability, and has some similarities to the English language with influence from mathematics.
Python uses new lines to complete a command, as opposed to other programming languages which often use semicolons or parentheses.
Python relies on indentation, using whitespace, to define scope; such as the scope of loops, functions and classes. Other programming languages often use curly-brackets for this purpose.
  1. Python Comments
    Python Comments
    Comments can be used to explain Python code.
    Comments can be used to make the code more readable.
    Comments can be used to prevent execution when testing code.
                         
                            """
                            This is a comment
                            written in
                            more than just one line
                            """
                            
    
         
            print("Hello, World!")        #This is a comment
            
    
  2. Python Variables
    Python Variables
    Variables

    Variables are containers for storing data values.


    Creating Variables
    Python has no command for declaring a variable.

    A variable is created the moment you first assign a value to it.


    Casting
    If you want to specify the data type of a variable, this can be done with casting.


    Get the Type

                     
                    print(type(x))
                
            

    variables

                     
                    x = 5
    y = "John"
                
            
  3. Variable Names
    Variable Names
    Variable Names
    A variable can have a short name (like x and y) or a more descriptive name (age, carname, total_volume). Rules for Python variables:

    A variable name must start with a letter or the underscore character
    A variable name cannot start with a number
    A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ )
    Variable names are case-sensitive (age, Age and AGE are three different variables)


    Multi Words Variable Names
    Variable names with more than one word can be difficult to read.
    There are several techniques you can use to make them more readable:

    Camel Case
    Each word, except the first, starts with a capital letter:

    Pascal Case
    Each word starts with a capital letter:

    Snake Case
    Each word is separated by an underscore character:

                                    
                                        x, y, z = "Orange", "Banana", "Cherry"
                                
                                

                                    
                                        x = y = z = "Orange"
                                
                                

                                    
                                        fruits = ["apple", "banana", "cherry"]
                                        x, y, z = fruits
                                
                                
  4. Output Variables
    Output Variables
    Normally, when you create a variable inside a function, that variable is local, and can only be used inside that function.

    To create a global variable inside a function, you can use the global keyword.
                        
                            global x  
                    
                    
  5. Python Data Types
    Python Data Types
    Built-in Data Types
    In programming, data type is an important concept.

    Variables can store data of different types, and different types can do different things.

    Python has the following data types built-in by default, in these categories:
    Text Type: str
    Numeric Types: int, float, complex
    Sequence Types: list, tuple, range
    Mapping Type: dict
    Set Types: set, frozenset
    Boolean Type: bool
    Binary Types: bytes, bytearray, memoryview
    None Type: NoneType
  6. Python Numbers
    Python Numbers
    Python Numbers
    There are three numeric types in Python:
    int
    float
    complex


    Variables of numeric types are created when you assign a value to them


    Int
    Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.

    Float
    Float, or "floating point number" is a number, positive or negative, containing one or more decimals.

    Complex
    Complex numbers are written with a "j" as the imaginary part

    Random Number
    Python does not have a random() function to make a random number, but Python has a built-in module called random that can be used to make random numbers

    Random Number

                            
                                import random                            print(random.randrange(1, 10))
                        
                        
  7. Python Casting
    Python Casting
    Specify a Variable Type
    There may be times when you want to specify a type on to a variable. This can be done with casting. Python is an object-orientated language, and as such it uses classes to define data types, including its primitive types.

    Casting in python is therefore done using constructor functions:

    int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number)
    float() - constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer)
    str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals

    Casting

                                
                                    x = int(1)   # x will be 1
    y = int(2.8) # y will be 2
    z = int("3") # z will be 3 
                            
                            
  8. Python Strings
    Python Strings
    Strings Strings in python are surrounded by either single quotation marks, or double quotation marks. 'hello' is the same as "hello".

                    
                        a = "Hello"
                
                

                    
                        a = """Lorem ipsum dolor sit amet,
    consectetur adipiscing elit,
    sed do eiusmod tempor incididunt
    ut labore et dolore magna aliqua."""
    
                

                    
                        a = "Hello, World!"
                        print(a[1])
    
                

                    
                        for x in "banana":
                        print(x)
    
                

                    
                       len(a)
    
                

                    
                        txt = "The best things in life are free!"
                        if "free" in txt:
                          print("Yes, 'free' is present.")
    
                

                    
                        txt = "The best things in life are free!"
                        if "expensive" not in txt:
                          print("No, 'expensive' is NOT present.")
    
                
  9. Slicing
    Slicing
    You can return a range of characters by using the slice syntax.

    Specify the start index and the end index, separated by a colon, to return a part of the string.

                
                    b = "Hello, World!"
                    print(b[2:5])
            
            

                
                    b = "Hello, World!"
                    print(b[:5])
    
            

                
                    b = "Hello, World!"
                    print(b[2:])
    
            

                
                    b = "Hello, World!"
    print(b[-5:-2])
    
            
  10. Modify Strings
    Modify Strings
    Python has a set of built-in methods that you can use on strings.

    format strings
    we can combine strings and numbers by using the format() method!
    The format() method takes the passed arguments, formats them, and places them in the string where the placeholders {} are

            
              a.upper()
        
        

            
            a.lower()
    
        

            
    print(a.strip()) # returns "Hello, World!"
    
        

            
                print(a.replace("H", "J"))
    
        

            
                print(a.split(",")) # returns ['Hello', ' World!']
    
        

            
    c = "Hello" + "World"
    
        

            
                quantity = 3
    itemno = 567
    price = 49.95
    myorder = "I want to pay {2} dollars for {0} pieces of item {1}."
    print(myorder.format(quantity, itemno, price))
    
        
  11. Escape Character
    Escape Character
    Code Result
    \' Single Quote
    \\ Backslash
    \n New Line
    \r Carriage Return
    \t Tab
    \b Backspace
    \f Form Feed
    \ooo Octal value
    \xhh Hex value
  12. String Methods
    String Methods
    Method Description
    capitalize() Converts the first character to upper case
    casefold() Converts string into lower case
    center() Returns a centered string
    count() Returns the number of times a specified value occurs in a string
    encode() Returns an encoded version of the string
    endswith() Returns true if the string ends with the specified value
    expandtabs() Sets the tab size of the string
    find() Searches the string for a specified value and returns the position of where it was found
    format() Formats specified values in a string
    format_map() Formats specified values in a string
    index() Searches the string for a specified value and returns the position of where it was found
    isalnum() Returns True if all characters in the string are alphanumeric
    isalpha() Returns True if all characters in the string are in the alphabet
    isdecimal() Returns True if all characters in the string are decimals
    isdigit() Returns True if all characters in the string are digits
    isidentifier() Returns True if the string is an identifier
    islower() Returns True if all characters in the string are lower case
    isnumeric() Returns True if all characters in the string are numeric
    isprintable() Returns True if all characters in the string are printable
    isspace() Returns True if all characters in the string are whitespaces
    istitle() Returns True if the string follows the rules of a title
    isupper() Returns True if all characters in the string are upper case
    join() Joins the elements of an iterable to the end of the string
    ljust() Returns a left justified version of the string
    lower() Converts a string into lower case
    lstrip() Returns a left trim version of the string
    maketrans() Returns a translation table to be used in translations
    partition() Returns a tuple where the string is parted into three parts
    replace() Returns a string where a specified value is replaced with a specified value
    rfind() Searches the string for a specified value and returns the last position of where it was found
    rindex() Searches the string for a specified value and returns the last position of where it was found
    rjust() Returns a right justified version of the string
    rpartition() Returns a tuple where the string is parted into three parts
    rsplit() Splits the string at the specified separator, and returns a list
    rstrip() Returns a right trim version of the string
    split() Splits the string at the specified separator, and returns a list
    splitlines() Splits the string at line breaks and returns a list
    startswith() Returns true if the string starts with the specified value
    strip() Returns a trimmed version of the string
    swapcase() Swaps cases, lower case becomes upper case and vice versa
    title() Converts the first character of each word to upper case
    translate() Returns a translated string
    upper() Converts a string into upper case
    zfill() Fills the string with a specified number of 0 values at the beginning
  13. Python Booleans
    Python Booleans
    Booleans represent one of two values: True or False.

    Boolean Values
    In programming you often need to know if an expression is True or False.

    You can evaluate any expression in Python, and get one of two answers, True or False.

    Evaluate Values and Variables
    The bool() function allows you to evaluate any value, and give you True or False in return,


    Most Values are True
    Almost any value is evaluated to True if it has some sort of content.
    Any string is True, except empty strings.
    Any number is True, except 0.
    Any list, tuple, set, and dictionary are True, except empty ones.
                                            
                                                bool("abc")
                                                bool(123)
                                                bool(["apple", "cherry", "banana"])
                                        
                                        
  14. Python Operators
    Python Operators
    Operators are used to perform operations on variables and values.

    Python divides the operators in the following groups:
    Arithmetic operators
    Assignment operators
    Comparison operators
    Logical operators
    Identity operators
    Membership operators
    Bitwise operators


    Python Arithmetic Operators
    Operator Name Example
    + Addition x + y
    - Subtraction x - y
    * Multiplication x * y
    / Division x / y
    % Modulus x % y
    ** Exponentiation x ** y
    // Floor division x // y


    Python Assignment Operators
    Operator Example Same As
    = x = 5 x = 5
    += x += 3 x = x + 3
    -= x -= 3 x = x - 3
    *= x *= 3 x = x * 3
    /= x /= 3 x = x / 3
    %= x %= 3 x = x % 3
    //= x //= 3 x = x // 3
    **= x **= 3 x = x ** 3
    &= x &= 3 x = x & 3
    |= x |= 3 x = x | 3
    ^= x ^= 3 x = x ^ 3
    >>= x >>= 3 x = x >> 3
    <<= x <<= 3 x = x << 3


    Python Comparison Operators
    Operator Name Example
    == Equal x == y
    != Not equal x != y
    > Greater than x > y
    < Less than x < y
    >= Greater than or equal to x >= y
    <= Less than or equal to x <= y


    Python Logical Operators
    Operator Description Example
    and  Returns True if both statements are true x < 5 and  x < 10
    or Returns True if one of the statements is true x < 5 or x < 4
    not Reverse the result, returns False if the result is true not(x < 5 and x < 10)


    Python Identity Operators
    Operator Description Example
    is  Returns True if both variables are the same object x is y
    is not Returns True if both variables are not the same object x is not y
    Python Membership Operators
    Operator Description Example
    in  Returns True if a sequence with the specified value is present in the object x in y
    not in Returns True if a sequence with the specified value is not present in the object x not in y
    Python Bitwise Operators
    Operator Name Description
    AND Sets each bit to 1 if both bits are 1
    | OR Sets each bit to 1 if one of two bits is 1
    ^ XOR Sets each bit to 1 if only one of two bits is 1
    ~ NOT Inverts all the bits
    << Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off
    >> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off
  15. Python Collections (Arrays)
    Python Collections (Arrays)
    There are four collection data types in the Python programming language:

    List is a collection which is ordered and changeable. Allows duplicate members.
    Tuple is a collection which is ordered and unchangeable. Allows duplicate members.
    Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
    Dictionary is a collection which is ordered** and changeable. No duplicate members.
  16. Python Lists
    Python Lists
    Lists are used to store multiple items in a single variable.

    Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set, and Dictionary, all with different qualities and usage.


    List Items
    List items are ordered, changeable, and allow duplicate values.
    List items are indexed, the first item has index [0], the second item has index [1] etc.

    Ordered
    When we say that lists are ordered, it means that the items have a defined order, and that order will not change.
    If you add new items to a list, the new items will be placed at the end of the list.

    Changeable
    The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.

    Allow Duplicates
    Since lists are indexed, lists can have items with the same value:

    List Length
    To determine how many items a list has, use the len() function


    Negative Indexing
    Negative indexing means start from the end
    -1 refers to the last item, -2 refers to the second last item etc.

                                            
                                                thislist = ["apple", "banana", "cherry"]
    print(thislist)   
                                        
                                        

                                        
                                            len(thislist)
                                    
                                    

                                            
                                                type(mylist) 
                                        
                                        

                                            
                                                thislist = list(("apple", "banana", "cherry"))    # note the double round-brackets
                                        
                                        

                                            
                                                thislist = ["apple", "banana", "cherry"]
                                                print(thislist[1])
                                             
                                        

                                            
                                                thislist = ["apple", "banana", "cherry"]
                                                print(thislist[-1])
                                        
                                        

                                            
                                                thislist = ["apple", "banana", "cherry"]
    if "apple" in thislist:
      print("Yes, 'apple' is in the fruits list")
     
                                        

                                            
                                                thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
                                                thislist[1:3] = ["blackcurrant", "watermelon"]
                                        
                                        

                                            
                                                thislist = ["apple", "banana", "cherry"]
    thislist.insert(2, "watermelon")                              #Insert "watermelon" as the third item
                                        
                                        

                                            
                                                thislist = ["apple", "banana", "cherry"]
    thislist.append("orange")
                                        
                                        

                                            
                                                thislist = ["apple", "banana", "cherry"]
    tropical = ["mango", "pineapple", "papaya"]
    thislist.extend(tropical)       #To append elements from another list to the current list
                                        
                                        

                                            
                                                thislist.remove("banana")
                                        
                                        

                                            
                                                thislist = ["apple", "banana", "cherry"]
    thislist.pop(1)
                                        
                                        

                                            
                                                del thislist
                                        
                                        

                                            
                                                thislist.clear()
                                        
                                        

                                            
                                                for x in thislist:
                                                print(x)
                                        
                                        

                                            
                                                for i in range(len(thislist)):
                                                print(thislist[i])
                                        
                                        

                                            
                                                fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
    newlist = []for x in fruits:
      if "a" in x:
        newlist.append(x)                                    
                                        

                                            
                                                thislist.reverse()
                                        
                                        

                                            
                                                def myfunc(n):
                                                return abs(n - 50)
                                              
                                              thislist = [100, 50, 65, 82, 23]
                                              thislist.sort(key = myfunc)
                                        
                                        

                                            
                                                thislist.sort()
                                        
                                        

                                            
                                                thislist.sort(reverse = True)
                                        
                                        

                                            
                                                mylist = thislist.copy()
                                        
                                        
                                            
                                                mylist = list(thislist)
                                        
                                        

                                            
                                                list1 = ["a", "b", "c"]
                                                list2 = [1, 2, 3]
                                                
                                                list3 = list1 + list2
                                        
                                        

    List Methods
    List Methods
    Method Description
    append() Adds an element at the end of the list
    clear() Removes all the elements from the list
    copy() Returns a copy of the list
    count() Returns the number of elements with the specified value
    extend() Add the elements of a list (or any iterable), to the end of the current list
    index() Returns the index of the first element with the specified value
    insert() Adds an element at the specified position
    pop() Removes the element at the specified position
    remove() Removes the item with the specified value
    reverse() Reverses the order of the list
    sort() Sorts the list
  17. Python Tuples
    Python Tuples
    Tuples are used to store multiple items in a single variable.

    Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Set, and Dictionary, all with different qualities and usage.

    A tuple is a collection which is ordered and unchangeable.

    Tuples are written with round brackets.


    Tuple Items
    Tuple items are ordered, unchangeable, and allow duplicate values.
    Tuple items are indexed, the first item has index [0], the second item has index [1] etc.


    Ordered
    When we say that tuples are ordered, it means that the items have a defined order, and that order will not change.


    Unchangeable
    Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.


    Allow Duplicates
    Since tuples are indexed, they can have items with the same value


    Change Tuple Values
    Once a tuple is created, you cannot change its values. Tuples are unchangeable, or immutable as it also is called.

    But there is a workaround. You can convert the tuple into a list, change the list, and convert the list back into a tuple.


    Remove Items
    Note: You cannot remove items in a tuple.

    Tuples are unchangeable, so you cannot remove items from it, but you can use the same workaround as we used for changing and adding tuple items


    we are also allowed to extract the values back into variables. This is called "unpacking"

                                            
                                                thistuple = ("apple", "banana", "cherry")
                                                print(thistuple)
                                        
                                        

                                        
                                            len(thistuple)
                                    
                                    

                                            
                                                thistuple = ("apple",)
                                        
                                        

                                            
                                                thistuple = tuple(("apple", "banana", "cherry")) # note the double round-brackets
                                        
                                        

                                            
                                                thistuple = ("apple", "banana", "cherry")
                                                print(thistuple[1])
                                             
                                        

                                            
                                                thistuple = ("apple", "banana", "cherry")
    print(thistuple[-1])
                                        
                                        

                                            
                                                thistuple = ("apple", "banana", "cherry")
    if "apple" in thistuple:
      print("Yes, 'apple' is in the fruits tuple")
     
                                        

                                            
                                                x = ("apple", "banana", "cherry")
                                                y = list(x)
                                                y[1] = "kiwi"
                                                x = tuple(y)
                                                
                                                print(x)
                                        
                                        

                                            
                                                thislist = ["apple", "banana", "cherry"]
    thislist.insert(2, "watermelon")            
    thistuple = ("apple", "banana", "cherry")
    y = ("orange",)
    thistuple += yprint(thistuple)                  #Insert "watermelon" as the third item
                                        
                                        

                                            
                                                thistuple = ("apple", "banana", "cherry")
                                                y = list(thistuple)
                                                y.remove("apple")
                                                thistuple = tuple(y)
                                        
                                        

                                            
                                                fruits = ("apple", "banana", "cherry","clory")(green, yellow, red) = fruitsprint(green)
    print(yellow)
    print(red)
                                        
                                        

                                            
                                                thistuple = ("apple", "banana", "cherry")
    for x in thistuple:
      print(x)
                                        
                                        

                                            
                                                tuple1 = ("a", "b" , "c")
    tuple2 = (1, 2, 3)tuple3 = tuple1 + tuple2
                                        
                                        

                                            
                                                fruits = ("apple", "banana", "cherry")
                                                mytuple = fruits * 2
                                        
                                        

    Tuple Methods
    Tuple Methods
    Method Description
    count() Returns the number of times a specified value occurs in a tuple
    index() Searches the tuple for a specified value and returns the position of where it was found
  18. Python Sets
    Python Sets
    Set
    Sets are used to store multiple items in a single variable.

    Set is one of 4 built-in data types in Python used to store collections of data, the other 3 are List, Tuple, and Dictionary, all with different qualities and usage.

    A set is a collection which is unordered, unchangeable*, and unindexed.
    * Note: Set items are unchangeable, but you can remove items and add new items.

    Set Items
    Set items are unordered, unchangeable, and do not allow duplicate values.

    Unordered
    Unordered means that the items in a set do not have a defined order.

    Set items can appear in a different order every time you use them, and cannot be referred to by index or key.

    Unchangeable
    Set items are unchangeable, meaning that we cannot change the items after the set has been created.

    Once a set is created, you cannot change its items, but you can remove items and add new items.

    Duplicates Not Allowed
    Sets cannot have two items with the same value.

                                            
                                                thisset = {"apple", "banana", "cherry"}
                                                print(thisset)
                                        
                                        

                                        
                                            len(thislist)
                                    
                                    

                                            
                                                type(mylist) 
                                        
                                        

                                            
                                                thisset = set(("apple", "banana", "cherry")) # note the double round-brackets
                                        
                                        

                                            
                                                thisset = {"apple", "banana", "cherry"}for x in thisset:
      print(x)
                                             
                                        

                                            
                                                thisset = {"apple", "banana", "cherry"}thisset.add("orange")
                                        
                                        

                                            
                                                thisset = {"apple", "banana", "cherry"}
                                                tropical = {"pineapple", "mango", "papaya"}
                                                thisset.update(tropical)
     
                                        

                                                
                                                    thisset = {"apple", "banana", "cherry"}                                                
                                                    thisset.remove("banana")
                                                    
                                            
                                            
                                            
                                                thisset = {"apple", "banana", "cherry"}thisset.discard("banana")
                                        
                                        

    Note: If the item to remove does not exist, discard() will NOT raise an error.

                                            
                                                thisset = {"apple", "banana", "cherry"}
                                                x = thisset.pop()
                                        
                                        

                                                
                                                    thisset = {"apple", "banana", "cherry"}
                                                    thisset.clear()
                                            
                                            

                                            
                                                thisset = {"apple", "banana", "cherry"}
                                                del thisset
                                                print(thisset)
                                        
                                        

                                            
                                                thisset = {"apple", "banana", "cherry"}for x in thisset:
      print(x)
                                        
                                        

                                            
                                                set1 = {"a", "b" , "c"}
                                                set2 = {1, 2, 3}
                                                
                                                set3 = set1.union(set2)
                                        
                                        
                                            
                                                set1 = {"a", "b" , "c"}
                                                set2 = {1, 2, 3}
                                                
                                                set1.update(set2)
                                        
                                        

                                            
                                                x = {"apple", "banana", "cherry"}
    y = {"google", "microsoft", "apple"}x.intersection_update(y)
                                        
                                        

                                            
                                                x = {"apple", "banana", "cherry"}
                                                y = {"google", "microsoft", "apple"}
                                                
                                                x.symmetric_difference_update(y)
                                        
                                        

    Set Methods
    Set Methods
    Method Description
    add() Adds an element to the set
    clear() Removes all the elements from the set
    copy() Returns a copy of the set
    difference() Returns a set containing the difference between two or more sets
    difference_update() Removes the items in this set that are also included in another, specified set
    discard() Remove the specified item
    intersection() Returns a set, that is the intersection of two other sets
    intersection_update() Removes the items in this set that are not present in other, specified set(s)
    isdisjoint() Returns whether two sets have a intersection or not
    issubset() Returns whether another set contains this set or not
    issuperset() Returns whether this set contains another set or not
    pop() Removes an element from the set
    remove() Removes the specified element
    symmetric_difference() Returns a set with the symmetric differences of two sets
    symmetric_difference_update() inserts the symmetric differences from this set and another
    union() Return a set containing the union of sets
    update() Update the set with the union of this set and others
  19. Python Dictionaries
    Python Dictionaries
    Dictionary
    Dictionaries are used to store data values in key:value pairs.

    A dictionary is a collection which is ordered*, changeable and do not allow duplicates.

    As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

    Dictionaries are written with curly brackets, and have keys and values Dictionary Items Dictionary items are ordered, changeable, and does not allow duplicates.

    Dictionary items are presented in key:value pairs, and can be referred to by using the key name. Ordered or Unordered? As of Python version 3.7, dictionaries are ordered. In Python 3.6 and earlier, dictionaries are unordered.

    When we say that dictionaries are ordered, it means that the items have a defined order, and that order will not change.

    Unordered means that the items does not have a defined order, you cannot refer to an item by using an index.

    Changeable Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been created.

    Duplicates Not Allowed Dictionaries cannot have two items with the same key:

                                            
                                                thisdict = {
                                                    "brand": "Ford",
                                                    "model": "Mustang",
                                                    "year": 1964
                                                  }
                                                  print(thisdict)
                                        
                                        

                                        
                                            len(thislist)
                                    
                                    

                                            
                                                type(mylist) 
                                        
                                        

                                            
                                                thisdict = dict(name = "John", age = 36, country = "Norway")
                                        
                                        

                                            
                                                x = thisdict.get("model")
                                             
                                        

                                            
                                                x = thisdict.keys()
                                        
                                        

                                            
                                                x = thisdict.values()
     
                                        

                                                
                                                    x = thisdict.items()
                                            
                                            

                                            
                                                thisdict = {
                                                    "brand": "Ford",
                                                    "model": "Mustang",
                                                    "year": 1964
                                                  }
                                                  if "model" in thisdict:
                                                    print("Yes, 'model' is one of the keys in the thisdict dictionary")              
                                        
                                        

                                                
                                                    thisdict = {
                                                        "brand": "Ford",
                                                        "model": "Mustang",
                                                        "year": 1964
                                                      }
                                                      thisdict["year"] = 2018
                                            
                                            

                                            
                                                thisdict = {
                                                    "brand": "Ford",
                                                    "model": "Mustang",
                                                    "year": 1964
                                                  }
                                                  thisdict.update({"year": 2020})
                                        
                                        

                                            
                                                thisdict = {
                                                    "brand": "Ford",
                                                    "model": "Mustang",
                                                    "year": 1964
                                                  }
                                                  thisdict["color"] = "red"
                                        
                                        

                                            
                                                thisdict = {
                                                    "brand": "Ford",
                                                    "model": "Mustang",
                                                    "year": 1964
                                                  }
                                                  thisdict.pop("model")
                                                  print(thisdict)
                                        
                                        

                                            
                                                thisdict = {
                                                    "brand": "Ford",
                                                    "model": "Mustang",
                                                    "year": 1964
                                                  }
                                                  del thisdict
                                        
                                        

                                            
                                                thisdict = {
                                                    "brand": "Ford",
                                                    "model": "Mustang",
                                                    "year": 1964
                                                  }
                                                  thisdict.clear()
                                        
                                        

                                            
                                                for x in thisdict:
                                                print(x)
                                        
                                        

                                            
                                                thisdict = {
                                                    "brand": "Ford",
                                                    "model": "Mustang",
                                                    "year": 1964
                                                  }
                                                  mydict = thisdict.copy()
                                                  print(mydict)
                                                                 
                                        
                                            
                                                thisdict = {
                                                    "brand": "Ford",
                                                    "model": "Mustang",
                                                    "year": 1964
                                                  }
                                                  mydict = dict(thisdict)
                                                  print(mydict)
                                            
                                        

                                            
                                                child1 = {
                                                    "name" : "Emil",
                                                    "year" : 2004
                                                  }
                                                  child2 = {
                                                    "name" : "Tobias",
                                                    "year" : 2007
                                                  }
                                                  child3 = {
                                                    "name" : "Linus",
                                                    "year" : 2011
                                                  }
                                                  
                                                  myfamily = {
                                                    "child1" : child1,
                                                    "child2" : child2,
                                                    "child3" : child3
                                                  }
                                                                 
                                        

    Dictionary Methods
    Dictionary Methods
    Method Description
    clear() Removes all the elements from the dictionary
    copy() Returns a copy of the dictionary
    fromkeys() Returns a dictionary with the specified keys and value
    get() Returns the value of the specified key
    items() Returns a list containing a tuple for each key value pair
    keys() Returns a list containing the dictionary's keys
    pop() Removes the element with the specified key
    popitem() Removes the last inserted key-value pair
    setdefault() Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
    update() Updates the dictionary with the specified key-value pairs
    values() Returns a list of all the values in the dictionary
  20. If ..elif.. Else
    Java Continue
    Python Conditions and If statements
    Python supports the usual logical conditions from mathematics:

    Equals: a == b
    Not Equals: a != b
    Less than: a < b
    Less than or equal to: a <=b
    Greater than: a > b
    Greater than or equal to: a >= b
    These conditions can be used in several ways, most commonly in "if statements" and loops.
    An "if statement" is written by using the if keyword.
                        
                            a = 200
                            b = 33
                            if b > a:
                              print("b is greater than a")
                            elif a == b:
                              print("a and b are equal")
                            else:
                              print("a is greater than b")
                        
                        
  21. The pass Statement
    The pass Statement
    if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error.
    
        a = 33
    b = 200
    
    if b > a:
      pass
    
    
  22. While Loops
    While Loops
    With the while loop we can execute a set of statements as long as a condition is true.
                        
                            i = 1
    while i < 6:
      print(i)
      i += 1
                        
                        
  23. The break Statement
    The break Statement
    The break Statement
                        
                            i = 1
    while i < 6:
      print(i)
      if i == 3:
        break
      i += 1
                        
                        
  24. The continue Statement
    The continue Statement
    With the continue statement we can stop the current iteration, and continue with the next
                        
                            i = 0
                            while i < 6:
                              i += 1
                              if i == 3:
                                continue
                              print(i)
                        
                        
  25. Python For Loops
    Python For Loops
    A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

    This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages.

    With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
                        
                            fruits = ["apple", "banana", "cherry"]
                            for x in fruits:
                              print(x)
                        
                        
  26. The range() Function
    The range() Function
    To loop through a set of code a specified number of times, we can use the range() function,

    The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.
                
                    for x in range(2,6):
                        print(x)
                
            
  27. Python Functions
    Python Functions
    A function is a block of code which only runs when it is called.
    You can pass data, known as parameters, into a function.
    A function can return data as a result.

    Creating a Function In Python a function is defined using the def keyword

    Arguments
    Information can be passed into functions as arguments.

    Arguments are specified after the function name, inside the parentheses. You can add as many arguments as you want, just separate them with a comma.

    The following example has a function with one argument (fname). When the function is called, we pass along a first name, which is used inside the function to print the full name
                        
                            def my_function():
                            print("Hello from a function")
                        
                        
                            
                                def my_function(fname):
      print(fname + " Refsnes")
    my_function("Emil")
                            
                            
  28. Arbitrary Arguments, *args
    Arbitrary Arguments, *args
    If you do not know how many arguments that will be passed into your function, add a * before the parameter name in the function definition.

    This way the function will receive a tuple of arguments, and can access the items accordingly
                        
                            def my_function(*kids):
                            print("The youngest child is " + kids[2])
                          
                          my_function("Emil", "Tobias", "Linus")
                        
                        
  29. Recursion
    Recursion
    Python also accepts function recursion, which means a defined function can call itself.

    Recursion is a common mathematical and programming concept. It means that a function calls itself. This has the benefit of meaning that you can loop through data to reach a result.

    The developer should be very careful with recursion as it can be quite easy to slip into writing a function which never terminates, or one that uses excess amounts of memory or processor power. However, when written correctly recursion can be a very efficient and mathematically-elegant approach to programming.

    In this example, tri_recursion() is a function that we have defined to call itself ("recurse"). We use the k variable as the data, which decrements (-1) every time we recurse. The recursion ends when the condition is not greater than 0 (i.e. when it is 0).

    To a new developer it can take some time to work out how exactly this works, best way to find out is by testing and modifying it.
                        
                            def tri_recursion(k):
      if(k > 0):
        result = k + tri_recursion(k - 1)
        print(result)
      else:
        result = 0
      return result
    
    print("\n\nRecursion Example Results")
    tri_recursion(6)
                        
                        
  30. Python Lambda
    Python Lambda
    A lambda function is a small anonymous function.

    A lambda function can take any number of arguments, but can only have one expression.

    Why Use Lambda Functions?
    The power of lambda is better shown when you use them as an anonymous function inside another function.

    Say you have a function definition that takes one argument, and that argument will be multiplied with an unknown number

    Use lambda functions when an anonymous function is required for a short period of time.
                        
                            lambda arguments : expression
                        
                        
                        
                            def myfunc(n):
      return lambda a : a * n
                        
                        
  31. Arrays
    Arrays
    Note: Python does not have built-in support for Arrays, but Python Lists can be used instead.
    Note: This page shows you how to use LISTS as ARRAYS, however, to work with arrays in Python you will have to import a library, like the NumPy library.
    Arrays are used to store multiple values in one single variable

    What is an Array?

    An array is a special variable, which can hold more than one value at a time.

    If you have a list of items (a list of car names, for example), storing the cars in single variables could look like this:

    car1 = "Ford" car2 = "Volvo" car3 = "BMW" However, what if you want to loop through the cars and find a specific one? And what if you had not 3 cars, but 300?

    The solution is an array!

    An array can hold many values under a single name, and you can access the values by referring to an index number.

    Access the Elements of an Array You refer to an array element by referring to the index number.
                        
                            cars = ["Ford", "Volvo", "BMW"]
                        
                        
  32. Array Methods
    Array Methods
    Python has a set of built-in methods that you can use on lists/arrays.
    Method Description
    append() Adds an element at the end of the list
    clear() Removes all the elements from the list
    copy() Returns a copy of the list
    count() Returns the number of elements with the specified value
    extend() Add the elements of a list (or any iterable), to the end of the current list
    index() Returns the index of the first element with the specified value
    insert() Adds an element at the specified position
    pop() Removes the element at the specified position
    remove() Removes the first item with the specified value
    reverse() Reverses the order of the list
    sort() Sorts the list
  33. Python Classes/Objects
    Python Classes/Objects
    Python is an object oriented programming language. Almost everything in Python is an object, with its properties and methods. A Class is like an object constructor, or a "blueprint" for creating objects.

    class MyClass: x = 5

    p1 = MyClass() print(p1.x)
  34. The __init__() Function
    The __init__() Function
    The examples above are classes and objects in their simplest form, and are not really useful in real life applications.

    To understand the meaning of classes we have to understand the built-in __init__() function.

    All classes have a function called __init__(), which is always executed when the class is being initiated.

    Use the __init__() function to assign values to object properties, or other operations that are necessary to do when the object is being created
    Note: The __init__() function is called automatically every time the class is being used to create a new object.
                                
                                    class Person:
                                    def __init__(self, name, age):
                                      self.name = name
                                      self.age = age
                                  
                                  p1 = Person("John", 36)
                                  
                                  print(p1.name)
                                  print(p1.age)
                                
                                
  35. The __str__() Function
    The __str__() Function
    The __str__() function controls what should be returned when the class object is represented as a string.

    If the __str__() function is not set, the string representation of the object is returned

    Note: The self parameter is a reference to the current instance of the class, and is used to access variables that belong to the class.
                                
                                    class Person:
      def __init__(self, name, age):
        self.name = name
        self.age = age
    
      def __str__(self):
        return f"{self.name}({self.age})"
    
    p1 = Person("John", 36)
    
    print(p1)
                                
                                
  36. Object Methods
    Object Methods
    Objects can also contain methods. Methods in objects are functions that belong to the object.

    Let us create a method in the Person class

    The self Parameter
    The self parameter is a reference to the current instance of the class, and is used to access variables that belongs to the class.

    It does not have to be named self , you can call it whatever you like, but it has to be the first parameter of any function in the class
                                
                                    class Person:
      def __init__(self, name, age):
        self.name = name
        self.age = age
    
      def myfunc(self):
        print("Hello my name is " + self.name)
    
    p1 = Person("John", 36)
    p1.myfunc()
                                
                                
  37. Python Inheritance
    Python Inheritance
    Inheritance allows us to define a class that inherits all the methods and properties from another class.

    Parent class is the class being inherited from, also called base class.

    Child class is the class that inherits from another class, also called derived class.

    Create a Parent Class Any class can be a parent class, so the syntax is the same as creating any other class

  38. the super() Function
    the super() Function
    Python also has a super() function that will make the child class inherit all the methods and properties from its parent
    By using the super() function, you do not have to use the name of the parent element, it will automatically inherit the methods and properties from its parent
                        
                            class Student(Person):
                            def __init__(self, fname, lname):
                              super().__init__(fname, lname)                 }
                        
                        
  39. Python Iterators
    Python Iterators
    An iterator is an object that contains a countable number of values.

    An iterator is an object that can be iterated upon, meaning that you can traverse through all the values.

    Technically, in Python, an iterator is an object which implements the iterator protocol, which consist of the methods __iter__() and __next__().

    Iterator vs Iterable Lists, tuples, dictionaries, and sets are all iterable objects. They are iterable containers which you can get an iterator from.

    All these objects have a iter() method which is used to get an iterator


    Create an Iterator To create an object/class as an iterator you have to implement the methods __iter__() and __next__() to your object.

    As you have learned in the Python Classes/Objects chapter, all classes have a function called __init__(), which allows you to do some initializing when the object is being created.

    The __iter__() method acts similar, you can do operations (initializing etc.), but must always return the iterator object itself.

    The __next__() method also allows you to do operations, and must return the next item in the sequence.

    Return an iterator from a tuple

                        
                            mytuple = ("apple", "banana", "cherry")
                            myit = iter(mytuple)
                            
                            for x in mytuple:
      print(x)               
                        
                        

    Create an Iterator

                        
                            class MyNumbers:
      def __iter__(self):
        self.a = 1
        return self
    
      def __next__(self):
        x = self.a
        self.a += 1
        return x
    
    myclass = MyNumbers()
    myiter = iter(myclass)
    
    print(next(myiter))
    print(next(myiter))
                        
                        
  40. StopIteration
    StopIteration
    The example above would continue forever if you had enough next() statements, or if it was used in a for loop.
    To prevent the iteration to go on forever, we can use the StopIteration statement.
    In the __next__() method, we can add a terminating condition to raise an error if the iteration is done a specified number of times
                        
                            class MyNumbers:
                            def __iter__(self):
                              self.a = 1
                              return self
                          
                            def __next__(self):
                              if self.a <= 20:
                                x = self.a
                                self.a += 1
                                return x
                              else:
                                raise StopIteration
                          
                          myclass = MyNumbers()
                          myiter = iter(myclass)
                          
                          for x in myiter:
                            print(x)
                        
                        
  41. Python Scope
    Python Scope
    A variable is only available from inside the region it is created. This is called scope.

    Local Scope
    A variable created inside a function belongs to the local scope of that function, and can only be used inside that function.

    Function Inside Function
    As explained in the example above, the variable x is not available outside the function, but it is available for any function inside the function

    Global Scope
    A variable created in the main body of the Python code is a global variable and belongs to the global scope.
    Global variables are available from within any scope, global and local.


    Naming Variables
    If you operate with the same variable name inside and outside of a function, Python will treat them as two separate variables, one available in the global scope (outside the function) and one available in the local scope (inside the function)


    Global Keyword
    If you need to create a global variable, but are stuck in the local scope, you can use the global keyword.
    The global keyword makes the variable global.

    Global Keyword

                        
                            def myfunc():
                            global x
                            x = 300
                          myfunc()      
                          print(x)
                        
                        
  42. Python Modules
    Python Modules
    What is a Module?
    Consider a module to be the same as a code library.

    A file containing a set of functions you want to include in your application.


    Create a Module To create a module just save the code you want in a file with the file extension .py


    Use a Module
    Now we can use the module we just created, by using the import statement


    Note: When using a function from a module, use the syntax: module_name.function_name.


    Variables in Module
    The module can contain functions, as already described, but also variables of all types (arrays, dictionaries, objects etc):
                                    
                                        import mymodule
                                    
                                    

    Re-naming a Module

                                        
                                            import mymodule as mx
                                        
                                        
  43. Python Dates
    Python Dates
    A date in Python is not a data type of its own, but we can import a module named datetime to work with dates as date objects.
                                    
                                        import datetime
    
    x = datetime.datetime.now()
    print(x)
                                    
                                    
  44. The strftime() Method
    The strftime() Method
    The datetime object has a method for formatting date objects into readable strings. The method is called strftime(), and takes one parameter, format, to specify the format of the returned string
    Directive Description Example
    %a Weekday, short version Wed
    %A Weekday, full version Wednesday
    %w Weekday as a number 0-6, 0 is Sunday 3
    %d Day of month 01-31 31
    %b Month name, short version Dec
    %B Month name, full version December
    %m Month as a number 01-12 12
    %y Year, short version, without century 18
    %Y Year, full version 2018
    %H Hour 00-23 17
    %I Hour 00-12 05
    %p AM/PM PM
    %M Minute 00-59 41
    %S Second 00-59 08
    %f Microsecond 000000-999999 548513
    %z UTC offset +0100
    %Z Timezone CST
    %j Day number of year 001-366 365
    %U Week number of year, Sunday as the first day of week, 00-53 52
    %W Week number of year, Monday as the first day of week, 00-53 52
    %c Local version of date and time Mon Dec 31 17:41:00 2018
    %C Century 20
    %x Local version of date 12/31/18
    %X Local version of time 17:41:00
    %% A % character %
    %G ISO 8601 year 2018
    %u ISO 8601 weekday (1-7) 1
    %V ISO 8601 weeknumber (01-53) 01
                                            
                                                import datetime
    x = datetime.datetime(2018, 6, 1)
    print(x.strftime("%B"))
                                            
                                            
  45. Python Math
    Python Math
    Python has a set of built-in math functions, including an extensive math module, that allows you to perform mathematical tasks on numbers.


    Built-in Math Functions
    The min() and max() functions can be used to find the lowest or highest value in an iterable

    Method Description
    math.acos() Returns the arc cosine of a number
    math.acosh() Returns the inverse hyperbolic cosine of a number
    math.asin() Returns the arc sine of a number
    math.asinh() Returns the inverse hyperbolic sine of a number
    math.atan() Returns the arc tangent of a number in radians
    math.atan2() Returns the arc tangent of y/x in radians
    math.atanh() Returns the inverse hyperbolic tangent of a number
    math.ceil() Rounds a number up to the nearest integer
    math.comb() Returns the number of ways to choose k items from n items without repetition and order
    math.copysign() Returns a float consisting of the value of the first parameter and the sign of the second parameter
    math.cos() Returns the cosine of a number
    math.cosh() Returns the hyperbolic cosine of a number
    math.degrees() Converts an angle from radians to degrees
    math.dist() Returns the Euclidean distance between two points (p and q), where p and q are the coordinates of that point
    math.erf() Returns the error function of a number
    math.erfc() Returns the complementary error function of a number
    math.exp() Returns E raised to the power of x
    math.expm1() Returns Ex - 1
    math.fabs() Returns the absolute value of a number
    math.factorial() Returns the factorial of a number
    math.floor() Rounds a number down to the nearest integer
    math.fmod() Returns the remainder of x/y
    math.frexp() Returns the mantissa and the exponent, of a specified number
    math.fsum() Returns the sum of all items in any iterable (tuples, arrays, lists, etc.)
    math.gamma() Returns the gamma function at x
    math.gcd() Returns the greatest common divisor of two integers
    math.hypot() Returns the Euclidean norm
    math.isclose() Checks whether two values are close to each other, or not
    math.isfinite() Checks whether a number is finite or not
    math.isinf() Checks whether a number is infinite or not
    math.isnan() Checks whether a value is NaN (not a number) or not
    math.isqrt() Rounds a square root number downwards to the nearest integer
    math.ldexp() Returns the inverse of math.frexp() which is x * (2**i) of the given numbers x and i
    math.lgamma() Returns the log gamma value of x
    math.log() Returns the natural logarithm of a number, or the logarithm of number to base
    math.log10() Returns the base-10 logarithm of x
    math.log1p() Returns the natural logarithm of 1+x
    math.log2() Returns the base-2 logarithm of x
    math.perm() Returns the number of ways to choose k items from n items with order and without repetition
    math.pow() Returns the value of x to the power of y
    math.prod() Returns the product of all the elements in an iterable
    math.radians() Converts a degree value into radians
    math.remainder() Returns the closest value that can make numerator completely divisible by the denominator
    math.sin() Returns the sine of a number
    math.sinh() Returns the hyperbolic sine of a number
    math.sqrt() Returns the square root of a number
    math.tan() Returns the tangent of a number
    math.tanh() Returns the hyperbolic tangent of a number
    math.trunc() Returns the truncated integer parts of a number
  46. Python JSON
    Python JSON
    JSON is a syntax for storing and exchanging data.


    JSON is text, written with JavaScript object notation.
    JSON in Python
    Python has a built-in package called json, which can be used to work with JSON data.

    Convert from JSON to Python

                                                
                                                    import json
    
                                                    # some JSON:
                                                    x =  '{ "name":"John", "age":30, "city":"New York"}'
                                                    
                                                    # parse x:
                                                    y = json.loads(x)
                                                    
                                                    # the result is a Python dictionary:
                                                    print(y["age"])    
                                                
                                                

    Convert from Python to JSON

                                                
                                                    import json
    
    # a Python object (dict):
    x = {
      "name": "John",
      "age": 30,
      "city": "New York"
    }
    
    # convert into JSON:
    y = json.dumps(x)
    
    # the result is a JSON string:
    print(y)    
                                                
                                                
  47. Python RegEx
    Python RegEx
    A RegEx, or Regular Expression, is a sequence of characters that forms a search pattern.

    RegEx can be used to check if a string contains the specified search pattern.

    RegEx Module Python has a built-in package called re, which can be used to work with Regular Expressions.

    Import the re module

    RegEx Functions
    Function Description
    findall Returns a list containing all matches
    search Returns a Match object if there is a match anywhere in the string
    split Returns a list where the string has been split at each match
    sub Replaces one or many matches with a string

    Metacharacters ]
    Character Description Example
    [] A set of characters "[a-m]"
    \ Signals a special sequence (can also be used to escape special characters) "\d"
    . Any character (except newline character) "he..o"
    ^ Starts with "^hello"
    $ Ends with "planet$"
    * Zero or more occurrences "he.*o"
    + One or more occurrences "he.+o"
    ? Zero or one occurrences "he.?o"
    {} Exactly the specified number of occurrences "he.{2}o"
    | Either or "falls|stays"
    () Capture and group    

    Special Sequences
    Character Description Example
    \A Returns a match if the specified characters are at the beginning of the string "\AThe"
    \b Returns a match where the specified characters are at the beginning or at the end of a word
    (the "r" in the beginning is making sure that the string is being treated as a "raw string")
    r"\bain"
    r"ain\b"
    \B Returns a match where the specified characters are present, but NOT at the beginning (or at the end) of a word
    (the "r" in the beginning is making sure that the string is being treated as a "raw string")
    r"\Bain"
    r"ain\B"
    \d Returns a match where the string contains digits (numbers from 0-9) "\d"
    \D Returns a match where the string DOES NOT contain digits "\D"
    \s Returns a match where the string contains a white space character "\s"
    \S Returns a match where the string DOES NOT contain a white space character "\S"
    \w Returns a match where the string contains any word characters (characters from a to Z, digits from 0-9, and the underscore _ character) "\w"
    \W Returns a match where the string DOES NOT contain any word characters "\W"
    \Z Returns a match if the specified characters are at the end of the string "Spain\Z"

    Sets
    Set Description
    [arn] Returns a match where one of the specified characters (a, r, or n) is present
    [a-n] Returns a match for any lower case character, alphabetically between a and n
    [^arn] Returns a match for any character EXCEPT a, r, and n
    [0123] Returns a match where any of the specified digits (0, 1, 2, or 3) are present
    [0-9] Returns a match for any digit between 0 and 9
    [0-5][0-9] Returns a match for any two-digit numbers from 00 and 59
    [a-zA-Z] Returns a match for any character alphabetically between a and z, lower case OR upper case
    [+] In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a match for any + character in the string

                                                
                                                    import re
                                                
                                                

                                                
                                                    import re
    
    txt = "The rain in Spain"
    x = re.search("^The.*Spain$", txt)
                                                
                                                

    The findall() function returns a list containing all matches.

                                                
                                                    import re
    
    txt = "The rain in Spain"
    x = re.findall("ai", txt)
    print(x)
                                                
                                                

    The search() function searches the string for a match, and returns a Match object if there is a match.
    If there is more than one match, only the first occurrence of the match will be returned

                                                  
                                                    import re
    
    txt = "The rain in Spain"
    x = re.search("\s", txt)
    
    print("The first white-space character is located in position:", x.start())
                                                  
                                                  

    The split() function returns a list where the string has been split at each match

                                                  
                                                    import re
    
                                                    txt = "The rain in Spain"
                                                    x = re.split("\s", txt)
                                                    print(x)
                                                  
                                                  

    The sub() function replaces the matches with the text of your choice

                                                  
                                                    import re
    
    txt = "The rain in Spain"
    x = re.sub("\s", "9", txt)
    print(x)
                                                  
                                                  
  48. Python Try Except
    Python Try Except
    The try block lets you test a block of code for errors.

    The except block lets you handle the error.

    The else block lets you execute code when there is no error.

    The finally block lets you execute code, regardless of the result of the try- and except blocks.

    Exception Handling When an error occurs, or exception as we call it, Python will normally stop and generate an error message.

    These exceptions can be handled using the try statement

                                                
                                                    try:
                                                    print(x)
                                                  except:
                                                    print("An exception occurred")
                                                
                                                

    The finally block, if specified, will be executed regardless if the try block raises an error or not.

                                                                                        
                                                    try:
                                                    print(x)
                                                  except:
                                                    print("Something went wrong")
                                                  finally:
                                                    print("The 'try except' is finished")
       
                                                
                                                

    As a Python developer you can choose to throw an exception if a condition occurs. To throw (or raise) an exception, use the raise keyword.

                                                
                                                    x = -1
    
                                                    if x < 0:
                                                        raise Exception("Sorry, no numbers below zero"      
                                                
                                                
  49. Python String Formatting
    Python String Formatting
    To make sure a string will display as expected, we can format the result with the format() method.

    String format()
    The format() method allows you to format selected parts of a string.

    Sometimes there are parts of a text that you do not control, maybe they come from a database, or user input?

    To control such values, add placeholders (curly brackets {}) in the text, and run the values through the format() method
                        
                            price = 49
    txt = "The price is {} dollars"
    print(txt.format(price))
                        
                        
  50. Python File handling
    Python File handling
    File handling is an important part of any web application.

    Python has several functions for creating, reading, updating, and deleting files.

    File Handling

    The key function for working with files in Python is the open() function.

    The open() function takes two parameters; filename, and mode.

    There are four different methods (modes) for opening a file:

    "r" - Read - Default value. Opens a file for reading, error if the file does not exist

    "a" - Append - Opens a file for appending, creates the file if it does not exist

    "w" - Write - Opens a file for writing, creates the file if it does not exist

    "x" - Create - Creates the specified file, returns an error if the file exists

    In addition you can specify if the file should be handled as binary or text mode

    "t" - Text - Default value. Text mode

    "b" - Binary - Binary mode (e.g. images)

    Create a New File To create a new file in Python, use the open() method, with one of the following parameters: "x" - Create - will create a file, returns an error if the file exist "a" - Append - will create a file if the specified file does not exist "w" - Write - will create a file if the specified file does not exist Write to an Existing File To write to an existing file, you must add a parameter to the open() function: "a" - Append - will append to the end of the file "w" - Write - will overwrite any existing content

                                    
                                        f = open("demofile.txt", "r")
                                    
                                    

                                    
                                        f = open("demofile.txt", "r")
                                        print(f.read())
                                    
                                    

                                    
                                        f = open("demofile.txt", "r")
                                        print(f.readline())
                                    
                                    

                                      
                                        f.close()
                                      
                                      

                                      
                                        f.write("Woops! I have deleted the content!")
                                      
                                      

                                      
                                        f = open("myfile.txt", "w")
                                      
                                      

                                      
                                        import os
                                        os.remove("demofile.txt")
                                      
                                      

    Note: You can only remove empty folders.

                                      
                                        import os
                                        os.rmdir("myfolder")