Python Essentials 2 https://skillsforall.com/launch?id=a0ad2851-c6d4-4980-a9a7-98b3f3108166&tab=curriculum&view=4dffa4e1-581f-5b7e-9251-75d1bcea70a5

https://skillsforall.com/launch?id=a0ad2851-c6d4-4980-a9a7-98b3f3108166&tab=curriculum&view=4dffa4e1-581f-5b7e-9251-75d1bcea70a5

Same course is also available at https://edube.org/study/pe2 

1.1 Section 1 – Introduction to Modules in Python


one of the most frequently used modules, named math

 the module contains a rich collection of entities (not only functions) which enable a programmer to effectively implement calculations demanding the use of mathematical functions, like sin() or log().

  1.1.3 Importing a module



>>> import math
 


import math
import sys
import math, sys

 

1.1.4 Namespace

A namespace is a space  in which some names exist and the names don't conflict with each other (i.e., there are not two different objects of the same name).








Inside a certain namespace, each name must remain unique.


1.1.5 Importing a module: continued





you may define your own functions sin and pi which will not conflict with math.sin and math.pi functions 


from module import *
 

Is it unsafe? Yes, it is - unless you know all the names provided by the module, you may be unable to avoid name conflicts. Treat this as a temporary solution, and try not to use it in regular code.


1.1.7 The as keyword


import module as alias
 


import math as m
    
print(m.sin(m.pi/2))

from module import n as a, m as b, o as c
  

 

1.2 Section 2 – Selected Python modules (math, random, platform)


1.2.1 Working with standard modules 

>>> dir() 






>>> dir(math) 

1.2.2 Selected functions from the math module


  • radians(x) → a function that converts x from degrees to radians;
  • degrees(x) → acting in the other direction (from radians to degrees)
  • pow(x, y) → finding the value of xy (mind the domains)

 ceil()floor() and trunc().











The randrange and randint functions








seed(0) to initialize to random generator with the same values will be given by the generator















randint(from,to)

randint(1,10)




















sample(nos of samples)

choice()






























platform  



















The machine function



















The processor function
















The system function


















 1.3 Section 3 – Modules and Packages


1.3.1 What is a package?


Package is composed of group of modules and functions

module is a kind of container filled with functions 


















1.3.5 SECTION QUIZ
Question 1: You want to prevent your module's user from running your code as an ordinary script. How will you achieve such an effect?
import sys

if __name__ == "__main__":
    print "Don't do that!"
    sys.exit()
    

Question 2: Some additional and necessary packages are stored inside the D:\Python\Project\Modules directory. Write a code ensuring that the directory is traversed by Python in order to find all requested modules.

import sys # note the double backslashes! sys.path.append("D:\\Python\\Project\\Modules")



Question 3: The directory mentioned in the previous exercise contains a sub-tree of the following structure:

abc
 |__ def
     |__ mymodule.py

Assuming that D:\Python\Project\Modules has been successfully appended to the sys.path list, write an import directive letting you use all the mymodule entities.

import abc.def.mymodule


1.4.Section 4 – Python Package Installer (PIP)

pip on Linux





1.4.4 Dependencies

Imagine that you've created a brilliant Python application named redsuspenders, able to predict stock exchange rates with 99% accuracy (by the way, if you actually do that, please contact us immediately).



NOTE last but one line Requires: six


pip install -U package_name


where -U means update. Note: this form of the command makes use of the --user option for the same purpose as presented previously;

  • $ pip install pygame==1.9.2
  • $ pip uninstall package_name

    1.4.9 SECTION QUIZ
    Question 1: Where does the name "The Cheese Shop" come from?
    Answer:
            It's a reference to an old Monty Python's sketch of the same name.
    Question 2: Why should I ensure which one of pip and pip3 works for me?
            
            When Python 2 and Python 3 coexist in your OS, it's likely that pip identifies
    the instance of pip working with Python 2 packages only.
    Question 3: How can I determine if my pip works with either Python 2 or Python 3?
    $ pip --version will tell you that. 
    Question 4: Unfortunately, I don't have administrative right. What should I do to install a package system-wide?

    You have to ask your sysadmin - don't try to hack your OS!

     

    2.1.5 SECTION QUIZ
     Question 1: What is BOM?
                            BOM (Byte Order Mark) is a special combination of bits announcing the encoding used by a file's content (eg. UCS-4 or UTF-8).

    Question 2: Is Python 3 I18Ned?

                Yes, it's completely internationalized - we can use                     UNICODE characters inside our code, read them from               input and send to output.


    2.2. Section 2 – The nature of strings in Python






    2.2.10 SECTION QUIZ
    Incomplete  

    SECTION QUIZ

    Question 1: What is the length of the following string assuming there is no whitespaces between the quotes?

    """
    """
    Answer is: 1

    Question 2: What is the expected output of the following code?

    s = 'yesteryears'
    the_list = list(s)
    print(the_list[3:6])

    Answer:
        ['t','e','r'] 

    2.3. Section 3 – String Methods




























































    print('kappa'.find('l')) -1


























    txt = "Hello, welcome to my world."
    #                     start from 5, end at 10
    x = txt.find("e"510)
    #                                  start, end)

    print(x)











































    Note the result of print('lambda_30'.isalnum())  as False 

    like ltrim()




     







    The three-parameter replace() variant uses the third argument (a number) to limit the number of replacements.
































    2.3.23 SECTION SUMMARY

    1. Some of the methods offered by strings are:

    • capitalize() – changes all string letters to capitals;
    • center() – centers the string inside the field of a known length;
    • count() – counts the occurrences of a given character;
    • join() – joins all items of a tuple/list into one string;
    • lower() – converts all the string's letters into lower-case letters;
    • lstrip() – removes the white characters from the beginning of the string;
    • replace() – replaces a given substring with another;
    • rfind() – finds a substring starting from the end of the string;
    • rstrip() – removes the trailing white spaces from the end of the string;
    • split() – splits the string into a substring using a given delimiter;
    • strip() – removes the leading and trailing white spaces;
    • swapcase() – swaps the letters' cases (lower to upper and vice versa)
    • title() – makes the first letter in each word upper-case;
    • upper() – converts all the string's letter into upper-case letters.

    2. String content can be determined using the following methods (all of them return Boolean values):

    • endswith() – does the string end with a given substring?
    • isalnum() – does the string consist only of letters and digits?
    • isalpha() – does the string consist only of letters?
    • islower() – does the string consists only of lower-case letters?
    • isspace() – does the string consists only of white spaces?
    • isupper() – does the string consists only of upper-case letters?
    • startswith() – does the string begin with a given substring?
    first_greek_2 = sorted(first_greek)

    second_greek = ['omega', 'alpha', 'pi', 'gamma']
    second_greek.sort()

    2.5.3 The Numbers Processor








    2.5.7   LAB   Palindromes
    mean reverse = actual text 
    like mom,  

    def ispolindrome(strng):
    strng=strng.replace(' ','')
    strng=strng.lower()
    rev=''
    for i in range(len(strng)):
    rev+=strng[-(i+1)]
    return rev==strng
    print(ispolindrome('Ten animals I slam in a net'))

    2.5.8   LAB   Anagrams

    text1 has all the characters in text2
    a very simple
    def ana(text1,text2): for c in text2.lower(): if c not in text1.lower(): return 'Not Anagrams' return 'Anagrams' text1= input('Input text 1:') text2= input('Input Text 2:') print(ana(text1,text2))

    2.6.2 Exceptions












    • (locally on your machine) if you press Ctrl-C while the program is waiting for the user's input (which causes an exception named KeyboardInterrupt), the program says:
    Oh dear, something went wrong...
    THE END.













    BaseException

    Exception

    ArithmeticError

    ZeroDivisionError


















































    Arithmetic problem!
    THE END.
    Output





















    assert. This is a keyword.

    1
    2
    assert expression3
     

    How does it work?

    • It evaluates the expression;
    • if the expression evaluates to True, or a non-zero numerical value, or a non-empty string, or any other value different than None, it won't do anything else;
    • otherwise if value is 
      • False
      • ZERO or 
      • empty String or
      • None , it automatically and immediately raises an exception named AssertionError (in this case, we say that the assertion has failed
























    2.8 Section 8 – Useful exceptions

    to learn more about exceptions on your own, look into the Standard Python Library at https://docs.python.org/3.6/library/exceptions.html.

    IndexError

    Location: BaseException←Exception←LookupError← IndexError
























    KeyboardInterrupt

    Location: BaseException ← KeyboardInterrupt

    Description:  to terminate a program's execution (Ctrl-C in most OSs);













    MemoryError

    Location: BaseException ← Exception ← MemoryError

    Description: a concrete exception raised when an operation cannot be completed due to a lack of free memory.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    # This code causes the MemoryError exception.
    # Warning: executing this code may affect your OS.
    # Don't run it in production environments!
     
    string = 'x'
    try:
        while True:
            string = string + string
            print(len(string))
    except MemoryError:
        print('This is not funny!')
     


    OverflowError

    Location: BaseException ← Exception ← ArithmeticError ← OverflowError

    Description: a concrete exception raised when  a number too big to be successfully stored

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    # The code prints subsequent
    # values of exp(k), k = 1, 2, 4, 8, 16, ...
    from math import exp
    ex = 1
    try:
        while True:
            print(exp(ex))
            ex *= 2
    except OverflowError:
        print('The number is too big.')

    Test data

    Test your code carefully.

    This is how the function should react to the user's input:

    Enter a number from -10 to 10: 100
    Error: the value is not within permitted range (-10..10)
    Enter a number from -10 to 10: asd
    Error: wrong input
    Enter number from -10 to 10: 1
    The number is: 1

    My coding 
     

     





    2.8.3 SECTION SUMMARY

    1. Some abstract built-in Python exceptions are:

    • ArithmeticError,
    • BaseException,
    • LookupError.

    2. Some concrete built-in Python exceptions are:

    • AssertionError,
    • ImportError,
    • IndexError,
    • KeyboardInterrupt,
    • KeyError,
    • MemoryError,
    • OverflowError.

    2.8.4 SECTION QUIZ

    Question 1: Which of the exceptions will you use to protect your code from being interrupted through the use of the keyboard?

    Hit light the answer

    KeyboardInterrupt

    Question 2: What is the name of the most general of all Python exceptions?

    Hit light the answer

    BaseException

    Question 3: Which of the exceptions will be raised through the following unsuccessful evaluation?

    huge_value = 1E250 ** 2
    Hit light the answer

    OverflowError

    Module 2 Test

    The top‑most Python exception is called:

    done

    BaseException

    Remember that the BaseException class is, as the name suggests, the base class for all built-in exceptions in Python.

    The following statement:

    1
    2
    assert var == 0

    will stop the program when var != 0

    Which of the following are examples of built-in concrete Python exceptions? (Select two answers)

    concrete exceptions in Python are build-in exceptions that inherit directly from the Exception class. IndexError and ImportError are such cases.

    UNICODE is a standard:

    like ASCII, but much more expansive


    3.1 Section 1 – The foundations of OOP

    3.1.1 The basic concepts of the object-oriented approach











    IN object approach   the data and the code are enclosed together in the same world, divided into classes.

    Every object has a set of traits (they are called properties or attributes 

     properties = attributes 

                                      attributes = properties






                An object belonging to a specific class belongs to all the superclasses at the same time like wheeled Vehicles (lower class)  belongs to Land vehicle (middle class) and Vehicle(Supper Class)  

                It may also mean that any object belonging to a superclass may not belong to any of its subclasses.




    3.1.7 Your first class


    class TheSimplestClass:
        pass
     


    3.1.8 Your first object


    my_first_object = TheSimplestClass()
     



    3.1.9 SECTION SUMMARY

    1. A class is an idea (more or less abstract) which can be used to create a number of incarnations – such an incarnation is called an object.


    2. When a class is derived from another class, their relation is named inheritance. The class which derives from the other class is named a subclass. The second side of this relation is named superclass. A way to present such a relation is an inheritance diagram, where:

    • superclasses are always presented above their subclasses;
    • relations between classes are shown as arrows directed from the subclass toward its superclass.

    3. Objects are equipped with:

    • a name which identifies them and allows us to distinguish between them;
    • a set of properties (the set can be empty )
    • Properties=Attrributes=Memory Variable like size=13, color =pink, weight=2 Kg
    • a set of methods (can be empty, too functions inside class)

    4. To define a Python class, you need to use the class keyword. For example:

    1
    2
    3
    class This_Is_A_Class:
        pass
     

    5. To create an object of the previously defined class, you need to use the class as if it were a function. For example:

    1
    2
    this_is_an_object = This_Is_A_Class()
     


    3.2 Section 2 – A short journey from procedural to object approach


    3.2.1 What is a stack?

                A stack is a structure developed to store data in a very specific way. as shown under



    stack's behavior: LIFO Last In – First Out. The coin that came last onto the stack will leave first.



































    Data Hiding:

    We prefer stack_list to be hidden from the outside world. Is that possible?

    Yes, and it's simple, 

     we've added two underscores before the stack_list name












    So we cane not access/change memory variable (attribute) value   __stack_list outside the class/object

    When any class component has a name starting with two underscores (__), it becomes private – this means that it can be accessed only from within the class.

    You cannot see it from the outside world. This is how Python implements the encapsulation concept.

    Run the program to test our assumptions – an AttributeError exception should be raised.


    3.2.5 The object approach: a stack from scratch
























































































    class stack:

        def __init__(self):

            self.__sl=[]   

            print('from stack super class')

                                           

        def push(self,value):

            self.__sl.append(value)

                              

        def pop(self):

            value = self.__sl[-1]

            del self.__sl[-1]

            return value

        

        def getlist(self):

            return self.__sl

        

    class addstack(stack):

        def __init__(self):

            print('from addstack class')

            stack.__init__(self)

            self.__sum=0

            

        def push(self,value):

            self.__sum += value

            stack.push(self,value)

            

        def pop(self):

            value = stack.pop(self)

            self.__sum -= value

            return value

        

        def getvalue(self):

            return self.__sum

           

    no1=addstack()

     

    for i in range(5):

        no1.push(i)

    print(no1.getvalue())

    print(no1.getlist())


    for i in range(5):

        print(no1.pop())

        print(no1.getlist())



    3.2.6 SECTION SUMMARY

    . A class method is actually a function declared inside the class and able to access all the class's components.


    4. The part of the Python class responsible for creating new objects is called the constructor, and it's implemented as a method of the name __init__.

    5. Each class method declaration must contain at least one parameter (always the first one) usually referred to as self, and is used by the objects to identify themselves.


    6. If we want to hide any of a class's components from the outside world, we should start its name with __. Such components are called private.


























































    Another program
























    3.3 Section 3 – OOP: Properties


    3.3.1 Instance variables

























    • example_object_3 has been enriched with a property named third and fourth just on the fly, outside the class's code - this is possible and fully permissible.


    3.3.2 Class variables


































    3.3.3 Checking an attribute's existence






































































    4. A function named hasattr() can be used to determine if any object/class contains a specified property.

    For example:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    class Sample:
        gamma = 0 # Class variable.
        def __init__(self):
     
            self.alpha = 1 # Instance variable.
            self.__delta = 3 # Private instance variable.
     
     
    obj = Sample()
    obj.beta = 2 # Another instance variable (existing only inside the 

    "obj" instance.)
    print(obj.__dict__)
     

    Incomplete  
    SECTION SUMMARY

    The code outputs:

    {'alpha': 1, '_Sample__delta': 3, 'beta': 2}


    3.3.5 SECTION QUIZ

    Question 1: Which of the Python class properties are instance variables and which are class variables? Which of them are private?

    class Python:
        population = 1
        victims = 0
        def __init__(self):
            self.length_ft = 3
            self.__venomous = False
     

    population and victims are class variables, while length and __venomous are instance variables (the latter is also private).


    3.4 Section 4 – OOP: Methods


    3.4.1 Methods in detail

                a method is a function embedded inside a class.

                The name self suggests the parameter's purpose – it identifies the object for which the method is invoked.

       E.g.   newobject=myclass()

    class myclass:

        def amethod(self):

            self.a=100

    newobject.a

    is 100 where selft is correspond to newobject 








































    Incomplete  
    3.4.5 SECTION SUMMARY





    3.4.5 SECTION SUMMARY

    . If a class contains a constructor (a method named __init__) it cannot return any value and cannot be invoked directly.



    Question 3: Can you predict the output of the following code?

    class Snake:
        pass
    class Python(Snake):
        pass
     
    print(Python.__name__, 'is a', Snake.__name__)
    print(Python.__bases__[0].__name__, 'can be', Python.__name__)
    Python is a Snake
    Snake can be Python

    3.4.7   LAB   The Timer class









































    3.4.8   LAB   Days of the week


    Program written by me



















    by author as SAMPLE SOLUTION by website

    class WeekDayError(Exception):
    pass

    class Weeker:
    __names = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']

    def __init__(self, day):
    try:
    self.__current = Weeker.__names.index(day)
    except ValueError:
    raise WeekDayError

    def __str__(self):
    return Weeker.__names[self.__current]

    def add_days(self, n):
    self.__current = (self.__current + n) % 7

    def subtract_days(self, n):
    self.__current = (self.__current - n) % 7
    try:
    weekday = Weeker('Mon')
    print(weekday)
    weekday.add_days(15)
    print(weekday)
    weekday.subtract_days(23)
    print(weekday)
    weekday = Weeker('Monday')
    except WeekDayError:
    print("Sorry, I can't serve your request.")

    Expected output

    Mon
    Tue
    Sun
    Sorry, I can't serve your request.

    3.4.9   LAB   Points on a plane

    pending to do/learn


    3.4.10   LAB   Triangle

    pending to do /learn


    3.5 Section 5 – OOP Fundamentals: Inheritance

    Inheritance is a common practice (in object programming) of passing attributes and methods from the superclass (defined and existing) to a newly created class, called the subclass.

    e.g  newobject =existingclass

    as in many previous example mentioned

    3.5.1 Inheritance – why and how?

     example of two-level inheritance is presented here:

    class Vehicle:
        pass
     
    class LandVehicle(Vehicle):
        pass

    class TrackedVehicle(LandVehicle):
        pass

    We can say that:

    • The Vehicle class is the superclass for both the LandVehicle and TrackedVehicle classes;
    • The LandVehicle class is a subclass of Vehicle and a superclass of TrackedVehicle at the same time;
    • The TrackedVehicle class is a subclass of both the Vehicle and LandVehicle classes.


    3.5.2 issubclass()


















    3.5.3 isinstance()

    whether it is an object of a certain class or not.


    isinstance(objectName, ClassName)
     
























    3.5.4 The is operator



    object_one is object_two
     

    Assigning a value of an object variable to another variable doesn't copy the object, but only its handle. It only refer the same memory location see the example sa under   

























    class SampleClass:
    def __init__(self, val):
    self.val = val

    object_1 = SampleClass(0)
    object_2 = SampleClass(2)
    object_3 = object_1
    object_3.val += 1

    print(object_1 is object_2)
    print(object_2 is object_3)
    print(object_3 is object_1)
    print(object_1.val, object_2.val, object_3.val)

    string_1 = "Mary had a little "
    string_2 = "Mary had a little lamb"
    string_1 += "lamb"

    print(string_1 == string_2, string_1 is string_2)


    False
    False
    True
    1 2 1
    True False

    The results prove that object_1 and object_3 are actually the same objects, while string_1 and string_2 aren't, despite their contents being the same.


    3.5.5 How Python finds properties and methods






























































    From Level 1 we can access Level 2 and Level 3:

    it is inhertance


    Multiple inheritance occurs when a class has more than one superclass.

    a very easy example

























    3.5.6 How to build a hierarchy of classes















    A very simple Eample of inheritance


























    A simplified version of program at 

    https://skillsforall.com/launch?id=a0ad2851-c6d4-4980-a9a7-98b3f3108166&tab=curriculum&view=66c099f6-a8d2-57c8-b824-9f67783088b4 






































    3.5.8 What is Method Resolution Order (MRO) and why is it that not all inheritances make sense?



























    When changed FROM class Bottom(Top, Middle) 

                            TO         class Bottom(Middle,Top)

                            NO ERROR 














    3.5.10 SECTION SUMMARY


    Following method usually used for return String value 

        def __str__(self):
            return 'Any String value'


    2. A function named issubclass(Class_1, Class_2) is able to determine if Class_1 is a subclass of Class_2. For example:









    3. A function named isinstance(Object, Class) checks if an object comes from an indicated class.








    4. A operator called is checks if two variables refer to the same object









    5. A parameterless function named super() returns a reference to the nearest superclass of the class. For example:













    6. Methods as well as instance and class variables defined in a superclass are automatically inherited by their subclasses.
















    3.5.11 SECTION QUIZ
















    Question 2: What is the expected output of the following piece of code?

    print(issubclass(SheepDog, Dog), issubclass(SheepDog, GuardDog))
    print(isinstance(rocky, GuardDog), isinstance(luna, GuardDog))

    True False

    False True


    Question 3: What is the expected output of the following piece of code?

    print(luna is luna, rocky is luna)
    print(rocky.kennel)

    True False


    3.6 Section 6 – Exceptions once again














    The finally block is always executed



















    3.6.2 Exceptions are classes

























































































    3.6.3 Detailed anatomy of exceptions













    3.6.4 How to create your own exception

    First to step by step to understand the actual example




































    3.6.6 SECTION QUIZ

    Question No 3.














    3.7 Module 3 Completion – Module Test


    Question 5

    What will be the output of the following code?

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    class A:
        def __init__(self,v = 1):
            self.v = v
     
        def set(self,v):
            self.v = v
            return v
     
     
    a = A()
    print(a.set(a.v + 1))

    What will be the output of the following code?

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    class A:
        X = 0
        def __init__(self,v = 0):
            self.Y = v
            A.X += v
     
     
    a = A()
    b = A(1)
    c = A(2)
    print(c.X)
     


    Question 16

    What will be the result of executing the following code?

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    class Ex(Exception)
        def __init__(self, msg):
            Exception.__init__(self, msg + msg)
            self.args = (msg,)
     
     
    try:
        raise Ex('ex')
    except Ex as e:
        print(e)
    except Exception as e:
        print(e)













    4.1 Section 1 – Generators, iterators, and closures


    A Python generator is a piece of specialized code able to produce a series of values, and to control the iteration process. This is why generators are very often called iterators,


    An iterator must provide two methods:

    • __iter__() which should return the object itself and which is invoked once (it's needed for Python to successfully start the iteration)
    • __next__() which is intended to return the next value (first, second, and so on) of the desired series – it will be invoked by the for/in statements in order to pass through the next iteration; if there are no more values to provide, the method should raise the StopIteration exception.





























    fib(n) iter class in used in class Class note it please

    __iter__ ise used fromclass Class and __next_ used from Fib(n) class 






















    Completed 4.1.3 How to build a generator (Using yield kw)







































    The list() function


    def powers_of_2(n):
        power = 1
        for i in range(n):
            yield power
            power *= 2
     
     
    t = list(powers_of_2(3))
    print(t)


    def powers_of_2(n):
        power = 1
        for i in range(n):
            yield power
            power *= 2
     
     
    for i in range(20):
        if i in powers_of_2(4):

            print(i)





    The Fibonacci number generator















    Completed 4.1.4 More about list comprehensions














     conditional expression 








    List comprehensions vs. generators

    List is in [] where gen.. in ()
















     len(the_generator) will raise an exception, and you will see the following message:

    TypeError: object of type 'generator' has no len()

    Completed 4.1.5 The lambda function

    lambda parameters: return expression

     













    4.1.6 How to use lambdas and what for?

       poly()      f(x) = 2x2 - 4x + 2











    Instead of poly() , lambda is used at under:









    Completed 4.1.7 Lambdas and the map() function

    map(function, list|tuple|iter|generator)





















    Completed 4.1.8 Lambdas and the filter() function













    =========== some outputs ==========

    [5, 2, -7, -2, -4]
    [2]

    [-4, 5, 4, 7, 0]
    [4]

    [-3, 3, 6, 2, 1]
    [6, 2]

    [9, 6, 6, -3, 7]

    [6, 6]
    ======================


    4.1.9 A brief look at closures









































































    4.1.10 SECTION SUMMARY


    1. An iterator is an object of a class providing at least two methods (not counting the constructor):

    • __iter__() is invoked once when the iterator is created and returns the iterator's object itself;
    • __next__() is invoked to provide the next iteration's value and raises the StopIteration exception when the iteration comes to an end.


    2. The yield statement can be used only inside functions. The yield statement suspends function execution and causes the function to return the yield's argument as a result. Such a function cannot be invoked in a regular way – its only purpose is to be used as a generator (i.e. in a context that requires a series of values, like a for loop).


    def powers_of_2(n):
        power = 1
        for i in range(n):
            yield power
            power *= 2
     
     
    t = list(powers_of_2(8))

     ===========RESTART: D:/Python/OOP/temp.py ======

    [1, 2, 4, 8, 16, 32, 64, 128]


    . A conditional expression is an expression built using the if-else operator. For example:

    1
    2
    print(True if 0 >= 0 else False)
     


    outputs True.



    4. A list comprehension becomes a generator when used inside parentheses (used inside brackets, it produces a regular list). For example:

    1
    2
    3
    for x in (el * 2 for el in range(5)):
    print(x)
     


    outputs 02468.


    4. A lambda function is a tool for creating anonymous functions. For example:










    Using map() and Lambda function










      





























    4.1.11 SECTION QUIZ














    4.2 Section 2 – Files (file streams, file processing, diagnosing stream problems)


    4.2.5 Opening the streams

    stream = open(file, mode = 'r', encoding = None)

    4.2.6 Selecting text and binary modes



    Text modeBinary modeDescription
    rtrbread
    wtwbwrite
    atabappend
    r+tr+bread and update
    w+tw+bwrite and update


    4.2.10 Diagnosing stream problems













    Let's take a look at some selected constants useful for detecting stream errors:

    • errno.EACCES → Permission denied

      The error occurs when you try, for example, to open a file with the read only attribute for writing.

    • errno.EBADF → Bad file number

      The error occurs when you try, for example, to operate with an unopened stream.

    • errno.EEXIST → File exists

      The error occurs when you try, for example, to rename a file with its previous name.

    • errno.EFBIG → File too large

      The error occurs when you try to create a file that is larger than the maximum allowed by the operating system.

    • errno.EISDIR → Is a directory

      The error occurs when you try to treat a directory name as the name of an ordinary file.

    • errno.EMFILE → Too many open files

      The error occurs when you try to simultaneously open more streams than acceptable for your operating system.

    • errno.ENOENT → No such file or directory

      The error occurs when you try to access a non-existent file/directory.

    • errno.ENOSPC → No space left on device

      The error occurs when there is no free space on the media.












    4.3 Section 3 – Working with real files





















    File=open(‘saeed.txt’)

    File.read()  mean read whole file

    File.read(1) means read one character of ile

    File.read(20) means read 20 chrars of file

    File.readline() is obvious

    File.readlines() do not know what is this today


    4.3.2 readline()

    The method tries to read a complete line of text from the file,


















    4.3.3 readlines()

    tries to read all the file contents, and returns a list of strings, one element per file line.





    The maximum accepted input buffer size is passed to the method as its argument.


    4.3.5 What is a bytearray?

     the specialized classes Python uses to store amorphous data.

    Amorphous data is data which have no specific shape or form – they are just a series of bytes.





















































































































































































































    Comments

    Popular posts from this blog

    PANDAS micro course by www.Kaggle.com https://www.kaggle.com/learn/pandas

    Course No 2 Using Python to Interact with the Operating System Rough Notes

    Introduction to Git and GitHub https://www.coursera.org/learn/introduction-git-github/