10-Python Basic

Scopes and Name Resolution

Scopes and Name Resolution

Local scope - inside a function

Enclosing scope - from outer function if nested

Global - Top leve script

def serve_chai():
    chai_type = "Masala" # local scope
    print(f"Inside function {chai_type}")
chai_type = "Lemon"
serve_chai()
print(f"Outside function: {chai_type}")


def chai_counter():
    chai_order = "lemon" # Enclosing scope
    def print_order():
        chai_order = "Ginger"
        print("Inner:", chai_order)
    print_order()
    print("Outer: ", chai_order)
chai_order = "Tulsi" # Global
chai_counter()
print("Global :", chai_order)

NonLocal - The nonlocal keyword is used to modify a variable in an enclosing but non-global scope, which is specifically relevant for nested functions.

[Read More]

10-Python Basic

Generator, Iterator

# Topic covered
* Generators
* Iterable and Iterator in Python
    * Create an Iterator Class

11.1 Generators

Generator is a function which is responsible to generate a sequence of values.

We can write generator functions just like ordinary functions, but it uses yield keyword to return values.

def simpleGeneratorFun(): 
  yield 1         
  yield 2         
  yield 3         

for value in simpleGeneratorFun(): 
  print(value, end=' ')
# 1 2 3

x = simpleGeneratorFun() 
print(list(x))
# [1, 2, 3]

Advantages of Generator Functions

  1. When compared with class level iterators, generators are very easy to use
  2. Improves memory utilization and performance.
  3. Generators are the best suitable for reading data from large number of large files
  4. Generators work great for web scraping and crawling.
* Saves memory
* Don't want the result immediately
* Lazy evaluation

[…] β†’ list comprehension (eager, stores everything in memory).

We will get MemoryError in this case because all these values are required to store in the memory.

[Read More]

10-Python Basic

Built-in Functions, Generator, Iterator

# Topic covered
* Built-in Functions
    * Anonymous/lambda Functions
    * map() function
    * reduce() function
    * filter() function
    * eval() function

10.1 Anonymous/lambda Functions

Sometimes we can declare a function without any name, such type of nameless functions are called anonymous/lambda functions

The main purpose of anonymous function is just for instant use(i.e. for one time usage)

AKA lambda functions or shorthand function

# Syntax
lambda argument_list : expression
print((lambda x: x + 1)(2)) # 3

s = lambda n:n*n
print(s(4)) # 64

s = lambda a,b:a+b
print(s(2, 3)) # 5

s = lambda a,b:a if a>b else b
print(s(10,20)) # 20
print(s(100,200)) # 200

print((lambda x, y, z=3: x + y + z)(1, 2))

Note

Lambda Function internally returns expression value and we are not required to write return statement explicitly

[Read More]