https://github.com/agent-006/python
https://github.com/agent-006/python
Last synced: 10 months ago
JSON representation
- Host: GitHub
- URL: https://github.com/agent-006/python
- Owner: Agent-006
- Created: 2024-03-23T20:20:48.000Z (about 2 years ago)
- Default Branch: main
- Last Pushed: 2024-03-30T07:49:59.000Z (about 2 years ago)
- Last Synced: 2025-02-27T12:38:46.672Z (over 1 year ago)
- Language: Python
- Size: 779 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
Awesome Lists containing this project
README
# β Python β
## π― What is python ? β
-> Python is a high-level programming language that is widely used for \
various purpose such as web development, data analysis, artificial intelligence, scientific computing, and more.
It was created by Guido van Rossum and first released in 1991.\
It features a clear and concise syntax, which allows developers to write code quickly and efficiently. Python supports multiple programming paradigms, \
including porcedural, object-oriented, and functional programming.
## π― What is Byte-Code in python ? β
-> In python, bytecode refers to the intermediate representation of the source code that is generated by the Python interpreter. When you write a Python script or enter commands in the Python shell, the Python interpreter first tanslates the source code into bytecode before executing it.
Bytecode is a low-level, platform-independent representation of the souce code that is optimized for efficient execution by the Python virtual machine(PVM). It is not directly executable by the computer's hardware like machine code, but it serves as an intermidiary step between the source code and the execution.
The bytecode is stored in `.pyc` files (compiled Python files) or in memory if the code is entered interactively. These `.pyc` files are created by the interpreter to speed up the execution of Python programs by avoiding the need to recompile the source code every time it is executed.
When you run a Python script, the interpreter checks if a corresponding `.pyc` file exists and if it is up-to-date with the source code. If the `.pyc` file exists and is up-to-date, the interpreter loads and executes the bytecode directly, speeding up the execution process. If the `.pyc` file is missing or outdated, the interpreter recompiles the source code into bytecode and then executes it.
Overall, bytecode plays a crucial role in the execution of Python programs, providing a platform-independent and efficient representation of the source code for interpretation by the Python virtual machine.
## π― What is virtual machine in python ? β
-> In Python, the term "virtual machine" refers to the Python Virtual Machine (PVM). The PVM is an interpreter that executes Python bytecode. It is responsible for translating the bytecode generated from Python source code into machine code that can be understood and executed by the underlying hardware.
The PVM abstracts the underlying hardware architecture, providing a platform-independent runtime environment for Python programs. This means that Python code can be written and executed on any platform (such as Windows, macOS, or Linux) without modification, as long as the appropriate Python interpreter is available for that platform.
The PVM manages memory allocation, garbage collection, and other runtime tasks required for executing Python code. It also provides access to the Python standard library and any additional modules or packages that are installed.
Overall, the Python Virtual Machine plays a crucial role in the execution of Python programs, providing a consistent and portable runtime environment across different platforms.

## π― What is frozen binaries in python ? β
-> In Python, frozen binaries typically refer to executable files that contain both the Python interpreter and the bytecode of a Python script, packaged together into a single standalone file. These frozen binaries are generated using tools like PyInstaller or cx_Freeze.
When you freeze a Python script into a binary, the resulting executable includes the Python interpreter along with any necessary libraries and dependencies, allowing the program to be run on a system that doesn't have Python installed. This makes distribution and deployment of Python applications more convenient, as users don't need to install Python separately to run the application.
Frozen binaries are often used for distributing Python applications as standalone executables, especially for deployment on systems where installing Python may not be feasible or desirable. They encapsulate the entire Python environment needed to run the application, making it easier to distribute and execute Python code across different platforms.
## π― Do you know what `__pychache__` means ? β
-> `__pycache__` is a directory automatically generated by Python to store compiled bytecode files (`.pyc` files) when a Python module is imported. This directory is created in the same directory as the Python script or module being executed.
The purpose of the `__pycache__` directory is to improve the performance of Python programs by caching compiled bytecode. When a Python module is imported, the interpreter checks if a corresponding `.pyc` file exists in the `__pycache__` directory. If the `.pyc` file exists and is up-to-date with the source code, the interpreter loads the bytecode from the `.pyc` file instead of recompiling the source code, which can save time and resources.
The `__pycache__` directory is automatically managed by Python and typically doesn't need manual intervention. It's safe to ignore or delete the `__pycache__` directory if necessary, as Python will recreate it as needed when modules are imported.
π Source Change & Python Version\
hello_chai.cpython-312.pyc
π² Works only for imported files\
π² not for top level files (parent or root directory)
def
variables
engine
bytecode machinecode
# π― Immutable and mutable in python β
-> In python, data types can be classified as either mutable or immutable, depending on whether their values can be changed after they are created.
1. Immutable Data Types: Immutable data types are those whose values cannot be changed after they are created. Any operation that appears to modify an immutable object actually creates a new object with the modified value. Examples of immutable data types in Python include:\
π²int (integer)\
π²float (floating-point number)\
π²str (string)\
π²tuple\
π²frozenset
β Example:
username = "sagar"
β Example:
x = 10
y = x
print(x) # gives output as 10
print(y) # gives output as 10
x = 15
print(x) # gives output as 15
print(y) # gives output as 10

π In the above two examples, you can understand the concept of immutable and mutable in python only by the diagram. Whenever we create a variable and assign a immutable type value to it, It's value is stored in the memory and the variable name(username) is then takes refrence of that memory location.
So, whenever we assign a new value to the immutable data type, a new memory location is assigned and it's reference is given to the variable. It previous value of that variable is removed by the garbage collector of python and then removed from the memory if not in use or referenced by any other variable.
# π― Data(Object)-Types in python β
->
π² Number : 1234, 3.14, 3+4j, 0b111, Decimal(), Fraction()\
π² String : 'spam', "Bob's", b'a\x01c', u'sp\xc4m'\
π² List : [1, [2, 'three'], 4.5], list(range(10))\
π² Tuple : (1, 'spam', 4, 'U'), tuple('spam'), namedtuple\
π² Dictionary : {'food': 'spam', 'taste': 'yum'}, dict(hours=10)\
π² Set : set('abc'), {'a', 'b', 'c'}\
π² File : open('eggs.txt'), open(r'C:\ham.bin', 'wb')\
π² Boolean : True, False\
π² None : None\
π² Functions, modules, classes
β Advance: Decorators, Generators, Iterators, MetaProgramming
# π― Internal working of python | copy, refrence counts, slice β
-> Refer to this link:
π [Video explanation π½οΈ](https://www.youtube.com/watch?v=brp5aiuWfso&list=PLu71SKxNbfoBsMugTFALhdLlZ5VOqCg2s&index=7)
# π― Numbers in python β
-> decimal context manager
π [Video explanation π½οΈ](https://www.youtube.com/watch?v=E4GNbP4SbKM&list=PLu71SKxNbfoBsMugTFALhdLlZ5VOqCg2s&index=8)
# π― Strings in python β
->
```
>>> num_list = "0123456789"
>>> num_list[:]
'0123456789'
>>> num_list[3:]
'3456789'
>>> num_list[:7]
'0123456'
>>> num_list[0:7:1]
'0123456'
>>> num_list[0:7:2]
'0246'
>>> num_list[0:7:4]
'04'
>>> num_list[0:7:4]
'04'
>>> num_list[0:7:-1]
''
>>> num_list[0:7:-2]
''
>>> num_list[::-2]
'97531'
>>> num_list[::]
'0123456789'
>>> num_list[::-1]
'9876543210'
>>> num_list[::2]
'02468'
>>> chai = 'Masala chai'
>>> chai
'Masala chai'
>>> print(chai.lower())
masala chai
>>> print(chai.upper())
MASALA CHAI
>>> chai
'Masala chai'
>>> chai = " Masala Chai "
>>> chia
Traceback (most recent call last):
File "", line 1, in
NameError: name 'chia' is not defined
>>> chai
' Masala Chai '
>>> print(chai.strip())
Masala Chai
>>> chai = "Lemon Chai"
>>> chia
Traceback (most recent call last):
File "", line 1, in
NameError: name 'chia' is not defined
>>> chai
'Lemon Chai'
>>> print(chai.replace("Lemon", "Ginger"))
Ginger Chai
>>> chai
'Lemon Chai'
>>> chai = "Lemon, Ginger, Masala, Mint"
>>> chia
Traceback (most recent call last):
File "", line 1, in
NameError: name 'chia' is not defined
>>> chai
'Lemon, Ginger, Masala, Mint'
>>> print(chai.split())
['Lemon,', 'Ginger,', 'Masala,', 'Mint']
>>> print(chai.split(", "))
['Lemon', 'Ginger', 'Masala', 'Mint']
>>> print(chai.split(","))
['Lemon', ' Ginger', ' Masala', ' Mint']
>>> chai = "Masala Chai"
>>> print(chai.find("Chai"))
7
>>> chai = "Masala Chai Chai Chai"
>>> print(chai.count("Chai"))
3
>>> chai_type = "Masala"
>>> quantity = 2
>>> order = "I ordered {} cups of {} chai"
>>> order
'I ordered {} cups of {} chai'
>>> print(order.format(quantity, chai_type))
I ordered 2 cups of Masala chai
>>> chai_variety = ["Lemon", "Masala", "Ginger"]
>>> chai_variety
['Lemon', 'Masala', 'Ginger']
>>> print(chai_variety.toStr())
Traceback (most recent call last):
File "", line 1, in
AttributeError: 'list' object has no attribute 'toStr'
>>> print("".join(chai_variety))
LemonMasalaGinger
>>> print(" ".join(chai_variety))
Lemon Masala Ginger
>>> print(" ,".join(chai_variety))
Lemon ,Masala ,Ginger
>>> print(", ".join(chai_variety))
Lemon, Masala, Ginger
>>> chai = "Masala Chai"
>>> chai
'Masala Chai'
>>> print(len(chai))
11
>>> for letter in chai:
... print(letter)
...
M
a
s
a
l
a
C
h
a
i
>>> chai = "He said, \"Masala chai is awesome\" "
>>> chai
'He said, "Masala chai is awesome" '
>>> chai = "Masala\nChai"
>>> chai
'Masala\nChai'
>>> print(chai)
Masala
Chai
>>> chai = r"Masala\nChai"
>>> print(chai)
Masala\nChai
>>> chai = r"c:\user\pwd\"
File "", line 1
chai = r"c:\user\pwd\"
^
SyntaxError: unterminated string literal (detected at line 1)
>>> chai = r"c\:\user\pwd\"
File "", line 1
chai = r"c\:\user\pwd\"
^
SyntaxError: unterminated string literal (detected at line 1)
>>> chai = r"c:\\user\\pwd\\"
>>> chai
'c:\\\\user\\\\pwd\\\\'
>>> print(chai)
c:\\user\\pwd\\
>>> chai = r"c\:\user\pwd"
>>> print(chai)
c\:\user\pwd
>>> chai = r"c:\user\pwd\"
File "", line 1
chai = r"c:\user\pwd\"
^
SyntaxError: unterminated string literal (detected at line 1)
>>> chai = r"c:\user\pwd"
>>> print(chai)
c:\user\pwd
>>> chai = "Masala Chai"
>>> print("Masala" in chai)
True
>>> print("Masalaa" in chai)
False
```
# π― List in python β
```
>>> tea_varieties = ["Black", "Green", "Oolong", "White"]
>>> print(tea_varieties)
['Black', 'Green', 'Oolong', 'White']
>>> print(tea_varieties[0])
Black
>>> print(tea_varieties[-1])
White
>>> print(tea_varieties[1:3])
['Green', 'Oolong']
>>> print(tea_varieties[:3])
['Black', 'Green', 'Oolong']
>>> print(tea_varieties[:2])
['Black', 'Green']
>>> print(tea_varieties[:2:2])
['Black']
>>> print(tea_varieties[:2:-2])
['White']
>>> print(tea_varieties[::-2])
['White', 'Green']
>>> print(tea_varieties[::-1])
['White', 'Oolong', 'Green', 'Black']
>>> tea_varieties[3] = "Herbal"
>>> print(tea_varieties
... print(tea_varieties
File "", line 1
print(tea_varieties
^^^^^^^^^^^^
SyntaxError: invalid syntax. Perhaps you forgot a comma?
>>> print(tea_varieties)
['Black', 'Green', 'Oolong', 'Herbal']
>>> tea_varieties[1:2]
['Green']
>>> tea_varieties[1:2] = "Lemon"
>>> tea_varieties[1:2]
['L']
>>> tea_varieties
['Black', 'L', 'e', 'm', 'o', 'n', 'Oolong', 'Herbal']
>>> tea_varieties = ["Black", "Green", "Oolong", "White"]
>>> print(tea_varieties)
['Black', 'Green', 'Oolong', 'White']
>>> tea_varieties[1:2]
['Green']
>>> tea_varieties[1:2] = ["Lemon"]
>>> tea_varieties[1:2]
['Lemon']
>>> print(tea_varieties)
['Black', 'Lemon', 'Oolong', 'White']
>>> tea_varieties[1:3]
['Lemon', 'Oolong']
>>> tea_varieties[1:3] = ["Green", "Masala"]
>>> tea_varieties[1:3]
['Green', 'Masala']
>>> print(tea_varieties)
['Black', 'Green', 'Masala', 'White']
>>> tea_varieties[1:1]
[]
>>> tea_varieties[1:1] = ["test", "test"]
>>> tea_varieties[1:1]
[]
>>> print(tea_varieties)
['Black', 'test', 'test', 'Green', 'Masala', 'White']
>>> tea_varieties[1:2]
['test']
>>> tea_varieties[1:3]
['test', 'test']
>>> tea_varieties[1:3] = []
>>> print(tea_varieties)
['Black', 'Green', 'Masala', 'White']
>>> for tea in tea_varieties:
... print(tea)
...
Black
Green
Masala
White
>>> for tea in tea_varieties:
... print(tea, end="-")
...
Black-Green-Masala-White->>>
>>> if "Oolong" in tea_varieties:
... print("I have Oolong tea")
...
>>> tea_varieties.append("Oolong")
>>> if "Oolong" in tea_varieties:
... print("I have Oolong tea")
...
I have Oolong tea
>>> tea_varieties.pop()
'Oolong'
>>> tea_varieties
['Black', 'Green', 'Masala', 'White']
>>> tea_varieties.remove("Green")
>>> tea_varieties
['Black', 'Masala', 'White']
>>> tea_varieties.insert(1, "Green")
>>> tea_varieties
['Black', 'Green', 'Masala', 'White']
>>> tea_varieties_copy = tea_varieties.copy()
>>> tea_varieties_copy.append("Lemon")
>>> tea_varieties_copy
['Black', 'Green', 'Masala', 'White', 'Lemon']
>>> tea_varieties
['Black', 'Green', 'Masala', 'White']
>>> squared_nums = [x**2 for x in range(10)]
>>> squared_nums
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> cube_num = [y**3 for y in range(10)]
>>> cube_num
[0, 1, 8, 27, 64, 125, 216, 343, 512, 729]
```
# π― Dictionary in python β
->
```
>>> chai_types = {"Masala": "Spicy", "Ginger": "Zesty", "Green": "Mild"}
>>> chai_types
{'Masala': 'Spicy', 'Ginger': 'Zesty', 'Green': 'Mild'}
>>> chai_types[0]
Traceback (most recent call last):
File "", line 1, in
KeyError: 0
>>> chai_types["Masala"]
'Spicy'
>>> chai_types.get('Ginger')
'Zesty'
>>> chai_types.get('Gingery')
>>> chai_types['Green'] = 'Fresh'
>>> chai_types
{'Masala': 'Spicy', 'Ginger': 'Zesty', 'Green': 'Fresh'}
>>> for chai in chai_types:
... print(chai)
...
Masala
Ginger
Green
>>> for chai in chai_types:
... print(chai, chai_types[chai])
...
Masala Spicy
Ginger Zesty
Green Fresh
>>> for key, values in chai_types.items():
... print(key, values)
...
Masala Spicy
Ginger Zesty
Green Fresh
>>> if "Masala" in chai_types:
... print('I have masala chai')
...
I have masala chai
>>> print(len(chai_types))
3
>>> chai_types
{'Masala': 'Spicy', 'Ginger': 'Zesty', 'Green': 'Fresh'}
>>> chai_types["Earl Grey"] = "Citrus"
>>> chai_types
{'Masala': 'Spicy', 'Ginger': 'Zesty', 'Green': 'Fresh', 'Earl Grey': 'Citrus'}
>>> chai_types.pop("Ginger")
'Zesty'
>>> chai_types
{'Masala': 'Spicy', 'Green': 'Fresh', 'Earl Grey': 'Citrus'}
>>> chai_types.pop()
Traceback (most recent call last):
File "", line 1, in
TypeError: pop expected at least 1 argument, got 0
>>> chai_types.popitem()
('Earl Grey', 'Citrus')
>>> chai_types
{'Masala': 'Spicy', 'Green': 'Fresh'}
>>> del chai_types["Green"]
>>> chai_types
{'Masala': 'Spicy'}
>>> chai_types_copy = chai_types.copy()
>>> tea_shop = {
... "chai": {'Masala' : 'Spicy', 'Ginger' : 'Zesty'},
... "Tea" : {'Green' : 'Mild', 'Black' : 'Strong'}
... }
>>> tea_shop
{'chai': {'Masala': 'Spicy', 'Ginger': 'Zesty'}, 'Tea': {'Green': 'Mild', 'Black': 'Strong'}}
>>> tea_shop['chai']
{'Masala': 'Spicy', 'Ginger': 'Zesty'}
>>> tea_shop['chai']['Ginger']
'Zesty'
>>> squared_nums = {x:x**2 for x in range(6)}
>>> squared_nums
{0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
>>> squared_nums.clear()
>>> squared_nums
{}
>>> keys = ['Masala', 'Ginger', 'Lemon']
>>> keys
['Masala', 'Ginger', 'Lemon']
>>> default_value = 'Delicious'
>>> new_dict = dict.fromkeys(keys, default_value)
>>> new_dict
{'Masala': 'Delicious', 'Ginger': 'Delicious', 'Lemon': 'Delicious'}
>>> new_dict = dict.fromkeys(keys, keys)
>>> new_dict
{'Masala': ['Masala', 'Ginger', 'Lemon'], 'Ginger': ['Masala', 'Ginger', 'Lemon'], 'Lemon': ['Masala', 'Ginger', 'Lemon']}
```
# π― Tuples in python β
->
```
>>> tea_types = ('Black', 'Green', 'Oolong')
>>> tea_types
('Black', 'Green', 'Oolong')
>>> tea_types[0]
'Black'
>>> tea_types[-1]
'Oolong'
>>> tea_types[1:]
('Green', 'Oolong')
>>> tea_types[0]
'Black'
>>> tea_types[0] = 'Lemon'
Traceback (most recent call last):
File "", line 1, in
TypeError: 'tuple' object does not support item assignment
>>> len(tea_types)
3
>>> more_tea = ('Herbal', 'Earl Grey')
>>> all_tea = more_tea + tea_types
>>> all_tea
('Herbal', 'Earl Grey', 'Black', 'Green', 'Oolong')
>>> if 'Green' in all_tea:
... print('I have green tea')
...
I have green tea
>>> more_tea = ('Herbal', 'Earl Grey', 'Herbal')
>>> more_tea
('Herbal', 'Earl Grey', 'Herbal')
>>> more_tea.count()
Traceback (most recent call last):
File "", line 1, in
TypeError: tuple.count() takes exactly one argument (0 given)
>>> more_tea.count('Herbal')
2
>>> tea_types
('Black', 'Green', 'Oolong')
>>> (black, green, Oologn) = tea_types
>>> black
'Black'
>>> type(tea_types)
>>>
```
# π― Conditional in python β
->
π² Classify a person's age group: Child( < 13), Teenager(13-19), Adult(20-59), Senior(60+)\
π² Movie tickets are priced based on age: $12 for adults(18 and over), $8 for children. Everyone gets a $2 discount on Wednesday.\
π² Assign a letter grade based on a student's score: A(90-100), B(80-89), C(7079), D(60-69), F(below 60).\
π² Determine if a fruit is ripe, overripe, or unripe based on its color. (e.g., Banana: Green - Unripe, Yellow - Ripe, Brown - Overripe)\
π² Suggest an activity based on the weather(e.g., Sunny - Go for a walk, Rainy - Read a book, Snowy - Build a snowman).\
π² Choose a mode of transportation based on the distance (e.g., <3 km: Walk, 3-15 km: Bike, >15 km: Car).\
π² Customize a coffee order: "Small", "Medium", or "Large" with an option for "Extra shot" of expresso.\
π²Check if a password is "Weak", "Medium", or "Strong". Criteria: <6 chars (Weak), 6-10 chars (Medium), >10 chars (Strong).\
π² Determine if a year is a leap year.(Leap years are divisible by 4, but not by 100 unless also divisible by 400).\
π² Recommend a type of pet food based on the pet's species and age. (e.g., Dog: <2 years - Puppy food, Cat: >5 years - Senior cat food).
# π― loops in python β
π² Counting Positive Numbers\
Problem: Given a list of numbers, count how many are positive.
```
numbers = [1, -2, 3, -4, 5, 6, -7, -8, 9, 10]
```
π² Sum of Even Numbers\
Problem: Calculate the sum of even numbers up to a given number `n`.
π² Multiplication Table Printer\
Problem: Print the multiplication table for a given number up to 10, but skip the fifth iteration.
π² Reverse a string using a loop\
Problem: Reverse a string using a loop.
π² Find the First Non-Repeated Character\
Problem: Given a string, find the first non-repeated character.
π² Factorial Calculator\
Problem: Compute the factorial of a number using a while loop.
π² Validate Input\
Problem: Keep asking the user for input until they enter a number between 1 and 10.
π² Prime Number Checker\
Problem: Check if a number is prime.
π² List Uniqueness Checker\
Problem: Check if all elements in a list are unique. If a duplicate is found, exit the loop and print the duplicate.
```
items = ["apple", "banana", "orange", "apple", "mango"]
```
π² Exponential Backoff\
Problem: Implement an exponential backoff strategy that doubles the wait time between retries, starting from 1 second, but stops after 5 retries.
# π― Behind the scene of loops in python β
```
>>> file = open("chai.py")
>>> file.readline()
'import time\n'
>>> file.readline()
'print("chai is here")\n'
>>> file.readline()
'username = "sagar"\n'
>>> file.readline()
'print(username)'
>>> file.readline()
''
>>> file = open("chai.py")
>>> file.__next__()
'import time\n'
>>> file.__next__()
'print("chai is here")\n'
>>> file.__next__()
'username = "sagar"\n'
>>> file.__next__()
'print(username)'
>>> file.__next__()
Traceback (most recent call last):
File "", line 1, in
StopIteration
>>> for line in open("chai.py"):
... print(line)
...
import time
print("chai is here")
username = "sagar"
print(username)
>>> for line in open("chai.py"):
... print(line, end='')
...
import time
print("chai is here")
username = "sagar"
print(username)>>>
>>> file = open("chai.py")
>>> while True:
... line = file.readline()
... if not line:
... break
... print(line, end='')
...
import time
print("chai is here")
username = "sagar"
print(username)>>>
>>> test = 'sagar'
>>> if not test:
... print('chai')
...
>>> test = ''
>>> if not test:
... print('chai')
...
chai
>>> myList = [1, 2, 3, 4]
>>> I = iter(myList)
>>> I
>>> I.__next__()
1
>>> I
>>> I.__next__()
2
>>> I.__next__()
3
>>> I.__next__()
4
>>> I.__next__()
Traceback (most recent call last):
File "", line 1, in
StopIteration
>>> file = open('chai.py')
>>> iter(file) is file
True
>>> iter(file) is file.__iter__()
True
>>> myNewList = [1, 2, 3]
>>> iter(myNewList) is myNewList
False
>>> D = {'a': 1, 'b': 2}
>>> for key in D.keys():
... print(key)
...
a
b
>>> I = iter(D)
>>> I
>>> next(I)
'a'
>>> next(I)
'b'
>>> next(I)
Traceback (most recent call last):
File "", line 1, in
StopIteration
>>> range(5)
range(0, 5)
>>> R = range(5)
>>> R
range(0, 5)
>>> I = iter(R)
>>> I
>>> next(I)
0
>>> next(I)
1
>>> next(I)
2
>>> next(I)
3
>>> next(I)
4
>>> next(I)
Traceback (most recent call last):
File "", line 1, in
StopIteration
>>>
```
# π― Problems on functions in python β
-> In python, functions are most commonly know as `definition` or `function definition`.
```
def square_of_num(number):
print(number ** 2)
square_of_num(5)
```
### π€ Questions:
π² Basic Function Syntax\
Problem: Write a function to calculate and return the square of a number.
π² Function with Multiple Parameters\
Problem: Create a function that takes two numbers as parameters and returns their sum.
π² Polymorphism in Functions\
Problem: Write a function `multiply` that multiplies two numbers, but can also accept and multiply strings.
π² Function Returning Multiple Values\
Problem: Create a function that returns both the area and circumference of a circle given it's radius.
π² Default Parameter Value\
Problem: Write a function that greets a user. If no name is provided, it should greet with a default name.
π² Lambda Function\
Problem: Create a lambda function to compute the cube of a number.
π² Function with \*args\
Problem: Write a function that takes variable number of arguments and return their sum.
π² Function with \*\*kwargs\
Problem: Create a function that accepts any number of keyword arguments and prints them in the format `key:value`.
π² Generate Function with yield\
Problem: Write a generator function that yields even numbers up to a specified limit.
π² Recursive Function\
Problem: Create a recursive function to calculate the factorila of a number.
# π― Scopes and closure in python β
bag theory
clousure are also know as factory function
```
username = "thecoderwiz"
def func():
# username = "coder"
print(username)
print(username)
func()
```
```
x = 99
def func2(y):
z = x + y
return z
result = func2(1)
print(result)
def func3():
global x
x = 88
func3()
print(x)
```
Clousure
```
def f1():
x = 38
def f2():
print(x)
# f2()
return f2
result = f1()
result()
print(result)
```
```
def chaicoder(num):
def actual(x):
return x ** num
return actual
result = chaicoder(2)
print(result(2))
print(result)
```
# π― Object Oriented Programming in python (OOPs) β
π² Basic Class and Object\
Problem: Create a Car class with attributes like brand and model. Then create an instance of this class.
π² Class Method and Self\
Problem: Add a method to the Car class that displays the full name of the car (brand and model).
π² Inheritance\
Problem: Create an ElectricCar class that inherits from the Car class and has an additional attribute battery_size.
π² Encapsulation\
Problem: Modify the Car class to encapsulate the brand attribute, making it private, and provide a getter method for it.
π² Polymorphism\
Problem: Demonstrate polymorphism by defining a method fuel_type in both Car and ElectricCar classes, but with different behaviours.
π² Class Variables\
Problem: Add a class variable to Car that keeps track of the number of cars created.
π² Static Method\
Problem: Add a static method to the Car class that returns a general description of a car.
π² Property Decorators\
Problem: Use a property decorator in the Car class to make the model attribute read-only.
π² Class Inheritance and isinstance() Function\
Problem: Demonstrate the use of isinstance() to check if my_tesla is an instance of Car and ElectricCar.
π² Multiple Inheritance\
Problem: Create two classes Battery and Engine, and let the ElectricCar class inherit from both, demonstrating multiple inheritance.
# π― Decorators in python β
π² Timing Function Execution\
Problem: Write a decorator that measures the time a function takes to execute.
π² Debugging Function Calls\
Problem: Create a decorator to print the function name and the value of its arguments every time the function is called.
π² Cache Return Values\
Problem: Implement a decorator that chaches the return values of a function, so that when it's called with the same arguments, the cached value is returned instead of re-executing the function.