Python Quick Revision
Python Quick Revision
# Data types
string_var = "Hello, World!"
integer_var = 42
float_var = 3.14159
boolean_var = True
list_var = [1, 2, 3, 4, 5]
tuple_var = (1, 2, 3)
dictionary_var = {"name": "John", "age": 25}
Control Flow:
if isinstance(var, int):
var_type = "Integer"
elif isinstance(var, float):
var_type = "Float"
elif isinstance(var, str):
var_type = "String"
elif isinstance(var, bool):
var_type = "Boolean"
else:
var_type = "Unknown"
for loop
localhost:8888/nbconvert/html/Desktop/Linkedin/Python Quick Revision.ipynb?download=false 1/11
7/5/23, 4:16 PM Python Quick Revision
for i in range(rows):
for j in range(i + 1):
print("*", end="")
print()
while loop
In [4]: # User input validation using a while loop
password = "rachit"
input_password = input("Enter the password: ")
print("Access granted!")
Functions
In [5]: # Function definition
def greet(name):
print("Hello, " + name + "!")
# Function call
greet("Rachit")
Hello, Rachit!
Decorators
In [6]: # Authorization Decorator:
def check_authorization(username, password):
name = "Rachitmore"
pwd = "rachitmore"
if username == name and password == pwd:
return True
else:
return False
def authorization_decorator(func):
localhost:8888/nbconvert/html/Desktop/Linkedin/Python Quick Revision.ipynb?download=false 2/11
7/5/23, 4:16 PM Python Quick Revision
def wrapper(username, userpassword):
try:
if check_authorization(username, password):
return func(username, password)
else:
raise PermissionError("Unauthorized access")
except Exception as e:
return e
return wrapper
@authorization_decorator
def protected_function(username, password):
print("Access granted")
name = "Rachitmore"
password = "rachitmore"
protected_function(name, password)
Access granted
# Accessing elements
print(data_science[0]) # Output: Python
# Modifying elements
data_science[0] = "R language"
print(data_science) # Output: ["R language", "Statistics", "Machine Learning", "Deep Le
# Slicing a list
print(data_science[1:4]) # Output: ['Statistics', 'Machine Learning', 'Deep Learning']
Python
['R language', 'MySql', 'Statistics', 'Machine Learning', 'Deep Learning']
['R language', 'Statistics', 'Machine Learning', 'Deep Learning', 'Cloud']
['Statistics', 'Machine Learning', 'Deep Learning']
R language
Statistics
Machine Learning
Deep Learning
Cloud
# Displaying output
age = int(input("Enter your age: "))
print("Your age is", age)
File Handling
In [9]: import csv
import json
Hello, World!
['Name', 'Age', 'City']
['John', '25', 'New York']
['Alice', '32', 'London']
['Bob', '28', 'Paris']
{'name': 'John', 'age': 30, 'city': 'New York'}
Exception Handling
In [10]: try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("Error: Cannot divide by zero.")
except ValueError:
print("Error: Invalid input.")
Enter a number: 0
Error: Cannot divide by zero.
Iterators
In [11]: # function definition
class NumberIterator:
def __init__(self, limit):
self.limit = limit
self.current = 0
def __iter__(self):
return self
def __next__(self):
if self.current < self.limit:
number = self.current
self.current += 1
return number
else:
raise StopIteration
# driver code
# Using the custom iterator
iterator = NumberIterator(5)
for num in iterator:
print(num)
print("")
Generators
In [12]: # function definition
def fibonacci_generator():
a, b = 0, 1
while True:
yield a
a, b = b, a + b
# driver code
# Using the generator
fib_gen = fibonacci_generator()
for _ in range(5):
print(next(fib_gen))
0
1
1
2
3
def drive(self):
print("Driving", self.brand, self.model)
# Object creation
my_car = Car("Tata Motors", "Nexon")
# Accessing attributes
print(my_car.brand) # Output: Tata Motors
# Calling methods
my_car.drive() # Output: Driving Tata Motors Nexon
Tata Motors
Driving Tata Motors Nexon
Inheritance
In [14]: # Parent class
class Animal:
def __init__(self, name):
localhost:8888/nbconvert/html/Desktop/Linkedin/Python Quick Revision.ipynb?download=false 6/11
7/5/23, 4:16 PM Python Quick Revision
self.name = name
def eat(self):
print(f"{self.name} is eating.")
def bark(self):
print("Woof! Woof!")
def info(self):
print(f"Name : {self.name} and Breed : {self.breed}")
# Creating objects
animal = Animal("Animal")
dog = Dog("Charlie", "Golden Retriever")
Animal is eating.
Charlie is eating.
Woof! Woof!
Name : Charlie and Breed : Golden Retriever
Encapsulation
In [15]: class BankAccount:
def __init__(self, account_number, balance = 100000):
self._account_number = account_number
self._balance = balance
def get_balance(self):
return self._balance
Polymorphism
In [16]: class Shape:
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
Abstraction
In [17]: from abc import ABC, abstractmethod
def area(self):
return 3.14 * self.radius ** 2
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
import mymodule
print(dir(mymodule))
4.0
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__pack
age__', '__spec__', 'greet']
Hello Rachit
# Connecting to a database
conn = sqlite3.connect("mydb.db")
# Inserting data
cursor.execute("INSERT INTO students VALUES (?, ?)", ("Rachit", 25))
cursor.execute("INSERT INTO students VALUES (?, ?)", ("Ankur", 25))
cursor.execute("INSERT INTO students VALUES (?, ?)", ("Jonny", 26))
cursor.execute("INSERT INTO students VALUES (?, ?)", ("Rahul", 26))
cursor.execute("INSERT INTO students VALUES (?, ?)", ("Priya", 23))
for i in cursor1:
print(i)
('Rachit', 25)
('Rachit', 25)
('Rachit', 25)
('Rachit', 25)
('Rachit', 25)
Regular Expressions
In [22]: import re
class Validate:
def __init__(self, username, email, phone, url, date):
self.username = username
self.email = email
self.phone = phone
self.url = url
self.date = date
self.data_validate()
# Data validation
def validate_username(self):
localhost:8888/nbconvert/html/Desktop/Linkedin/Python Quick Revision.ipynb?download=false 10/11
7/5/23, 4:16 PM Python Quick Revision
pattern = r"^[a-zA-Z0-9_ ]+$"
result = re.match(pattern, self.username)
if result:
print(f"{self.username} is valid.")
else:
print(f"{self.username} is invalid.")
# Validating URLs
def validate_url(self):
pattern = r"^http(s)?://"
result = re.match(pattern, self.url)
if result:
print(f"{self.url} is valid.")
else:
print(f"{self.url} is invalid.")
# Data extraction
def validate_dates(self):
pattern = r"\d{1,2}[/-]\d{1,2}[/-]\d{2,4}"
result = re.findall(pattern, self.date)
if result:
print(f"{self.date} Valid:")
else:
print(f"{self.date} invalid.")
# Data extraction
def data_validate(self):
self.validate_username()
self.validate_email()
self.validate_phone_numbers()
self.validate_url()
self.validate_dates()
Valid details
Invalid details
Rachit@More is invalid.
rachitmore@gmailis invalid.
No phone numbers found or invalid phone number.
www.example is invalid.
No dates invalid.
In [ ]: