Python Important Topic
Python Important Topic
ChatGPT
Features of Python
Python is a popular programming language known for its simplicity and readability. Here are
some key features:
1. Easy to Read and Write: Python has a clear and simple syntax,
making it easy to learn and understand.
2. Interpreted Language: Python code is executed line-by-line, which
makes debugging easier.
3. High-Level Language: Python abstracts away many complex details
of the computer, allowing you to focus on programming concepts.
4. Object-Oriented: Python supports object-oriented programming,
which helps organize code into reusable and logical pieces.
5. Dynamic Typing: You don't need to declare the data type of a variable
when you create it. Python figures it out at runtime.
6. Extensive Libraries: Python has a vast standard library and
numerous third-party modules available, enabling you to accomplish a
wide range of tasks.
7. Cross-Platform: Python can run on various operating systems,
including Windows, macOS, and Linux, without needing any changes.
Data Types
Python supports several built-in data types:
1. Numbers:
o int: Whole numbers, e.g., 10, -5
o float: Decimal numbers, e.g., 3.14, -0.001
o complex: Complex numbers, e.g., 1+2j
2. Strings: Sequences of characters, e.g., "Hello, World!"
3. Booleans: Represent truth values, e.g., True or False
4. Lists: Ordered, mutable collections of items, e.g., [1, 2, 3, 4]
5. Tuples: Ordered, immutable collections of items, e.g., (1, 2, 3, 4)
6. Dictionaries: Unordered collections of key-value pairs, e.g., {'name': 'Alice',
'age': 25}
7. Sets: Unordered collections of unique items, e.g., {1, 2, 3, 4}
8. NoneType: Represents the absence of a value, e.g., None
Indentation and Comments
Indentation
Python uses indentation to define the structure of the code. Blocks of code are defined by their
indentation level.
python
Copy code
if True:
print("This is inside the if block")
if False:
print("This won't be printed")
print("This is outside the if block")
Comments
Comments are used to explain the code and are ignored by the interpreter.
Single-line comments: Start with #
python
Copy code
# This is a single-line comment
print("Hello, World!") # This is also a comment
Multi-line comments: Enclosed in triple quotes (''' or """)
python
Copy code
"""
This is a multi-line comment
that spans multiple lines
"""
print("Hello, World!")
Type Conversion
Type conversion refers to converting one data type to another. Python provides several built-in
functions for this purpose:
int(): Converts a value to an integer
python
Copy code
x = int(3.14) # x will be 3
float(): Converts a value to a float
python
Copy code
y = float("3.14") # y will be 3.14
str(): Converts a value to a string
python
Copy code
z = str(10) # z will be "10"
list(): Converts a value to a list
python
Copy code
a = list("hello") # a will be ['h', 'e', 'l', 'l', 'o']
y = "Hello"
print(type(y)) # Output: <class 'str'>
z = [1, 2, 3]
print(type(z)) # Output: <class 'list'>
Membership Operator
Membership operators are used to test if a value is a member of a sequence (like a string, list, or
tuple).
in: Returns True if the value is found in the sequence
python
Copy code
fruits = ["apple", "banana", "cherry"]
print("banana" in fruits) # Output: True
print("grape" in fruits) # Output: False
not in: Returns True if the value is not found in the sequence
python
Copy code
vegetables = ["carrot", "potato", "cabbage"]
print("spinach" not in vegetables) # Output: True
print("potato" not in vegetables) # Output: False
If, if-else, if-elif-else loop While loop range() function Continue and break
statements String - basic operations, slicing & joining, string methods
ChatGPT
Control Flow in Python
If, If-Else, If-Elif-Else Statements
If Statement
An if statement evaluates a condition and executes the block of code if the condition is True.
python
Copy code
x = 10
if x > 5:
print("x is greater than 5")
If-Else Statement
An if-else statement provides an alternative block of code to execute when the condition is
False.
python
Copy code
x = 3
if x > 5:
print("x is greater than 5")
else:
print("x is not greater than 5")
If-Elif-Else Statement
An if-elif-else statement allows for multiple conditions to be checked in sequence. Once a
True condition is found, its block of code is executed, and the rest are ignored.
python
Copy code
x = 7
if x > 10:
print("x is greater than 10")
elif x > 5:
print("x is greater than 5 but less than or equal to 10")
else:
print("x is 5 or less")
While Loop
A while loop repeatedly executes a block of code as long as the given condition is True.
python
Copy code
count = 0
while count < 5:
print(count)
count += 1
range() Function
The range() function generates a sequence of numbers. It is commonly used with loops.
range(stop): Generates numbers from 0 to stop-1.
python
Copy code
for i in range(5):
print(i) # Outputs 0, 1, 2, 3, 4
range(start, stop): Generates numbers from start to stop-1.
python
Copy code
for i in range(1, 5):
print(i) # Outputs 1, 2, 3, 4
range(start, stop, step): Generates numbers from start to stop-1, incrementing by step.
python
Copy code
for i in range(1, 10, 2):
print(i) # Outputs 1, 3, 5, 7, 9
Break Statement
The break statement exits the loop entirely, regardless of the condition.
python
Copy code
for i in range(5):
if i == 2:
break
print(i) # Outputs 0, 1 (stops at 2)
Strings
Strings are sequences of characters enclosed in single, double, or triple quotes.
Basic Operations
Concatenation: Combining strings using +.
python
Copy code
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2 # result is "Hello World"
Repetition: Repeating strings using *.
python
Copy code
result = "Hello" * 3 # result is "HelloHelloHello"
Joining
Joining combines a list of strings into a single string, with a specified separator.
python
Copy code
words = ["Hello", "World"]
joined_string = " ".join(words) # "Hello World"
String Methods
Python provides several built-in string methods. Here are a few commonly used ones:
upper(): Converts all characters to uppercase.
python
Copy code
print("hello".upper()) # Outputs "HELLO"
lower(): Converts all characters to lowercase.
python
Copy code
print("HELLO".lower()) # Outputs "hello"
strip(): Removes leading and trailing whitespace.
python
Copy code
print(" hello ".strip()) # Outputs "hello"
replace(old, new): Replaces occurrences of a substring with another substring.
python
Copy code
print("hello world".replace("world", "there")) # Outputs "hello there"
split(delimiter): Splits the string into a list of substrings based on the specified delimiter.
python
Copy code
print("hello world".split()) # Outputs ['hello', 'world']
find(substring): Returns the index of the first occurrence of the substring, or -1 if not
found.
python
Copy code
print("hello".find("e")) # Outputs 1
Lists, Tuples Dictionaries, Sets Function definition & calling the function
Return statement and void function Parameters and arguments Lifetime of
variables Lambda function
ChatGPT
Basic Operations
Creating a List:
python
Copy code
my_list = [1, 2, 3, 4, 5]
Accessing Elements:
python
Copy code
print(my_list[0]) # Outputs: 1
Modifying Elements:
python
Copy code
my_list[0] = 10
print(my_list) # Outputs: [10, 2, 3, 4, 5]
Adding Elements:
python
Copy code
my_list.append(6)
print(my_list) # Outputs: [10, 2, 3, 4, 5, 6]
Removing Elements:
python
Copy code
my_list.remove(2)
print(my_list) # Outputs: [10, 3, 4, 5, 6]
Tuples
Tuples are ordered, immutable collections of items. They are defined using parentheses ().
Basic Operations
Creating a Tuple:
python
Copy code
my_tuple = (1, 2, 3, 4, 5)
Accessing Elements:
python
Copy code
print(my_tuple[0]) # Outputs: 1
Immutability:
python
Copy code
my_tuple[0] = 10 # This will raise an error
Dictionaries
Dictionaries are unordered collections of key-value pairs. They are defined using curly braces
{}.
Basic Operations
Creating a Dictionary:
python
Copy code
my_dict = {'name': 'Alice', 'age': 25}
Accessing Values:
python
Copy code
print(my_dict['name']) # Outputs: Alice
Modifying Values:
python
Copy code
my_dict['age'] = 26
print(my_dict) # Outputs: {'name': 'Alice', 'age': 26}
Adding Key-Value Pairs:
python
Copy code
my_dict['city'] = 'New York'
print(my_dict) # Outputs: {'name': 'Alice', 'age': 26, 'city': 'New
York'}
Removing Key-Value Pairs:
python
Copy code
del my_dict['age']
print(my_dict) # Outputs: {'name': 'Alice', 'city': 'New York'}
Sets
Sets are unordered collections of unique items. They are defined using curly braces {}.
Basic Operations
Creating a Set:
python
Copy code
my_set = {1, 2, 3, 4, 5}
Adding Elements:
python
Copy code
my_set.add(6)
print(my_set) # Outputs: {1, 2, 3, 4, 5, 6}
Removing Elements:
python
Copy code
my_set.remove(2)
print(my_set) # Outputs: {1, 3, 4, 5, 6}
Unique Elements:
python
Copy code
my_set = {1, 2, 2, 3, 4}
print(my_set) # Outputs: {1, 2, 3, 4}
Functions in Python
Functions are blocks of reusable code that perform a specific task. They help in organizing code
into logical sections and enable code reuse.
Calling a Function
python
Copy code
greet("Alice") # Outputs: Hello, Alice!
result = add(3, 4)
print(result) # Outputs: 7
Void Function
A function that does not return a value is known as a void function. It implicitly returns None.
python
Copy code
def greet(name):
print(f"Hello, {name}!")
result = greet("Alice")
print(result) # Outputs: Hello, Alice! followed by None
Arguments
Arguments are the actual values passed to the function when calling it.
python
Copy code
greet("Alice") # "Alice" is an argument
Lifetime of Variables
The lifetime of a variable is the period during which the variable exists in memory. In Python:
Local Variables: Defined inside a function, they exist only within the
function's scope.
Global Variables: Defined outside any function, they exist for the
duration of the program.
python
Copy code
def my_function():
local_var = 10 # Local variable
print(local_var)
Lambda Function
Lambda functions are small, anonymous functions defined using the lambda keyword. They can
have any number of arguments but only one expression.
Syntax
python
Copy code
lambda arguments: expression
Example
python
Copy code
add = lambda x, y: x + y
print(add(3, 4)) # Outputs: 7
Lambda functions are often used for short, simple functions that are not going to be reused, such
as in higher-order functions like map(), filter(), and sorted().
python
Copy code
# Using lambda with sorted()
my_list = [(1, 'one'), (2, 'two'), (3, 'three')]
sorted_list = sorted(my_list, key=lambda x: x[1])
print(sorted_list) # Outputs: [(1, 'one'), (3, 'three'), (2, 'two')]
In summary, understanding data structures like lists, tuples, dictionaries, and sets, as well as
functions in Python, is fundamental for efficient programming. Functions help organize code and
enable reuse, while lambda functions provide a concise way to define small functions. The
concept of variable scope and lifetime is crucial for managing data and avoiding errors in code.
4o
ChatGPT
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
Object
An object is an instance of a class. When you create an object, you instantiate the class.
python
Copy code
person1 = Person("Alice", 30)
person1.greet() # Outputs: Hello, my name is Alice and I am 30 years old.
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
Methods of a Class
Methods are functions defined inside a class that describe the behaviors of the objects.
Example
python
Copy code
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
print(f"Hello, my name is {self.name} and I am {self.age} years old.")
def __del__(self):
print(f"Person object with name {self.name} is being deleted")
Example
python
Copy code
class Person:
def __init__(self, name, age):
self.__name = name # Private variable
self.__age = age # Private variable
def public_method(self):
self.__greet()
Inheritance
Inheritance allows a class to inherit attributes and methods from another class.
Example
python
Copy code
class Animal:
def __init__(self, name):
self.name = name
def speak(self):
raise NotImplementedError("Subclasses must implement this method")
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
Types of Inheritance
1. Single Inheritance: A class inherits from one superclass.
python
Copy code
class Dog(Animal):
...
2. Multiple Inheritance: A class inherits from more than one superclass.
python
Copy code
class FlyingFish(Fish, Bird):
...
3. Multilevel Inheritance: A class inherits from a class, which in turn inherits from another
class.
python
Copy code
class Puppy(Dog):
...
4. Hierarchical Inheritance: Multiple classes inherit from one superclass.
python
Copy code
class Cat(Animal):
...
class Dog(Animal):
...
5. Hybrid Inheritance: A combination of two or more types of inheritance.
Common Operations
Matching: re.match() checks for a match at the beginning of the string.
python
Copy code
import re
result = re.match(r'hello', 'hello world')
if result:
print("Match found")
else:
print("No match")
Searching: re.search() searches the string for a match.
python
Copy code
import re
result = re.search(r'world', 'hello world')
if result:
print("Match found")
else:
print("No match")
Find All: re.findall() returns a list of all matches.
python
Copy code
import re
result = re.findall(r'o', 'hello world')
print(result) # Outputs: ['o', 'o']
Substitution: re.sub() replaces matches with a string.
python
Copy code
import re
result = re.sub(r'world', 'Python', 'hello world')
print(result) # Outputs: hello Python
Example
python
Copy code
import re