Introduction

  • Programming is giving instructions to a computer.
  • Instructions are understood by computer to perform operations or task.
  • We Have data and these instructions process data to derive results.
  • Python 3.7 is the stable version as of now
    • 3.9 is latest version
  • High Level interpreted language
  • Mostly used IDE is Jupyter Notebook or pycharm or vscode
  • Each python file is a represented as a module
  • Any folder that has empty __init__.py Is known as a package as per python vocabulary
    • Files not in package can be accessed directly
  • Python Data Structures
    •  Integers
    • Floating Point
    • Lists
      • order stet of datatype
      • is mutable
    • Dictionary
    • Array
  • To check type of a variable
    • type(b1)
  • Complex Numbers
  • Print formatting
  • Lists
    • Has homogeneous structure
    • Example
      • Numbers = ["One","Two","Three"] 
    • Iterate
      • For n in numbers
        • print(n)
    • Nested Lists
      • used for matrix
    • List Comprehensive
    • List are Mutable data types in python.
    • In mutable data types, the same memory reference Cannot be changed. Once allotted, the reference remains forever with same information.
      • In immutable data types We can change reference later with new information, but information at old reference remain same.
    • List is also known as array in Other languages.
    • We can mix and match our data, reorder them, et cetera.
    • We can update our list with new data since they are mutable.
    • Operation on list
      • Append
        • Append element in the last
      • Remove
        • Remove the particular element if present.
        • If we remove element from list, if it is available It will be removed.
      • Extend
        • Join list with another list.
      • Insert
        • Insert at specific position
      • Pop
        • Pops out last element from list And returns the same
      • Sort
        • Sort the list
      • Reverse
        • Versus the list
      • Max
        • Get the maximum from a list
      • Min
        • Get the minimum from the list.
    • Operator, overloading and byte array in Python
      • Same operator can be used to perform operations on strings and numbers and other data types.
      • Using b"" before a string means it's a byte array.
      • When we perform an operation on bytes array it returns a new array so these are immutable in nature.
  • Tuples
    • Tuples are Immutable in python.
    • Membership check is case sensitive.
      • We use “in” To check if a text or number Is a member of tuple or not.
  • Sets
    • does not allow duplicates
    • Set is known for uniqueness. All elements are unique.
    • Union means all the elements of a segment, AB and all elements of segment B.
    • Intersection means all the common elements in segments A and B
    • Set contains all the common elements of both segments, and non common elements of segment A and segment B
    • We can have following operations on sets
      • Union
      • Intersection
      • Difference
    • We can perform membership test on sets.
    • Frozen set is an unordered collection of unique elements in which is immutable.
  • Dictionaries
    • Key Value Pairs
    • Nested Dictionaries
    • Dictionary are data type in python indexing is based on strings.
    • In list, we have index based on numbers, marked positions.
    • In dictionary, we have index based on string names.
    • For example, we can create a dictionary based on first name, which stores last name And vice versa.
    • All set operations are available in dictionary also.
  • Creating Function
    • def function name(args):
    • To call body use function name
  • Iterators and Generators
  • Map
    • pass list to function directly in one line
  • Reduce Function
  • Filter Function
  • Lambda Function
  • Range Function
    • gets list of numbers in range
      • range(0,6)
  • Input
    • name=input("what is your name")
    • type(name)
  • String
    • len
      • gives length of String
      • S="Hello World"
      • S[1:] will print entire string from first letter
      • S.upper()->uppercase
      • s.lower()->lowercase
      • s.split()->split in list
  • printformatting 
  • Python program has following components
    • Objects
    • Functions also called as methods
    • Properties
    • Class
  • __init__()
    • Opens up the class factory to initialise the class objects.
    • Acts As a constructor of the class
    • Initialise the class with default variables.
    • This method is mandatory for all classes to have.
  • sys Is a library which is included by default in Python.
    • sys.version Gives us the current Python version.
  • Using virtual environment’s
    • A virtual environment is an environment for every component where it has its own version of python and required dependencies
    • This is done to resolve python version dependency compatibility issues.
    • Instead of getting dependences from the common installed, instance of python in operating system, which may Create issues If dependency is updated, every component uses Dependencies from Its own compatible virtual environment Python version.
    • There is a standalone Python environment for every application/component.
    • Third-party components sometimes provide version conflicts.
    • To install dependences from a file In a virtual environment, use
      • pip -r name_of_file
      • This help’s to distribute our package with dependencies with packaged versions.
    • Always work in a virtual environment.
    • A New way To set up a virtual environment in python is using UV.
  • Code organisation
    • run.py
      • This is a script that launch the program.
      • This script may have names such as run.py, main.py etc
      • Used to start application.
    • Processing
      • As the functional part of the code
    • Utils
      • Naming valuables in python.
      • In Utility files which are generally part of util folder, we may have Empty files like __init__.py.
      • We do this to differentiate them from source files or module files.
      • Any folder, which has a blank __init__.py File is known as a package.
        • This has to be an empty file.
    • Src
      • Contains the source files
    • Controller
      • In the web application, it may contain controller.
  • PEP8 and Zen of python
    • Pep8 Is the style guidelines for python code.
    • Always use four spaces/never tabs
    • Use meaningful names for classes and objects.
    • Use formatters.
    • All this is done by our IDE.
    • In the Python command prompt fire command 
      • import this
      • This populates the Zen of Python.
  • Advantages of python
    • Portable
      • Write once and use anywhere
    • Readable
    • Productive
    • Standard libraries
      • Many functionalities are already written for data, science, machine, learning, and AI.
    • Flexible
      • Multi use That is, we can use it in Web app, data, manipulation, data, science, CSV generation, et cetera.
  • Datatypes/objects in python and their manipulation
    • Everything is object in python
      • Every object has a unique ID Called as identity
      • Every object has a unique type
      • Each object will have a value
    • Mutable and immutable
      • Mutable Data can be changed. Immutable data cannot be changed.
      • Identity helps you to identify if the Viable or object is actually changeable or not. This should not be referred by value.
        • id(value) Can be used to print the ID of Data type for example id(2) ,id(12) etc.
    • Numbers by default are immutable.
      • When we assign a new value, it creates a new memory space and variable point to that space.
      • So never check mutability from value.
      • Only reference changes value is never changed.
    • Set is mutable In python, it’s ID remain same even after adding values.
  • Numbers, Booleans and operations and operations on them
    • Numbers are also called as integers.
    • Booleans are predictable That is, they can either be true or false.
    • Real numbers are floating point numbers with decimals.
    • There are also Complex numbers, we have one part is real and other is fictional That is iota value’s etc.
    • Each one of them has a name.
    • If during division, we put a “//“ Then the whole number is given as response and decimal values are ignore.
    • ** will give power of first number to second number
      • 2**3 =8
    • Boolean is denoted as 0 or 1, where zero means false. And one means true.
    • Booleans are automatically upcasted during operations to 0 or 1.
    • Using bool function We can downcast boolean values.
    • Any positive value in boolean Represents a true.
    • We can also perform logical operations on Boolean values.
      • AND, OR, NOT operations
      • Check their truth Tables for resultant values.
    • sys.float_info gives us the float information about our system.
    • Fraction class from fractions package helps us to deal with fractions.
    • Decimal class from decimal package helps us to deal with decimal values.
  • String – index, slice and encoding
    • String provides text objects that can perform operations on their values like indexing, slicing, et cetera.
    • Strings are immutable.
    • Strings are index zero till length of string -1.
    • We can encode the strengths, which have special characters, for example, strings with Japanese language, et cetera.
      • we can encode and decode using encode and decode functions
  • Advanced Data types
    • These datatypes Exist in python as third-party module.
    • Some examples are
      • DateTime
        • Includes date and time at same time.
      • Calendar
        • Only for dates and time Separately
      • Time
        • Used just for time
      • Date
        • Used just for date
      • Time Delta
        • Used to calculate duration between start of operation and end of an operation.
    • We can manipulate these data types.
    • Besides these types, we also have certain utilities
      • Arrow Utility
      • DateUtil
  • Conditional in python, help us to check for a truth of a condition and take decision based on that.
    • Example, if age is greater than 18 Allowed to vote, else, do not allow to vote.
  • Loops are used to perform tasks again and again, for example, showing items in a list
    • We use for and while to loop.
    • We loop through Sequences using range(),enumerate() And zip.
    • We control loop behaviour using break, continue, and else clauses.
    • enumerate() Is used to index items in a list
      • It returns a tuple Containing count(from start which defaults to 0) and the values obtained from iterating over iterable.
      • We can customise start index.
    • Zip is used to combine list in python.
      • Zip iterates over several iterables In parallel, producing tuples With An item from each.
    • Use while loop when we need to check or keep on checking For certain condition during looping.
    • If we need to skip certain values while looping, we use skip
    • Break allows to completely stop the loop.
    • In a for else loop Else is used to execute fallback logic When no condition meets in for condition.
  • Walrus operator
    • Represented by “:=“ sign
    • A statement in python assign a value and returns Nothing for example x=5.
    • An expression returns a value example 3+3
    • Walrus was introduced in python, 3.8.
    • This syntax assign a value to variable as a part of larger expression.
  • Dictionary should be used instead of repeating cases/code.
  • Functions in python
    • Used to reduce duplication and splitting complex task.
    • Functions wrap our code and make our code usable.
    • Functions are also called as methods
    • Functions are used to write, modular and reusable code
    • Functions improve readability , traceability And maintainability of code.
    • We can break down large task into smaller steps using well named functions
    • Functions are defined with parameters
    • When we call functions, we pass arguments.
    • We have as many parameters as we like.
    • Functions help us to hide implementation details
    • Scope in functions
      • Global scope
        • Top level script
      • Enclosing from outer function, if nested
      • Local scope
        • Inside a function
      • Build in function
    • Scopes are resolved through name resolution
    • When we create a a variable Inside a function, its scope is inside that function only.
    • Non-Local versus global scope
      • We can access non-Local that is global variables from functions, local scope.
      • We use “nonlocal” keyword To access the same.
      • Non-local should be used if the variable is defined just above the scope.
      • If the variable is not defined One level above scope, that is, we have two Nesting functions And the second nest function wants to access variable from outside parent scope We use global in this case.
      • Non-Local and global should be carefully used as it may be code since we are modifying shared papers outside scope
      • https://github.com/gauravmatta/python/blob/master/basic/src/functions/nonlocal.py
  • Handling arguments in function in python.
    • Arguments are values that go in a function when we call it.
    • When we define a function, we pass parameters.
    • We can define many Arguments as a tuple Using “*” Operator.
    • We can define multiple key word arguments Using “**” Operator.
    • These Arguments are stored as tuples Which follow these operator’s placeholder names as keys.
  • Handling multiple return in python
    • Functions return values after processing data.
    • Return keyword Is used to return values from a function.
    • If nothing is returned None/Null Is returned From function, implicitly.
    • We can return one value/multiple values.
    • We can have an early return from the function.
  • Lambda/types of functions
    • There are pure versus un pure functions
      • If a function modifies global variable, it becomes an unpure function.
    • There are Recursive functions
    • There are anonymous functions, which do not have any names. These are called as lambdas in python.
  • Documenting functions and built-in functions
    • Python built in functions are pre defined Functions in python, which are a part of python interpreter.
    • We can give function description/documentation in three quotes at the top of the function.
    • We can use dunder functions With the function, then
      • Example, __doc__,__annotation__,__class__,__builtin__ etc.
      • All functions in __ are Called as dunder functions
    • The description should be the very first line in the function.
  • Python imports, module and init file
    • we can import objects and functions
    • Import the file using import function, and then Call function using file name.
    • Another way to import is to use specific methods from a particular class.
    • We can import functions. Give it a specific name, and then use that name to refer them.
      • We use keyboard as in such cases
    • We can import from inbuilt files from python, example date time, request.
    • We can have localised imports
    • We can import from directory Path These are called as relative imports.
    • We should avoid * During imports as it imports everything without knowing impact.
    • __init__.py that is Adding init dunder In a folder, makes it a package
      • We don’t have to do this after python, 3.3
      • It basically converts folder into Module
      • Python automatically, does that for us after 3.3.
  • Comprehensions in python
    • Everything done with comprehensions can be done with loops as well.
    • Comprehensions are just a style way of writing python code.
    • They are a shorter way Of writing code.
    • They are like English statements where one statement can do the whole job.
    • Comprehensions are a concise way to create list, set, dictionary, and Generators in python, using a single line of code
    • They are used while filtering items, transforming objects, create a new collection, flatten nested structures et cetera.
    • They are a cleaner code and execute faster in many scenarios.
    • They are written in a functional style manner Use less memory etc.
    • Comprehensions have following types
      • List
        • Expression for item in iterable if condition
      • Set
      • Dictionary
      • Generator
  • References

Comments