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, 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
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)
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
a module is a kind of container filled with functions
1.3.5 SECTION QUIZ
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
import abc.def.mymodule
1.4.Section 4 – Python Package Installer (PIP)
pip on Linux
pip install -U package_name
$ 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?2.1.5 SECTION QUIZ
2.2.10 SECTION QUIZ
SECTION QUIZ
# start from 5, end at 10
x = txt.find("e", 5, 10)
print(x)
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?
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'))
- (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:
Arithmetic problem!THE END. Output12assert 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 thanNone , 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
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.
123456789101112# 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
1234567891011121314# The code prints subsequent# values of exp(k), k = 1, 2, 4, 8, 16, ...from math import expex = 1try: while True: print(exp(ex)) ex *= 2except 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:
2.8.3 SECTION SUMMARY
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 OverflowError
Module 2 Test
The top‑most Python exception is called:
Remember that the BaseException class is, as the name suggests, the base class for all built-in exceptions in Python.
The following statement:
12assert var == 0 will stop the program when
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
3.1.8 Your first object
my_first_object = TheSimplestClass() 3.1.9 SECTION SUMMARY
3.2 Section 2 – A short journey from procedural to object approach
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
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 (
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
5. Each class method declaration must contain at least one parameter (always the first one) usually referred to as
6. If we want to hide any of a class's components from the outside world, we should start its name with
Another program
3.3 Section 3 – OOP: Properties
3.3.1 Instance variables
example_object_3 has been enriched with a property namedthird 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
SECTION SUMMARY
3.3.5 SECTION QUIZ
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
3.4.5 SECTION SUMMARY
3.4.5 SECTION SUMMARY
. If a class contains a constructor (a method named
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
MonTueSunSorry, 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:
We can say that:
- The
Vehicle class is the superclass for both theLandVehicle andTrackedVehicle classes; - The
LandVehicle class is a subclass ofVehicle and a superclass ofTrackedVehicle at the same time; - The
TrackedVehicle class is a subclass of both theVehicle andLandVehicle classes.
3.5.2 issubclass()
3.5.3 isinstance()
whether it is an object of a certain class or not.
3.5.4 The is operator
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
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)
FalseFalseTrue1 2 1True False
The results prove that
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
2. A function named
3. A function named
4. A operator called
5. A parameterless function named
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
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
What will be the output of the following code?
123456789101112class 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?
123456789101112class 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) What will be the result of executing the following code?
123456789101112class 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 thefor /in statements in order to pass through the next iteration; if there are no more values to provide, the method should raise theStopIteration 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)
The Fibonacci number generator
Completed 4.1.4 More about list comprehensions
conditional expression
List comprehensions vs. generators
List is in [] where gen.. in ()
Completed 4.1.5 The lambda function
4.1.6 How to use lambdas and what for?
Instead of poly() , lambda is used at under:
Completed 4.1.7 Lambdas and the map() function
Completed 4.1.8 Lambdas and the filter() function
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 theStopIteration exception when the iteration comes to an end.
2. The
[1, 2, 4, 8, 16, 32, 64, 128]
. A conditional expression is an expression built using the
12print(True if 0 >= 0 else False) outputs
4. A list comprehension becomes a generator when used inside parentheses (used inside brackets, it produces a regular list). For example:
123for x in (el * 2 for el in range(5)):print(x) outputs
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 mode | Binary mode | Description |
|---|---|---|
| read | ||
| write | ||
| append | ||
| read and update | ||
| write 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
Post a Comment