0% found this document useful (0 votes)
10 views

Python Study Material

This study material should serve as a comprehensive resource to delve deeply into Python.

Uploaded by

zain.bsba90
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views

Python Study Material

This study material should serve as a comprehensive resource to delve deeply into Python.

Uploaded by

zain.bsba90
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 14

-- Python Study Material

• Table of Contents

1. [Introduction to Python](•introduction-to-python)

2. [Basic Syntax and Operations](•basic-syntax-and-operations)

3. [Control Flow](•control-flow)

4. [Data Structures](•data-structures)

5. [Functions and Modules](•functions-and-modules)

6. [Object-Oriented Programming (OOP)](•object-oriented-programming-oop)

7. [File Handling](•file-handling)

8. [Error Handling and Exceptions](•error-handling-and-exceptions)

9. [Libraries and Frameworks](•libraries-and-frameworks)

10. [Advanced Topics](•advanced-topics)

11. [Real-World Applications](•real-world-applications)

12. [Resources and Practice](•resources-and-practice)

---

• 1. Introduction to Python

• Overview

- Python is a high-level, interpreted programming language known for its readability and simplicity.

- It's widely used for web development, data analysis, artificial intelligence, scientific computing, and
more.

• Key Features

- Easy-to-read syntax
- Extensive standard library

- Dynamically typed

- Supports multiple programming paradigms (procedural, object-oriented, functional)

• Installation

- Install Python from the official website [python.org](https://www.python.org/).

- Use package managers like `pip` to install additional libraries.

• Basic Usage

- Python can be run in interactive mode or by executing scripts.

- The Python Interactive Shell (REPL) allows for quick testing of code snippets.

• 2. Basic Syntax and Operations

• Variables and Data Types

- Variables are containers for storing data values.

- Common data types: `int`, `float`, `str`, `bool`, `list`, `tuple`, `dict`, `set`.

•python

• Examples

x = 10 • Integer

y = 3.14 • Float

name = "Alice" • String

is_valid = True • Boolean

• Basic Operations

- Arithmetic: `+`, `-`, `*`, `/`, `//` (floor division), `%` (modulus), `•` (exponentiation)

- Comparison: `==`, `!=`, `>`, `<`, `>=`, `<=`


- Logical: `and`, `or`, `not`

- Assignment: `=`, `+=`, `-=`, `*=`, `/=`

•python

• Examples

a=5

b=2

sum = a + b • 7

diff = a - b • 3

product = a * b • 10

quotient = a / b • 2.5

floor_div = a // b • 2

remainder = a % b • 1

power = a • b • 25

• Strings

- Strings can be manipulated using methods like `upper()`, `lower()`, `replace()`, `split()`, `join()`.

- Use slicing to access substrings: `str[start:end]`.

•python

• Examples

greeting = "Hello, World!"

print(greeting.upper()) • "HELLO, WORLD!"

print(greeting[0:5]) • "Hello"

• 3. Control Flow
• Conditional Statements

- Use `if`, `elif`, and `else` to control the flow based on conditions.

•python

• Example

x = 10

if x > 0:

print("Positive")

elif x < 0:

print("Negative")

else:

print("Zero")

• Loops

- `for` loops iterate over a sequence (list, tuple, dictionary, set, or string).

- `while` loops execute as long as a condition is true.

•python

• Example

for i in range(5):

print(i) • 0, 1, 2, 3, 4

n=5

while n > 0:

print(n)

n -= 1


• List Comprehensions

- A concise way to create lists.

•python

• Example

squares = [x•2 for x in range(10)]

• 4. Data Structures

• Lists

- Ordered, mutable collections of items.

- Methods: `append()`, `remove()`, `sort()`, `reverse()`, etc.

•python

• Example

fruits = ['apple', 'banana', 'cherry']

fruits.append('date')

• Tuples

- Ordered, immutable collections of items.

•python

• Example

point = (10, 20)


• Dictionaries

- Unordered, mutable collections of key-value pairs.

•python

• Example

student = {'name': 'Alice', 'age': 25}

• Sets

- Unordered collections of unique items.

•python

• Example

numbers = {1, 2, 3, 3, 4}

• 5. Functions and Modules

• Functions

- Blocks of code that perform a specific task and can be reused.

- Define using `def`, return values with `return`.

•python

• Example

def add(a, b):

return a + b

• Modules
- Files containing Python code (functions, classes, variables).

- Use `import` to include modules.

•python

• Example

import math

print(math.sqrt(16)) • 4.0

• 6. Object-Oriented Programming (OOP)

• Classes and Objects

- Define classes using `class`, create objects (instances) from classes.

•python

• Example

class Person:

def __init__(self, name, age):

self.name = name

self.age = age

p1 = Person("Alice", 30)

• Inheritance

- Derive new classes from existing ones.

•python

• Example
class Student(Person):

def __init__(self, name, age, student_id):

super().__init__(name, age)

self.student_id = student_id

• Encapsulation and Polymorphism

- Encapsulation hides the internal state of objects.

- Polymorphism allows different classes to be treated as instances of the same class through inheritance.

• 7. File Handling

• Reading and Writing Files

- Use `open()` to read/write files. Modes: `'r'` (read), `'w'` (write), `'a'` (append), `'b'` (binary).

•python

• Example

with open('example.txt', 'w') as file:

file.write("Hello, World!")

• 8. Error Handling and Exceptions

• Try-Except Blocks

- Handle errors using `try` and `except`.

•python

• Example

try:
result = 10 / 0

except ZeroDivisionError:

print("Cannot divide by zero!")

• Custom Exceptions

- Create user-defined exceptions by subclassing `Exception`.

•python

• Example

class CustomError(Exception):

pass

try:

raise CustomError("An error occurred")

except CustomError as e:

print(e)

• 9. Libraries and Frameworks

• Popular Libraries

- •NumPy•: Numerical computing

- •Pandas•: Data manipulation and analysis

- •Matplotlib•: Plotting and visualization

- •Requests•: HTTP requests

- •BeautifulSoup•: Web scraping

•python
• Example with NumPy

import numpy as np

arr = np.array([1, 2, 3, 4, 5])

print(arr * 2)

• Web Frameworks

- •Django•: High-level web framework

- •Flask•: Lightweight web framework

•python

• Example with Flask

from flask import Flask

app = Flask(__name__)

@app.route('/')

def hello_world():

return 'Hello, World!'

if __name__ == '__main__':

app.run()

• 10. Advanced Topics

• Decorators

- Functions that modify the behavior of other functions or methods.

•python
• Example

def my_decorator(func):

def wrapper():

print("Something is happening before the function is called.")

func()

print("Something is happening after the function is called.")

return wrapper

@my_decorator

def say_hello():

print("Hello!")

say_hello()

• Generators

- Functions that return an iterator using `yield`.

•python

• Example

def generate_numbers():

for i in range(5):

yield i

for num in generate_numbers():

print(num)

• Context Managers
- Manage resources with `with` statements.

•python

• Example

with open('example.txt', 'r') as file:

content = file.read()

• 11. Real-World Applications

• Data Analysis

- Using `Pandas` for data manipulation.

•python

• Example

import pandas as pd

data = pd.read_csv('data.csv')

print(data.head())

• Web Development

- Building web applications with `Flask` or `Django`.

• Automation

- Automating tasks using scripts.

•python

• Example

import os
os.system('echo "Automation script running"')

• Machine Learning

- Applying models using `

scikit-learn`.

•python

• Example

from sklearn.linear_model import LinearRegression

model = LinearRegression()

• Assume X and y are defined

model.fit(X, y)

• 12. Resources and Practice

• Online Tutorials

- •Official Python Documentation•: [python.org](https://docs.python.org/3/)

- •Codecademy Python Course•: [Codecademy](https://www.codecademy.com/learn/learn-python-3)

- •W3Schools Python Tutorial•: [W3Schools](https://www.w3schools.com/python/)

• Books

- "Automate the Boring Stuff with Python" by Al Sweigart

- "Python Crash Course" by Eric Matthes

- "Fluent Python" by Luciano Ramalho

• Practice Platforms
- •LeetCode•: [LeetCode Python](https://leetcode.com/problemset/all/?
difficulty=Easy&difficulty=Medium&difficulty=Hard&tags=python)

- •HackerRank•: [HackerRank Python](https://www.hackerrank.com/domains/tutorials/10-days-of-


python)

- •CodeWars•: [CodeWars Python](https://www.codewars.com/?language=python)

---

You might also like