python
python
Python Basics
python
Copy code
# Example
x = 5 # Integer
print(x, y)
python
Copy code
x = 10
y = 20.5
z = "Python"
my_list = [1, 2, 3]
my_tuple = (1, 2, 3)
my_set = {1, 2, 3}
1.3. Operators
python
Copy code
x = 10
y=5
print(x + y) # 15
print(x == y) # False
python
Copy code
x = 10
if x > 5:
elif x == 5:
print("x is 5")
else:
1.5. Loops
python
Copy code
# For loop
for i in range(5):
print(i)
# While loop
i=0
while i < 5:
print(i)
i += 1
1.6. Functions
Functions help to reuse code and break problems into smaller tasks.
python
Copy code
def greet(name):
greet("Alice")
2. Intermediate Python
python
Copy code
my_list = [1, 2, 3]
print(my_list) # [1, 2, 3, 4]
python
Copy code
print(my_dict["name"]) # Alice
Tuple: Immutable list of elements.
python
Copy code
my_tuple = (1, 2, 3)
python
Copy code
python
Copy code
try:
print(10 / 0)
except ZeroDivisionError:
finally:
python
Copy code
# Write to a file
file.write("Hello, world!")
content = file.read()
print(content)
3. Advanced Python
python
Copy code
class Person:
self.name = name
self.age = age
def greet(self):
python
Copy code
class Employee(Person):
super().__init__(name, age)
self.salary = salary
3.2. Decorators
A way to modify or enhance functions.
python
Copy code
def decorator_function(original_function):
def wrapper_function():
return original_function()
return wrapper_function
@decorator_function
def display():
display()
3.3. Generators
python
Copy code
def my_generator():
for i in range(5):
yield i
gen = my_generator()
print(next(gen)) # 0
print(next(gen)) # 1
python
Copy code
file.write("Hello, World!")
python
Copy code
import re
print(result.group()) # Spain
python
Copy code
add = lambda x, y: x + y
print(add(2, 3)) # 5
Modules are Python files that can be imported. Packages are directories
with multiple modules.
python
Copy code
# Importing modules
import math
print(math.sqrt(16)) # 4.0
python
Copy code
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
ChatGPT said:
ChatGPT
Defining a Function
Functions in Python are defined using the def keyword. Here’s the general
syntax:
python
Copy code
def function_name(parameters):
# Function body
return result
python
Copy code
def greet():
print("Hello, World!")
2. Function Parameters
Arguments are passed to the function in the order in which they are
defined.
python
Copy code
def greet(name):
print(f"Hello, {name}!")
Default values can be set for function parameters, which are used if no
argument is passed.
python
Copy code
def greet(name="World"):
print(f"Hello, {name}!")
python
Copy code
python
Copy code
def sum_all(*args):
return sum(args)
python
Copy code
def display_info(**kwargs):
print(f"{key}: {value}")
display_info(name="Alice", age=30, country="USA")
# Output:
# name: Alice
# age: 30
# country: USA
3. Return Statement
python
Copy code
return a + b
result = add(2, 3)
print(result) # Output: 5
4. Lambda Functions
python
Copy code
python
Copy code
add = lambda a, b: a + b
python
Copy code
numbers = [1, 2, 3, 4, 5]
5. Scope of Variables
python
Copy code
def func():
x = 5 # Local variable
print(x)
func() # Output: 5
Variables defined outside all functions are globally accessible within the
script.
python
Copy code
x = 10 # Global variable
def func():
func() # Output: 10
python
Copy code
x = 10
def modify():
global x
modify()
print(x) # Output: 20
python
Copy code
def outer():
x = "outer variable"
def inner():
nonlocal x
x = "modified"
inner()
print(x)
6. Recursion
A function is recursive if it calls itself. Recursion is useful for tasks that
can be broken down into similar sub-tasks (like factorial or Fibonacci).
python
Copy code
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
7. Higher-Order Functions
python
Copy code
numbers = [1, 2, 3, 4]
python
Copy code
numbers = [1, 2, 3, 4, 5]
Example of a Decorator
python
Copy code
def decorator_function(original_function):
def wrapper_function():
return original_function()
return wrapper_function
@decorator_function
def display():
display()
# Output:
Syntax:
python
Copy code
Example:
python
Copy code
double = lambda x: x * 2
print(double(5)) # Output: 10
Example:
python
Copy code
numbers = [1, 2, 3, 4, 5]
print(len(numbers)) # Output: 5
print(max(numbers)) # Output: 5
print(min(numbers)) # Output: 1
python
Copy code
return x + y
python
Copy code
p = Point(1, 2)
python
Copy code
d = deque([1, 2, 3])
d.append(4)
d.appendleft(0)
python
Copy code
python
Copy code
dd = defaultdict(int)
dd['apple'] += 1
13.1. Iterators
python
Copy code
my_list = [1, 2, 3]
it = iter(my_list)
print(next(it)) # Output: 1
print(next(it)) # Output: 2
print(next(it)) # Output: 3
13.2. Generators
A generator is a type of iterator that generates values on the fly and uses
yield instead of return. It is more memory-efficient for large data sets.
python
Copy code
def my_generator():
for i in range(5):
yield i
gen = my_generator()
print(value) # Output: 0 1 2 3 4
python
Copy code
def bold_decorator(func):
def wrapper():
return f"<b>{func()}</b>"
return wrapper
def italic_decorator(func):
def wrapper():
return f"<i>{func()}</i>"
return wrapper
@bold_decorator
@italic_decorator
def greet():
return "Hello"
print(greet()) # Output: <b><i>Hello</i></b>
python
Copy code
def repeat(num):
def decorator(func):
for _ in range(num):
func(*args, **kwargs)
return wrapper
return decorator
@repeat(3)
def say_hello():
print("Hello")
say_hello()
# Output:
# Hello
# Hello
# Hello
python
Copy code
numbers = [1, 2, 3, 4]
python
Copy code
numbers = [1, 2, 3, 4, 5]
python
Copy code
numbers = [1, 2, 3, 4]
print(product) # Output: 24
15.2. zip()
python
Copy code
16.1. Multithreading
python
Copy code
import threading
def print_numbers():
for i in range(5):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
16.2. Multiprocessing
python
Copy code
def print_numbers():
for i in range(5):
print(i)
process = Process(target=print_numbers)
process.start()
process.join()
16.3. Asynchronous Programming (asyncio)
python
Copy code
import asyncio
print("Hello")
await asyncio.sleep(1)
print("World")
asyncio.run(say_hello())
python
Copy code
f.write(b'Hello, World!')
content = f.read()
python
Copy code
import json
json.dump(data, f)
content = json.load(f)
python
Copy code
import re
pattern = r"\bS\w+"
if match:
python
Copy code
pattern = r"(\d+)-(\d+)"
if match:
19. Metaprogramming
python
Copy code
obj = MyClass()
print(obj.x) # Output: 10
python
Copy code
class Person:
self.name = name
p = Person("Alice")
python
Copy code
class MyContext:
def __enter__(self):
print("Entering")
return self
print("Exiting")
with MyContext():
print("Inside")