06 SEP 2019

OS functions: 
getcwd – get current working directory
chdir – change current directory 
listdir – print all files in current directory
makedirs – create folders (and sub folder) 
mkdir – create folder (without sub folder)
stat.st_mtime – get file last modification time
stat.size – get file size
walk – get all files, folders in a folder (recursion)
getenv – get system variables (i.e. PATH)
startfile – start a process
path.isfile – check if a path is a file
path.isdir – check if a path is a directory
path.exists – check if a path exists or not
os.path.join – combine a folder name with a file name
os.path.splitext – separates file name from its extension

shutil library: 
rmtree – remove folder and all of its context

psutil library:
process_iter – get all processed

datetime library:
now – get the current date and time
fromtimestamp – converts a time stamp into a date time

More topics covered:

  • Task manager
  • Running os command from shell
  • static variables introduction

Links:

30 AUG 2019

exhr.png

Exception: An exception is an event that occurs during the execution of a program that disrupts the normal flow of instructions during the execution of a program. When an error occurs within a method, the method creates an object and hands it off to the python runtime. The object, called an exception object, contains information about the error, including its type and the state of the program when the error occurred. Creating an exception object and handing it to the python runtime s called throwing an exception. After a method throws an exception, the python runtime attempts to find something to handle it. The set of possible “somethings” to handle the exception is the ordered list of methods that had been called to get to the method where the error occurred. The try and except block in Python is used to catch and handle exceptions. Python executes code following the try statement as a “normal” part of the program. The code that follows the except statement is the program’s response to any exceptions in the preceding tryclause. You can attach a finally-clause to a try-except block. The code inside the finally clause will always be executed, even if an exception is thrown from within the try or except block. If your code has a return statement inside the try or except block, the code inside the finally-block will get executed before returning from the method. 

Import statement: In Python, modules are accessed by using the import statement. When you do this, you execute the code of the module, keeping the scopes of the definitions so that your current file(s) can make use of these. When Python imports a module called hello for example, the interpreter will first search for a built-in module called hello. If a built-in module is not found, the Python interpreter will then search for a file named hello.py in the current folder 

OS functions:
getcwd – get current working directory
chdir – change current directory 
listdir – print all files in current directory
mkdir – create folder (without sub folder)

More topics covered:

  • try-except-finally
  • Exception tree Hierarchy
  • Inner exception
  • Multiple except statement
  • catch vs except
  • except Exception as e
  • try-except for user input (i.e. int)
  • API class
  • Static method
  • if __name__ == __main__ …

Links:

23 AUG 2019

Class properties as __dict__: we saw that all of the properties in a class are stored in a dictionary property called __dict__. whenever we add a property to the object (i.e. using self.name = name) then the property (‘name’ [and its value]) is added into this dictionary (__dict__). this gives us the flexibility of adding properties into the class dynamically- by simply adding entries into __dict__ (or even set the dictionary as a whole). this could also assist us in writing a generic __str__- by simply printing all of the key-values inside of the __dict__

Representational State Transfe (REST) client in python: we saw how to fire a GET HttpRequest from python to a REST web service. then we took the JSON string result and parsed it into a dictionary… and now we can create an object properties from this dictionary (as mentioned above, using __dict__)

More topics covered:

  • REST architecture
  • GET POST PUT DELETE
  • Single Page Application (SPA)
  • python requests install
  • python json import
  • json.loads command
  • list class requires repr implementation 

Links:

09 AUG 2019

Getters and Setters are used  to add validation logic around getting and setting a value. To avoid direct access of a class field i.e. private variables cannot be accessed directly or modified by external user.
Class inheritance is the capability of one class to derive or inherit the properties from some another class. The benefits of inheritance are: It represents real-world relationships well. It provides re-usability of a code. We don’t have to write the same code again and again. Also, it allows us to add more features to a class without modifying it. It is transitive in nature, which means that if class B inherits from another class A, then all the sub-classes of B would automatically inherit from class A
Unified Modeling Language, is a standardized modeling language consisting of an integrated set of diagrams, developed to help system and software developers for specifying, visualizing, constructing, and documenting the artifacts of software system

More topics covered:

  • Data Encapsulation
  • Decorator ( @ )
  • @property – getter
  • @.setter – setter
  • Setter avoid crash using None in __init__ method
  • dir ( class ) – will show all of the properties and functions
  • class <name> ( <class-inherit-from> ) …
  • all classes derive from object
  • override functions
  • Method Resolution Order (MRO) – the order of seeking a method
  • help ( class ) – will print the info of this class and the MRO
  • adding ”’…”’  comment will appear in the help output
  • Polymorpyhism
  • isinstnace, issubclass
  • super ( )
  • <super-class-name>.__init__ (self)
  • __init__ calling super ( )
  • __str_  calling super ( )

Links:

02 AUG 2019

Instance variables data owned by instances of the class. This means that for each object or instance of a class, the instance variables are different. i.e. a Person class could have instance variable of name, age, etc. so each person will have a different name, age…
Magic methods in Python are the special methods which add “magic” to your class. Magic methods are not meant to be invoked directly by you, but the invocation happens internally from the class on a certain action. For example, when you add two numbers using the + operator, internally, the __add__() method will be called.
__str__ and __repr__:  __repr__ is a built-in function used to compute the “official” string reputation of an object, while __str__ is a built-in function that computes the “informal” string representations of an object. So both __repr__ and __str__ are used to represent objects, but in different ways. str( ) is used for creating output for end user while repr() is mainly used for debugging and development. repr’s goal is to be unambiguous and str’s is to be readable. For example, if we suspect a float has a small rounding error, repr will show us while str may not. repr( ) compute the “official” string representation of an object (a representation that has all information about the abject) and str() is used to compute the “informal” string representation of an object (a representation that is useful for printing the object). The print ( ) statement and str() built-in function uses __str__ to display the string representation of the object while the repr() built-in function uses __repr__ to display the object.

More topics covered:

  • self.<property> = [value]  will create a member data on self
  • __init__ method should be used to create data members on self
  • __init__ method could accepts arguments for data member values
  • self.__<property> will create a secret data member
  • __repr__ could represent the python code of creating the object
  • _repr__could be manually called by: obj.__repr__( )
  • if __str__ and __repr__ both appear, print will call __str__
  • __str__ and __repr__ both should return a string
  • __eq__ will be called when we write: obj1== obj1
  • class name starts with Capital letter

Links:

26 JULY 2019

*args **kwargs : *args and **kwargs are mostly used in function definitions. *args and **kwargs allow you to pass a variable number of arguments to a function. What does variable mean here is that you do not know before hand that how many arguments can be passed to your function by the user so in this case you use these two keywords. *args is used to send a non-keyworded variable length argument list to the function. **kwargs allows you to pass keyworded variable length of arguments to a function. You should use **kwargs if you want to handle named arguments in a function. 

Tuple: A tuple is a sequence of immutable Python objects. Tuples are sequences, just like lists. The differences between tuples and lists are, the tuples cannot be changed unlike lists and tuples use parentheses, whereas lists use square brackets. Creating a tuple is as simple as putting different comma-separated values. 

oop

Object Oriented Programming (OOP) : Python is an “object-oriented programming language.” Object-oriented programming (OOP) is a programming paradigm based on the concept of “objects”, which can contain data, in the form of fields (often known as attributes), and code, in the form of procedures (often known as methods). A feature of objects is an object’s procedures that can access and often modify the data fields of the object with which they are associated (objects have a notion of “this” or “self”). In OOP, computer programs are designed by making them out of objects that interact with one another

More topics covered:

  • *args are send with comma: i.e. foo (1,2,3,4)
  • **kwargs are send by key-value: i.e. foo (coolKey = ‘cool value’)
  • *args are turned into a tuple automatically
  • **kwargs are turned into a dictionary automatically
  • tuple have few methods: index, count, indexing (like list)
  • list could be turned into a tuple, i.e. tuple( [1, 2] )
  • class keyword
  • __init__ method is automatically called when creating a class instance
  • we can define function inside a class
  • iphoneX = IPhone( ) creates an iphoneX object (instance) from class IPhone
  • function defined inside a class are called via the instance

Links:

12 JULY 2019

We learned how scope works in python. what is a scope of a variable? answer: “The scope of a variable refers to the places that you can see or access a variable”. If you define a variable inside a function it becomes a local variable (of the function) and cannot be accessed from outside the function. if you define a variable not in a function- it becomes a global variable. if you try to access a global variable for a read-only purpose inside a function it will be possible, however if you try to change it’s value – the python will make a duplication of the global variable for the scope of the function (and will not affect the global variable value in any way.) if you want to change a global variable inside a function you can use the global keyword (usually not recommended). we leaned about a collection type called Set. A set is a very similar to list except that it holds only distinct values (without repetition). for example, if you add the same item twice into a set- you will still have only one occurrence of this item. we learned about file accessing in python. the open command allows us to access the file in the desired mode (read/ write/ append, etc). we need to make sure we close the file connection after the work is done. we can also use the with statement in python- which closes the file automatically

ww2.png

More topics covered:

  • Scope– function inside a function
  • Set methods – i.e. union
  • file open – a, a+, w, w+ …
  • Seek command
  • with inside with
  • return two variable from function
  • print( ‘….’, end = “”)

Links:

05 JULY 2019

We learned how to use List comprehensions in python. List comprehensions provide a concise way to create lists. As list comprehensions returns lists, they consist of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element. we saw some examples of how to create a list using the list comprehensions technique, for example sqr numbers: 2, 4, 9, 16, 25 … We studied a new collection type called dictionary. Each item of the dictionary consist of a key and a value pair (also called entry). dictionary is used whenever you want to quickly find an item by it’s key i.e. person-id as a key and the person-name as a value. You can access the items of a dictionary by referring to its key name, inside square brackets. Each key is separated from its value by a colon (:), the items are separated by commas, and the whole thing is enclosed in curly braces. An empty dictionary without any items is written with just two curly braces, like this: {}. dictionaries are stored in a JSON format. you can retrieve all of the keys of the dictionary by using the keys( ) method and retrieve all of the values of the dictionary by using the values( ) method. dictionary keys are unique, which means that writing a value into the dictionary using an existing key will overwrite the existing entry. we wrote some helper functions to work with the dictionary i.e. tryAddValue which adds an entry to a given dictionary only if the given key does not already exist in a the dictionary

More topics covered:

  • String concatenation 
  • String Slice
  • JSON format 
  • XML format
  • List comprehension with condition
  • List comprehension using range
  • dictionary pop
  • dictionary remove item
  • dictionary print
  • dictionary type is called dict
  • for loop with 2 parameters

Links:

21 JUN 2019

We studied a new concept called function. what is a function? answer: “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” . we can create function for various purposes: avoid the duplication of code, expose a certain ability , etc. we already used functions in python, such as: len, count etc – but now it’s time to create functions ourselves. to create a function in python we use the def key word and name the function regarding to its purpose (for example a function which adds two numbers should be named Add, etc). a function could accept parameters (for example a function which calculates the area of a circle should accept a parameter stating the radius). we could assign a default value to the function parameter which will be used whenever this parameter will not be sent by the caller. of course, default parameters should be aligned to the right. we saw that a function could return a value using the return key word. why should we need a return value? answer: for example if a function calculates the sum of two numbers- we would be interested to know what was the sum that our function has calculated. usually, we store the returned value of a function in a memory cell, or print it to the screen. we saw how to generate random numbers

More topics covered:

  • Function syntax: def <function-name> ( parameters )
  • Function name should be legal , i.e. not starting with a number
  • Function return value could be ignored
  • None in python means empty
  • If a function does not have a return value, the return value is None
  • You cannot define the same function name more than once with different set of parameters
  • Calling function with parameter name, i.e. MySum (a = 5, b = 8)
  • random.randint
  • import key word

Links: