[go: up one dir, main page]

0% found this document useful (0 votes)
17 views16 pages

PWP Try 3

The document outlines key differences between Python data structures such as lists, tuples, sets, and dictionaries, highlighting their definitions, syntax, mutability, performance, and use cases. It also covers concepts of inheritance in Python, including various types like single, multiple, and hierarchical inheritance, along with examples. Additionally, it discusses user-defined packages, membership operators, exception handling, and built-in functions, providing a comprehensive overview of Python's core concepts and functionalities.
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)
17 views16 pages

PWP Try 3

The document outlines key differences between Python data structures such as lists, tuples, sets, and dictionaries, highlighting their definitions, syntax, mutability, performance, and use cases. It also covers concepts of inheritance in Python, including various types like single, multiple, and hierarchical inheritance, along with examples. Additionally, it discusses user-defined packages, membership operators, exception handling, and built-in functions, providing a comprehensive overview of Python's core concepts and functionalities.
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
You are on page 1/ 16

Difference Between List and Tuple in Python

Aspect List Tuple

Tuple is a collection of
List is a collection of ordered,
Definition ordered, immutable
mutable elements.
elements.

Defined using parentheses


Syntax Defined using square brackets []
()

Mutable – can be changed Immutable – cannot be


Mutability
(add/delete/update). changed once defined.

Methods Has more built-in methods (like Has fewer built-in methods
Available append(), extend(), remove()) (count(), index())

Faster than lists due to


Performance Slower than tuples in iteration
immutability

Used when data needs to be Used when data is constant


Use Case
changed frequently and shouldn’t change

Memory Usage Consumes more memory More memory efficient

difference between Set, Tuple, and Dictionary in a clean row and column format
without emojis:

Feature Set Tuple Dictionary

Unordered Ordered Collection of key-value


Type
collection collection pairs

Mutable Yes No Yes

Yes (by
Indexed Access No Yes (by key)
position)

Duplicates
No Yes Keys - No, Values - Yes
Allowed

Syntax {1, 2, 3} (1, 2, 3) {'a': 1, 'b': 2}

Through loop By index (e.g.,


Element Access By key (e.g., d['a'])
only t[0])

Store unique Store mapped/related


Use Case Store fixed data
items data

1
Concept of Inheritance in Python:- Inheritance is an OOP (Object-Oriented
Programming) concept that allows a class (child class) to acquire properties and
methods from another class (parent class). Python uses Method Resolution Order
(MRO) to decide which method to call when there are multiple parents.Multiple
inheritance allows the child to inherit all accessible properties and methods from
multiple parents.
Types of Inheritance in Python:-
Single Inheritance:- A child class inherits from one parent class. Child inherits from
Parent. It can access methods of Parent.
Multiple Inheritance:- A child class inherits from more than one parent class.
Child inherits from both Father and Mother.
Multilevel Inheritance A class is derived from a class which is already derived from
another class (grandparent → parent → child). Child inherits from Parent, and Parent
inherits from Grandparent.
Hierarchical Inheritance:- Multiple child classes inherit from the same parent class.
Both Child1 and Child2 inherit from the same Parent.
Hybrid Inheritance:- A combination of two or more types of inheritance. This
combines multilevel (A → B → D) and multiple (B, C → D) inheritance.
Example: Multiple Inheritance in Python
class Father:
def father_info(self):
print("Father's info")
class Mother:
def mother_info(self):
print("Mother's info")
class Child(Father, Mother):
def child_info(self):
print("Child's info")
obj = Child()
obj.father_info()
obj.mother_info()
obj.child_info()

2
Concept: User-Defined Package in Python:- A package is a collection of Python
modules organized in directories with an __init__.py file. This helps to logically
organize your code. my_package is the name of the package (a folder).greetings is a
module (a .py file) within that package.You use from my_package import greetings to
access functions. __init__.py is required to make Python treat the directory as a
package (can be empty).

greetings.py (Module inside package)


def say_hello(name):
print(f"Hello, {name}!")
def say_goodbye(name):
print(f"Goodbye, {name}!")

main.py (Main program that uses the package)


from my_package import greetings
greetings.say_hello("Rahul")
greetings.say_goodbye("Rahul")

Output:
Hello, Rahul!
Goodbye, Rahul!

Create class with name & roll number / ID and name and display
class Student:
def __init__(self, name, roll_no):
self.name = name
self.roll_no = roll_no
def display_info(self):
print(f"Name: {self.name}")
print(f"Roll Number: {self.roll_no}")
student1 = Student("Aman", 101)
student1.display_info()
Output
Name: Aman
Roll Number: 101

3
Membership Operators in Python:- Membership operators are used to test
whether a value or variable is present in a sequence such as a string, list, tuple,
dictionary, or set. in checks if a value exists in a sequence. not in checks if a value
does not exist. Mainly used in conditions, loops, and search operations.
Types of Membership Operators:
In:- Returns True if the value is found in the sequence. Eg :- 'a' in 'apple' → True
not in :- Returns True if the value is not found. Eg 3 not in [1, 2, 3] → False
Examples:
# String print('h' in 'hello') # Output: True print('x' not in 'hello') # Output: True
Identity Operators:- Identity operators are used to compare memory locations of
two objects.
Is:- Returns True if both variables refer to the same object. Eg :- a is b
is not:- Returns True if they do not refer to the same object.eg :- a is not b
Bitwise Operators:- Bitwise operators operate on integers at the bit level.
& :- Bitwise AND eg :- 5 & 3 result :- 1
| :- Bitwise OR eg :- 5 | 3 result :- 7
^ :- Bitwise XOR eg :- 5 ^ 3 result :- 6
~ :- Bitwise NOT eg :- ~5 result :- -6
<< :- Left Shift eg :- 5 << 1 result :- 10
>> :- Right Shift eg :- 5 >> 1 result :- 2
Assignment Operators:- Assignment operators are used to assign values to
variables. Some also perform operations and then assign the result.
Assignment Operators
= :- Assign value eg :- x = 10 result :- x becomes 10
+= :- Add and assign eg :- x += 5 result :- x = x + 5
-= :- Subtract and assign eg :- x -= 2 result :- x = x - 2
*= :- Multiply and assign eg :- x *= 3 result :- x = x * 3
/= :- Divide and assign eg :- x /= 2 result :- x = x / 2
%= :- Modulus and assign eg :- x %= 3 result :- x = x % 3
**= :- Exponent and assign eg :- x **= 2 result :- x = x ** 2
//= :- Floor divide and assign eg :- x //= 2 result :- x = x // 2

4
The mkdir() function is used in programming to create a new directory (folder). It is
used to create a new empty folder. It may raise an error if the folder already exists
or if permissions are denied.
import os
os.mkdir("myFolder")

Explain building blocks of python


Character Set in Python:
The character set includes all characters Python can recognize.

Type Examples

Letters A–Z, a–z (Uppercase and lowercase alphabets)

Digits 0–9

Special Symbols +, -, *, **, /, //, %, ==, !=, >, <, etc.

Whitespaces Space, tab, newline

Other Characters All ASCII and Unicode characters

Tokens in Python:- Tokens are the smallest building blocks of a Python program,
like words in a sentence.
Types of Tokens:
1. Keywords – Reserved words with special meaning
Examples: if, else, True, False, return, import, lambda, etc.
2. Identifiers – Names for variables, functions, classes, etc.
Examples: square, num, a_lst
3. Literals – Fixed values used in code
o String Literals: 'Mayank', 'abc'
o Numeric Literals: 1, 1.2, -3.95
o Boolean Literals: True, False
o Special Literal: None (represents “nothing”)

5
Method Overloading:- Method Overloading means defining multiple methods
with the same name but different parameters in a class. Python does not
support traditional method overloading like Java or C++. Instead, it can be
achieved using default parameters or *args and **kwargs. Based on Number/type
of parameters. Purpose Perform similar tasks with different inputs

Example (Using Default Parameters):


class Greet:
def hello(self, name=None):
if name:
print(f"Hello, {name}!")
else:
print("Hello!")
g = Greet()
g.hello() # Output: Hello!
g.hello("Alice") # Output: Hello, Alice!
Method Overriding:-Method Overriding means defining a method in the child
class with the same name as in the parent class. The child class method
replaces (overrides) the parent class method.based on Inheritance (parent-child
relationship).purpose Provide specific behavior in subclass

Example:
class Animal:
def speak(self):
print("Animal speaks")
class Dog(Animal):
def speak(self):
print("Dog barks")
d = Dog()
d.speak() # Output: Dog barks

6
Modes of File Object in Python:- In Python, when opening a file using the open()
function, you must specify the mode — it defines how the file will be used (read,
write, append, etc.).
Common File Modes:

Mode Description

'r' Read (default mode) – file must exist

'w' Write – creates a new file or overwrites

'a' Append – adds data to the end of the file

'r+' Read and write – file must exist

'w+' Write and read – creates or overwrites

'a+' Append and read – file is created if not exists

'rb' Read in binary mode

'wb' Write in binary mode

'ab' Append in binary mode

Detailed Explanation of Four Modes:


1.'r' – Read Mode
 Opens the file for reading only. File must
exist, or it raises an error.
2 'w' – Write Mode
 Opens file for writing. If the file exists, it
overwrites it. If not, it creates a new file.
3.’a' – Append Mode
 Opens file for appending new data.
 Does not delete existing content.
 Creates the file if it doesn’t exist.
4.'r+' – Read and Write Mode
 Opens file for both reading and writing.
 File must exist, or an error is raised.

7
Summary – Python Data Types and Core Concepts
Basic Data Types:
 String (str): Text data inside 'single' or "double" quotes. Characters can be
accessed using indexing.
 Integer (int) and Float (float): Used for whole numbers and decimal
numbers. Can be used in arithmetic operations.
 Boolean (bool): Holds True or False values. 1 is True, 0 is False.
Core Data Structures:
 List: Ordered, mutable collection. Declared with brackets [].
 Tuple: Ordered, immutable collection. Declared with parentheses ().
 Dictionary: Collection of key-value pairs. Declared with {} using : for pairs.
 Set: Unordered collection of unique items. Also declared with {} but without
key-value.
Examples:
 x = 'abcd' (String)
 x = [10, 20] (List)
 x = (10, 20) (Tuple)
 x = {'a': 1, 'b': 2} (Dictionary)
 x = set(['a', 'b', 'a']) → {'a', 'b'} (Set)
Additional Concepts:
 Control Structures: Direct the flow of code. Includes if-else, for, while, and
try-except.
 Functions: Defined with def, used to group reusable code.
 Modules: Python files with reusable code, imported using import.
 Packages: Collections of modules grouped together for distribution and
reuse.

8
Exception:- An exception is an error that occurs during the execution of a program.
When Python encounters an error (like dividing by zero, accessing a missing file,
etc.), it raises an exception. If not handled, the program will crash. The try-except
block is used to catch and handle exceptions so the program doesn't crash.
Eg
class PasswordIncorrectError(Exception):
def __init__(self, message="Password is incorrect!"):
self.message = message
super().__init__(self.message)
def check_password(password):
correct_password = "Python@123" # Predefined correct password
if password != correct_password:
raise PasswordIncorrectError
else:
print("Access Granted. Password is correct.")
try:
user_password = input("Enter your password: ")
check_password(user_password)
except PasswordIncorrectError as e:
print("Access Denied:", e)

NumPy (Numerical Python) is a powerful Python library used for: Numerical


computations . Working with large arrays and matrices. Performing mathematical
operations efficiently
Key Features of NumPy:
Provides ndarray (N-dimensional array object. Supports vectorized operations
(faster than Python loops). Useful for scientific and mathematical computations.
Offers random number generation, linear algebra, statistics, etc.
Eg
import numpy as np
random_numbers = np.random.randint(10, 51, size=5)
print("Random integers between 10 and 50:", random_numbers)
output:- Random integers between 10 and 50: [35 47 12 28 44]

9
A dictionary in Python is created using curly braces {} and stores data in key:
value pairs. Eg student = { "roll_no": 1, "name": "Amit", "branch": "CO" }
You can access values by using the key inside square brackets or with the .get()
method. Eg print(student["name"]) # Output: Amit
print(student.get("roll_no")) # Output: 1
Removes the item with the specified key and returns its value. Raises error if key not
found. student.pop("branch")
print(student) # {'roll_no': 1, 'name': 'Amit'}
del statement :- Deletes a specific key-value pair.
del student["name"]
print(student) # {'roll_no': 1}

Built-in Functions with Example


len():- Returns the number of items in an object (string, list, tuple, etc.)
Example:
name = "Python"
print(len(name)) # Output: 6
type():- Returns the data type of the object.
Example:
a = 10
print(type(a)) # Output: <class 'int'>
input():- Takes input from the user as a string.
Example:
name = input("Enter your name: ")
print("Hello", name)
int():- Converts a string or float into an integer.
Example:
num = int("5")
print(num + 1) # Output: 6

10
Four Built-in List Functions
append() – Adds an element to the end of the list.
my_list = [1, 2, 3]
my_list.append(4)
print(my_list) # Output: [1, 2, 3, 4]
insert(index, element) – Inserts an element at a specific index.
my_list.insert(1, 10)
print(my_list) # Output: [1, 10, 2, 3, 4]
remove() – Removes the first occurrence of an element.
my_list.remove(10)
print(my_list) # Output: [1, 2, 3, 4]
sort() – Sorts the list in ascending order.
my_list.sort()
print(my_list) # Output: [1, 2, 3, 4]
Four Built-in Functions on Set
add() – Adds an element to the set.
s = {1, 2, 3}
s.add(4)
print(s) # Output: {1, 2, 3, 4}
remove() – Removes an element from the set; gives error if not found.
s.remove(2)
print(s) # Output: {1, 3, 4}
discard() – Removes an element; does not give an error if not found.
s.discard(5) # No error
union() – Combines two sets, returns a new set with all unique elements.
a = {1, 2}
b = {2, 3}
print(a.union(b)) # Output: {1, 2, 3}

11
# Palindrome number checker
num = input("Enter a number: ")
# clean_text = text.replace(" ", "").lower()
if num == num[::-1]:
print(f"{num} is a palindrome.")
else:
print(f"{num} is not a palindrome.")

for i in range(1, 5): # Outer loop for rows


for j in range(1, i + 1): # Inner loop for numbers
print(j, end=' ')
print()
Write a program for importing module for addition and subtraction of two numbers
# mymath.py
def add(a, b):
return a + b
def subtract(a, b):
return a - b
# main.py
import mymath # importing custom module
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
print("Addition:", mymath.add(num1, num2))
print("Subtraction:", mymath.subtract(num1, num2))
1. read() Function:- Purpose: Reads the entire contents of a file as a single string.
Syntax: file.read(size) Parameters:- size (optional): Number of bytes/characters to
read. If omitted, reads the whole file.
2. readline() Function:- Purpose: Reads one line at a time from a file.
Syntax: file.readline(size) Parameters:- size (optional): Number of characters to
read from the line.

12
Local Variable:- A local variable is a variable that is declared inside a function
and can be used only within that function. It is created when the function starts
and destroyed when the function ends.
def my_function():
x = 10 # local variable
print("Local x:", x)
my_function()
# print(x) # This would cause an error because x is not defined outside the function
Global Variable:- A global variable is a variable that is declared outside all
functions and is accessible throughout the program, including inside functions (if
not shadowed).
x = 20 # global variable
def my_function():
print("Accessing global x inside function:", x)
my_function()
print("Accessing global x outside function:", x)

In Python, seek() and tell() are used to manipulate and track the position of the file
pointer while reading or writing files.
tell() Function:- Purpose: Returns the current position of the file pointer in number
of bytes from the beginning. Syntax: file.tell()
with open("example.txt", "r") as f:
print("Current position:", f.tell()) # Usually 0 at the beginning
content = f.read(5)
print("After reading 5 characters, position:", f.tell())
2. seek() Function:- Purpose: Changes the position of the file pointer to a
specific location.Syntax: file.seek(offset, whence)
with open("example.txt", "r") as f:
f.seek(7) # Move file pointer to 8th byte (index starts from 0)
print("After seeking to position 7:", f.read(5))

13
readline() Function:- Purpose: Reads only one line at a time from a file. Returns:
A single string containing the next line, including the newline character (\n)
with open("sample.txt", "r") as f:
line1 = f.readline()
line2 = f.readline()
print("Line 1:", line1)
print("Line 2:", line2)
readlines() Function:- Purpose: Reads all the lines of a file and returns them as a
list of strings. Returns: A list where each element is a line from the file.
with open("sample.txt", "r") as f:
lines = f.readlines()
print("Lines as list:", lines)

Data hiding is a concept in object-oriented programming where the internal details


of an object's data are hidden from outside access. Only necessary data is exposed
through public methods (getters/setters). Advantages of Data Hiding:
Improved Security: Reduced Complexity:

A namespace in Python is a container that holds a collection of identifiers (names)


and their corresponding objects. It ensures that names are unique within a specific
context, preventing naming conflicts. Uses:- Avoiding Name Conflicts . Organizing
Code:

In Python, indentation is used to define the structure of the code. It determines the
grouping of statements and the hierarchy of blocks of code, such as loops, functions,
and conditionals. Unlike other programming languages, where braces {} are used to
define blocks, Python relies on indentation to create readable, clean code.
Key Roles:- Defines Code Blocks: Ensures Code Readability:

Data abstraction is a fundamental concept in object-oriented programming (OOP)


that focuses on hiding the complexity of data and exposing only the essential
features to the user. It allows the user to interact with objects in a simplified way
without needing to understand the internal workings or implementation details.
Key Points:
Hiding Implementation Details: Public Interface:

14
Decision making statements allow you to execute specific blocks of code based on
certain conditions. Python provides two common decision-making structures: if-else
and if-elif-else.
if-else Statement:- The if-else statement evaluates a condition and executes the
corresponding block of code based on whether the condition is True or False.
x = 10
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
2. if-elif-else Statement:- The if-elif-else statement allows checking multiple
conditions. If the first condition is False, it checks the next condition (elif) and so on.
If none of the conditions are True, the else block is executed.
x = 15
if x > 20:
print("x is greater than 20")
elif x > 10:
print("x is greater than 10 but less than or equal to 20")
else:
print("x is 10 or less")

matplotlib is a popular plotting library in Python used for creating static,


animated, and interactive visualizations. It is widely used for data visualization
and generating different types of plots and charts. Key Uses of matplotlib:
Plotting Graphs: Data Visualization: Customizing Plots: Exporting Graphics:
Class in Python: A class is a blueprint or template for creating objects. It defines
attributes and methods that describe the behavior of the objects.
Object in Python: An object is an instance of a class. It is created based on the
class and contains data (attributes) and methods (behaviors) defined in the class.

15
# Loop to print the pattern
num = 2 # Starting number
for i in range(1, 4): # for i in range(1, 5):
for j in range(i): # for j in range(1, i + 1):
print(num, end=" ") # print(j, end=" ")
num += 2 # Increment by 2 to get the next even number
print() # To move to the next line
2
468
10 12 14 16 18

16

You might also like