0% found this document useful (0 votes)
14 views11 pages

Python Quick Revision Notes

Uploaded by

eterno2e2023
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views11 pages

Python Quick Revision Notes

Uploaded by

eterno2e2023
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

7/5/23, 4:16 PM Python Quick Revision

Variables and Data Types


In [1]: # Variable assignment
name = "Rachit"
age = 25
is_student = True

# 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}

print(f"Variable : {string_var} , data type : {type(string_var)}")


print(f"Variable : {integer_var} , data type : {type(integer_var)}")
print(f"Variable : {float_var} , data type : {type(float_var)}")
print(f"Variable : {boolean_var} , data type : {type(boolean_var)}")
print(f"Variable : {list_var} , data type : {type(list_var)}")
print(f"Variable : {tuple_var} , data type : {type(tuple_var)}")
print(f"Variable : {dictionary_var} , data type : {type(dictionary_var)}")

Variable : Hello, World! , data type : <class 'str'>


Variable : 42 , data type : <class 'int'>
Variable : 3.14159 , data type : <class 'float'>
Variable : True , data type : <class 'bool'>
Variable : [1, 2, 3, 4, 5] , data type : <class 'list'>
Variable : (1, 2, 3) , data type : <class 'tuple'>
Variable : {'name': 'John', 'age': 25} , data type : <class 'dict'>

Control Flow:

if elif and else


In [2]: var = 10

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"

print(f"Variable: {var}, Type: {var_type}")

Variable: 10, Type: Integer

for loop
localhost:8888/nbconvert/html/Desktop/Linkedin/Python Quick [Link]?download=false 1/11
7/5/23, 4:16 PM Python Quick Revision

In [3]: # Nested loops to create a pattern


rows = int(input("Enter the row number :"))

for i in range(rows):
for j in range(i + 1):
print("*", end="")
print()

Enter the row number :5


*
**
***
****
*****

while loop
In [4]: # User input validation using a while loop
password = "rachit"
input_password = input("Enter the password: ")

while input_password != password:


print("Incorrect password. Try again.")
input_password = input("Enter the password: ")

print("Access granted!")

Enter the password: Rachit


Incorrect password. Try again.
Enter the password: rachit
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 [Link]?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

Lists and List Manipulation


In [7]: # List creation
data_science = ["Python", "MySql", "Statistics", "Machine Learning", "Deep Learning"]

# 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

# Appending and removing elements


data_science.append("Cloud")
data_science.remove("MySql")
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']

# Iterating over a list


for discipline in data_science:
print(discipline)

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

Input and Output

localhost:8888/nbconvert/html/Desktop/Linkedin/Python Quick [Link]?download=false 3/11


7/5/23, 4:16 PM Python Quick Revision

In [8]: # Accepting user input


name = input("Enter your name: ")
print("Hello, " + name + "!")

# Displaying output
age = int(input("Enter your age: "))
print("Your age is", age)

Enter your name: Rachit


Hello, Rachit!
Enter your age: 25
Your age is 25

File Handling
In [9]: import csv
import json

# Writing and Reading txt Files


file = open("[Link]", "w")
[Link]("Hello, World!")
[Link]()

file = open("[Link]", "r")


content = [Link]()
[Link]()
print(content)

# Writing and Reading csv Files


data = [
['Name', 'Age', 'City'],
['John', '25', 'New York'],
['Alice', '32', 'London'],
['Bob', '28', 'Paris']
]

with open('[Link]', 'w', newline='') as file:


csv_writer = [Link](file)
csv_writer.writerows(data)
[Link]()

with open('[Link]', 'r') as file:


csv_reader = [Link](file)
for row in csv_reader:
print(row)
[Link]()

# Writing and Reading JSON file


data = {
'name': 'John',
'age': 30,
'city': 'New York'
}

with open('[Link]', 'w') as file:


[Link](data, file)
[Link]()

localhost:8888/nbconvert/html/Desktop/Linkedin/Python Quick [Link]?download=false 4/11


7/5/23, 4:16 PM Python Quick Revision
with open('[Link]', 'r') as file:
data = [Link](file)
[Link]()
print(data)

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):
[Link] = limit
[Link] = 0

def __iter__(self):
return self

def __next__(self):
if [Link] < [Link]:
number = [Link]
[Link] += 1
return number
else:
raise StopIteration

# driver code
# Using the custom iterator
iterator = NumberIterator(5)
for num in iterator:
print(num)
print("")

localhost:8888/nbconvert/html/Desktop/Linkedin/Python Quick [Link]?download=false 5/11


7/5/23, 4:16 PM Python Quick Revision
0
1
2
3
4

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

Object-Oriented Programming (OOP)


In [13]: # Class definition
class Car:
def __init__(self, brand, model):
[Link] = brand
[Link] = model

def drive(self):
print("Driving", [Link], [Link])

# 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 [Link]?download=false 6/11
7/5/23, 4:16 PM Python Quick Revision
[Link] = name

def eat(self):
print(f"{[Link]} is eating.")

# Child class inheriting from parent


class Dog(Animal):
def __init__(self, name, breed):
# Calling the parent class constructor
super().__init__(name)
[Link] = breed

def bark(self):
print("Woof! Woof!")

def info(self):
print(f"Name : {[Link]} and Breed : {[Link]}")

# Creating objects
animal = Animal("Animal")
dog = Dog("Charlie", "Golden Retriever")

# Accessing parent class methods


[Link]()

# Accessing child class methods


[Link]()
[Link]()
[Link]()

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 deposit(self, amount):


if amount > 0:
self._balance += amount
print(f"Deposited {amount}. New balance: {self._balance}")

def withdraw(self, amount):


if amount > 0 and amount <= self._balance:
self._balance -= amount
print(f"Withdrew {amount}. New balance: {self._balance}")
else:
print("Insufficient funds.")

def get_balance(self):
return self._balance

localhost:8888/nbconvert/html/Desktop/Linkedin/Python Quick [Link]?download=false 7/11


7/5/23, 4:16 PM Python Quick Revision

# Creating an instance of the BankAccount class


account = BankAccount("1234567890")

# Accessing methods with encapsulated attributes


balance = account.get_balance()
print("Current balance:", balance)
[Link](20000)
[Link](50000)

Current balance: 100000


Withdrew 20000. New balance: 80000
Deposited 50000. New balance: 130000

Polymorphism
In [16]: class Shape:
def area(self):
pass

class Circle(Shape):
def __init__(self, radius):
[Link] = radius

def area(self):
return 3.14 * [Link] ** 2

class Rectangle(Shape):
def __init__(self, width, height):
[Link] = width
[Link] = height

def area(self):
return [Link] * [Link]

# Create instances of different shapes


circle = Circle(5)
rectangle = Rectangle(4, 6)

# Call the area method on different shapes


print("Area of the circle:", [Link]())
print("Area of the rectangle:", [Link]())

Area of the circle: 78.5


Area of the rectangle: 24

Abstraction
In [17]: from abc import ABC, abstractmethod

# Abstract parent class


class Shape(ABC):
@abstractmethod
def area(self):
pass

localhost:8888/nbconvert/html/Desktop/Linkedin/Python Quick [Link]?download=false 8/11


7/5/23, 4:16 PM Python Quick Revision

# Concrete classes implementing Shape


class Circle(Shape):
def __init__(self, radius):
[Link] = radius

def area(self):
return 3.14 * [Link] ** 2

class Rectangle(Shape):
def __init__(self, width, height):
[Link] = width
[Link] = height

def area(self):
return [Link] * [Link]

# Create instances of different shapes


circle = Circle(5)
rectangle = Rectangle(4, 6)

# Call the area method on different shapes


print("Area of the circle:", [Link]())
print("Area of the rectangle:", [Link]())

Area of the circle: 78.5


Area of the rectangle: 24

Modules and Packages


In [18]: # Importing modules
import math

print([Link](16)) # Output: 4.0

import mymodule
print(dir(mymodule))

[Link]("Rachit") # Output: Hello, John!

4.0
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__pack
age__', '__spec__', 'greet']
Hello Rachit

Working with Databases


In [21]: # SQLite example
import sqlite3

# Connecting to a database
conn = [Link]("[Link]")

# Creating a cursor object


cursor = [Link]()

# Executing SQL queries

localhost:8888/nbconvert/html/Desktop/Linkedin/Python Quick [Link]?download=false 9/11


7/5/23, 4:16 PM Python Quick Revision
[Link]("CREATE TABLE IF NOT EXISTS students (name TEXT, age INTEGER)")

# Inserting data
[Link]("INSERT INTO students VALUES (?, ?)", ("Rachit", 25))
[Link]("INSERT INTO students VALUES (?, ?)", ("Ankur", 25))
[Link]("INSERT INTO students VALUES (?, ?)", ("Jonny", 26))
[Link]("INSERT INTO students VALUES (?, ?)", ("Rahul", 26))
[Link]("INSERT INTO students VALUES (?, ?)", ("Priya", 23))

# Executing SQL queries


[Link]("Select * from students")

for i in cursor1:
print(i)

# Committing the changes


[Link]()

# Closing the connection


[Link]()

('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):
[Link] = username
[Link] = email
[Link] = phone
[Link] = url
[Link] = date
self.data_validate()

# Validating email addresses


def validate_email(self):
pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
result = [Link](pattern, [Link])
if result:
print(f"{[Link]} is valid.")
else:
print(f"{[Link]}is invalid.")

# Extracting phone numbers


def validate_phone_numbers(self):
pattern = r"\d{3}-\d{3}-\d{4}"
result = [Link](pattern, [Link])
if result:
print(f"{[Link]} phone numbers found:", result)
else:
print("No phone numbers found or invalid phone number.")

# Data validation
def validate_username(self):
localhost:8888/nbconvert/html/Desktop/Linkedin/Python Quick [Link]?download=false 10/11
7/5/23, 4:16 PM Python Quick Revision
pattern = r"^[a-zA-Z0-9_ ]+$"
result = [Link](pattern, [Link])
if result:
print(f"{[Link]} is valid.")
else:
print(f"{[Link]} is invalid.")

# Validating URLs
def validate_url(self):
pattern = r"^http(s)?://"
result = [Link](pattern, [Link])
if result:
print(f"{[Link]} is valid.")
else:
print(f"{[Link]} is invalid.")

# Data extraction
def validate_dates(self):
pattern = r"\d{1,2}[/-]\d{1,2}[/-]\d{2,4}"
result = [Link](pattern, [Link])
if result:
print(f"{[Link]} Valid:")
else:
print(f"{[Link]} invalid.")

# Data extraction
def data_validate(self):
self.validate_username()
self.validate_email()
self.validate_phone_numbers()
self.validate_url()
self.validate_dates()

print("Valid details \n")


obj1 = Validate("Rachit More","rachitmore3@[Link]","123-456-7890","[Link]
print("\nInvalid details \n")
obj2 = Validate("Rachit@More","rachitmore@gmail","qwerty","[Link]","No dates")

Valid details

Rachit More is valid.


rachitmore3@[Link] is valid.
123-456-7890 phone numbers found: ['123-456-7890']
[Link] is valid.
07/05/2023 Valid:

Invalid details

Rachit@More is invalid.
rachitmore@gmailis invalid.
No phone numbers found or invalid phone number.
[Link] is invalid.
No dates invalid.

In [ ]:

localhost:8888/nbconvert/html/Desktop/Linkedin/Python Quick [Link]?download=false 11/11

Common questions

Powered by AI

The Python code demonstrates OOP concepts such as encapsulation, inheritance, polymorphism, and abstraction. Encapsulation is shown by the BankAccount class, which hides account details and provides public methods for interaction. Inheritance is seen in the Dog class, inheriting from Animal, enabling reusability of the eat method. Polymorphism is illustrated by the Shape class example with Circle and Rectangle, where different shapes implement the area method. Abstraction is presented through the abstract Shape class, defining a common interface with the abstract method area(), which must be implemented by any subclass .

Python modules enhance functionality and modularity by encapsulating related code into separate files, improving code organization and reusability. For example, the math module provides functions like sqrt() for mathematical operations, demonstrating built-in functionality extension. Custom modules can be created to group user-defined functions, such as a greet function in a module to print customized messages. Modules can be imported into programs, making functions available for use, enhancing program clarity, reducing duplication of code, and supporting structured development .

Decorators in Python are significant for modifying or enhancing the behavior of functions or methods. They are higher-order functions that take another function as an argument and return a new function. For instance, an @authorization_decorator checks user credentials before granting access to a protected function. This modularizes the control aspects such as authorization, making the code more readable and reusable by separating concerns .

Effective data validation in Python can follow a structured pattern where input data is checked against specific criteria using regular expressions and controlled loops. This involves isolating validation logic into classes or functions for modular implementation. For instance, the Validate class uses separate methods for email, phone number, and URL validation, applying regex patterns to match formats. This separation of concerns ensures validation rules are maintainable and can handle different validation scenarios effectively, enhancing code readability and reliability .

In Python, file handling is accomplished by using methods to open, read, write, and close files. For text files, the open() function is used with modes such as 'r' for reading, 'w' for writing, and 'a' for appending. Example: file.write('Hello, World!') writes 'Hello, World!' to a text file. For CSV files, the csv module allows for structured data manipulation; csv_writer.writerows(data) writes rows of data to a CSV file. Files should be closed after operations to free up resources, typically using file.close() or with statements for auto-cleanup .

Regular expressions in Python offer a powerful way to validate and manipulate text by specifying patterns. They are used to verify formats of data such as emails, phone numbers, URLs, and dates. For instance, the pattern r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$" validates email addresses by ensuring the basic structure of an email is followed. Similarly, the pattern r"\d{3}-\d{3}-\d{4}" matches phone numbers of a specific format. These tools enable efficient data validation and extraction processes, important in applications requiring user input and format checks .

Exception handling in Python, using try-except blocks, improves error management by catching and dealing with errors gracefully, allowing the program to continue running. An example is catching ZeroDivisionError to avoid program crashes due to division by zero. Iterators such as custom iterator classes allow for sequence processing in a memory-efficient manner. Python's StopIteration exception is used to signal the end of an iteration, allowing for precise control over sequence traversal without exhausting resources .

Loops are instrumental in data validation and user interaction in Python by providing iterative control flow. For example, while loops can repeatedly prompt users to input valid data until the correct condition is met, such as re-entering a password until the correct one is inputted (while input_password != password). Nested loops can be used for patterns or repetitive actions, such as displaying rows of stars. By leveraging loops, Python can efficiently handle user-centric tasks requiring repeated checks or outputs .

SQLite provides advantages in Python applications through its simplicity and self-contained database engine, making it suitable for embedded database purposes without the need for a separate server. Interaction with SQLite involves connecting via the sqlite3 module, executing SQL queries, and managing transactions and cursors for data operations. Example: creating a students table, inserting data, and retrieving using SELECT queries. SQLite is favorable for applications that require compact data storage, ease of use, and integration directly within Python scripts .

Python supports various built-in data types such as strings, integers, floats, booleans, lists, tuples, and dictionaries. For example, 'Hello, World!' is a string, 42 is an integer, 3.14159 is a float, and [1, 2, 3, 4, 5] is a list. These data types allow Python to perform operations like arithmetic on numbers or concatenations on strings. Type-checking can be done using the isinstance function to determine a variable's datatype, which facilitates dynamic and flexible coding in Python .

You might also like