Python

 


Introduction


What is Python?

Python is a popular, high-level programming language known for its:


Simplicity (easy to read and write)


Versatility (used in web development, data science, AI, automation, etc.)


Large community (many libraries and resources)



It was created by Guido van Rossum and released in 1991.


---


 Why Learn Python?


Easy to learn for beginners


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


Huge ecosystem of libraries (e.g., NumPy, pandas, Flask, Django, TensorFlow)


Great for automation and scripting


Widely used in industries like data science, web dev, and AI


---


 Basic Concepts


1. Hello, World!


print("Hello, world!")


2. Variables


name = "Alice"

age = 25

height = 5.7


3. Data Types


int – integers (e.g., 5)


float – decimal numbers (e.g., 3.14)


str – strings (e.g., "Hello")


bool – booleans (True or False)



4. Conditional Statements


if age >= 18:

    print("You're an adult.")

else:

    print("You're a minor.")


5. Loops


for loop:


for i in range(5):

    print(i)


while loop:


count = 0

while count < 5:

    print(count)

    count += 1


6. Functions


def greet(name):

    print("Hello, " + name)


greet("Alice")



---


 Example Program


def add(a, b):

    return a + b


x = 10

y = 5

result = add(x, y)

print("The result is:", result)


---


Python Output 

Basic Output in Python

The primary way to display output in Python is using the print() function.

🔹 Example 1: Hello World

print("Hello, World!")

🔹 Output:

Hello, World!


---

Printing Variables

name = "Alice"
print("Hello,", name)

🔹 Output:

Hello, Alice


---

Using f-strings (Formatted Strings) — Python 3.6+

name = "Alice"
print(f"Hello, {name}!")

🔹 Output:

Hello, Alice!


---

Concatenating Strings

a = "Hello"
b = "World"
print(a + " " + b)

🔹 Output:

Hello World


---

Printing Numbers and Math

print(10 + 5)

🔹 Output:

15


---

 Multi-line Output

print("Line 1\nLine 2\nLine 3")

🔹 Output:

Line 1
Line 2
Line 3


---

 Printing Without a Newline

print("Hello", end=" ")
print("World")

🔹 Output:

Hello World


---


Data Type 

Great! Let’s explore Python Data Types — a fundamental concept that you need to understand before diving deeper into Python programming.


---

 What is a Data Type?

A data type tells Python what kind of value a variable holds — like whether it’s a number, text, list, etc.


---

Built-in Data Types in Python

Here are the most commonly used ones:

Data Type Example

Text str "Hello, world"

Numeric int, float, complex 10, 3.14, 3+2j

Sequence list, tuple, range [1, 2, 3], (4, 5), range(10)

Mapping dict {"name": "Alice", "age": 25}
Set set, frozenset {1, 2, 3}, frozenset([1, 2])

Boolean bool True, False

Binary bytes, bytearray, memoryview b"abc", bytearray(5)

None Type NoneType None


---

 Examples

1. String (str)

message = "Hello"
print(type(message))  # <class 'str'>

2. Integer (int)

age = 25
print(type(age))  # <class 'int'>

3. Float (float)

pi = 3.14
print(type(pi))  # <class 'float'>

4. Boolean (bool)

is_valid = True
print(type(is_valid))  # <class 'bool'>

5. List

fruits = ["apple", "banana", "cherry"]
print(type(fruits))  # <class 'list'>

6. Tuple

coordinates = (10, 20)
print(type(coordinates))  # <class 'tuple'>

7. Dictionary

person = {"name": "Alice", "age": 30}
print(type(person))  # <class 'dict'>

8. Set

unique_numbers = {1, 2, 3}
print(type(unique_numbers))  # <class 'set'>

9. None

result = None
print(type(result))  # <class 'NoneType'>


---

 Type Conversion

You can change types using functions like:

int("5")        # Converts string to integer
str(123)        # Converts number to string
list("abc")     # ['a', 'b', 'c']


---

Variables 

Absolutely! Let's go over Python variables — a core concept for storing and working with data in Python.


---

 What is a Variable?

A variable is a name that stores data or a reference to a value. Think of it like a container that holds information your program can use or modify.


---

 Creating Variables in Python

x = 10
name = "Alice"
is_happy = True

In Python:

You don’t need to declare the type of a variable — Python figures it out automatically.

The = symbol is used to assign a value.



---

 Variable Naming Rules

1. Names can include letters, numbers, and underscores.


2. Must start with a letter or underscore (not a number).


3. Case-sensitive (age and Age are different).


4. Should be descriptive (e.g., use student_name instead of sn).



✅ Valid names:

age = 25
_student = "John"
user2 = "Jane"

❌ Invalid names:

2name = "Tom"     # Starts with a number
user-name = "Ali" # Hyphens are not allowed


---

Changing Values

Variables can be updated at any time:

x = 5
x = 10  # Now x is 10


---

 Multiple Assignments

You can assign multiple variables in one line:

a, b, c = 1, 2, 3

Or give the same value to multiple variables:

x = y = z = 0


---

 Example

name = "Sarah"
age = 21
is_student = True

print(name)
print(age)
print(is_student)

Output:

Sarah
21
True


---

Dynamic Typing

Python is dynamically typed, meaning a variable's type can change:

x = 10       # x is an int
x = "Hello"  # Now x is a str


---

 Check a Variable's Type

Use type():

a = 42
print(type(a))  # <class 'int'>


---

Comments 

Great! Let's look at Python comments, which are essential for writing clean and understandable code.


---

 What are Comments?

Comments are notes in your code that Python ignores when running the program. They're used to:

Explain what the code does

Make your code easier to read

Help others (or future you) understand your thought process



---

 Types of Comments in Python

1. Single-line Comments

Use the # symbol:

# This is a single-line comment
name = "Alice"  # This is an inline comment

Everything after # on that line is ignored by Python.


---

2. Multi-line Comments (Workaround)

Python doesn't have a dedicated multi-line comment syntax like some other languages (e.g., /* */ in C). But you can use triple quotes ''' or """ as a workaround:

'''
This is a multi-line comment
that spans multiple lines
'''
print("Hello")


 Example

# This program adds two numbers

a = 5  # First number
b = 3  # Second number

# Add the numbers
sum = a + b

# Display the result
print("Sum is:", sum)


---

 Best Practices

Use comments to explain why, not what (if the code is already obvious).

Don’t over-comment — focus on clarity.

Keep them up to date when code changes.



---

Keywords 


 What Are Keywords in Python?

Keywords are reserved words in Python that have special meaning. You cannot use them as variable names, function names, or identifiers.

They are used to define the syntax and structure of Python programs.


---

List of Python Keywords (Python 3.10+)

Here's a list of common Python keywords:

Keyword   Description

False         Boolean value false
True           Boolean value true
None.        Represents the absence of a value
and           Logical AND
or              Logical OR
not.          Logical NOT
if                Conditional statement
elif.            Else if condition
else.          Else condition
while.        While loop
for            For loop
break.      Exit a loop
continue. Skip current iteration of loop
pass.        Do nothing (placeholder)
def             Define a function
return.      Return a value from a function
class         Define a class
try              Try block for error handling
except      Catch an exception
finally       Code that always runs after.  
                  try-except
raise.        Raise an exception
import     Import a module
from       Import specific parts from a module
as.          Rename a module or alias
global.      Declare a global variable
nonlocal   Declare a non-local variable
in.              Check for membership
is.              Identity comparison
lambda.    Create an anonymous function
assert.      Debugging tool
del            Delete an object or variable
with        Context manager (e.g., file handling)
yield        Pause a generator function
async.    Define asynchronous functions
await.    Wait for an async operation



---

Example in Code

def greet(name):
    if name:
        return "Hello, " + name
    else:
        return "Hello, stranger"

print(greet("Alice"))

In this code:

def, if, else, return, and print are keywords.



--


❌ Keyword as Variable Name (Not Allowed)

if = 5  # ❌ Invalid syntax — 'if' is a keyword


---


Operators 

In Python, operators are special symbols or keywords used to perform operations on variables and values. Here's a breakdown of the main types of operators in Python:


---

🔹 1. Arithmetic Operators

Used to perform basic mathematical operations.

Operator Description Example

+ Addition a + b
- Subtraction a - b
* Multiplication a * b
/ Division a / b
// Floor Division a // b
% Modulus a % b
** Exponentiation a ** b



---

🔹 2. Comparison (Relational) Operators

Used to compare two values.

Operator Description Example

== Equal to a == b
!= Not equal to a != b
> Greater than a > b
< Less than a < b
>= Greater or equal a >= b
<= Less or equal a <= b



---

🔹 3. Assignment Operators

Used to assign values to variables.

Operator Description Example

= Assign a = 5
+= Add and assign a += 2
-= Subtract and assign a -= 3
*= Multiply and assign a *= 4
/= Divide and assign a /= 2
//= Floor divide assign a //= 2
%= Modulus assign a %= 3
**= Power assign a **= 2



---

🔹 4. Logical Operators

Used to combine conditional statements.

Operator Description Example

and Logical AND a > 5 and b < 10
or Logical OR a > 5 or b < 10
not Logical NOT not a > 5



---

🔹 5. Bitwise Operators

Operate on bits (binary representations).

Operator Description Example

& AND a & b
` ` OR
^ XOR a ^ b
~ NOT ~a
<< Left Shift a << 2
>> Right Shift a >> 2



---



if else 

In Python, the if...else statement is used for conditional execution — that is, to run different blocks of code depending on whether a condition is True or False.


---

🔹 Basic if...else Syntax

if condition:
    # Code block if condition is True
else:
    # Code block if condition is False

 Example:

age = 18

if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

Output:

You are an adult.


---

🔹 if...elif...else (for multiple conditions)

if condition1:
    # Code if condition1 is True
elif condition2:
    # Code if condition2 is True
else:
    # Code if none of the above is True

Example:

marks = 75

if marks >= 90:
    print("Grade: A")
elif marks >= 70:
    print("Grade: B")
elif marks >= 50:
    print("Grade: C")
else:
    print("Grade: F")

Output:

Grade: B


---

🔹 One-line if (Ternary Operator)

You can write simple if...else statements in one line:

result = "Even" if number % 2 == 0 else "Odd"

 Example:

x = 10
print("Even" if x % 2 == 0 else "Odd")


---

🔹 Nested if Statements

You can also nest if statements inside each other:

num = 15

if num > 0:
    if num % 2 == 0:
        print("Positive even number")
    else:
        print("Positive odd number")
else:
    print("Not a positive number")


---


Loops 

In Python, loops are used to execute a block of code repeatedly. The two main types of loops are:


---

 1. for Loop

Used to iterate over a sequence (like a list, string, tuple, dictionary, or range).

🔹 Syntax:

for variable in sequence:
    # Code to run each time

Example 1: Looping over a list

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

for fruit in fruits:
    print(fruit)

Output:

apple
banana
cherry

 Example 2: Using range()

for i in range(5):
    print(i)

Output:

0
1
2
3
4


---

 2. while Loop

Repeats as long as a condition is True.

🔹 Syntax:

while condition:
    # Code to run while condition is True

 Example:

count = 0

while count < 5:
    print(count)
    count += 1

Output:

0
1
2
3
4


---

🔹 Loop Control Statements

Statement Purpose

break Exit the loop completely
continue Skip the current iteration and go to the next one
pass Do nothing (placeholder)


 Example of break:

for i in range(10):
    if i == 5:
        break
    print(i)

Output:

0
1
2
3
4

 Example of continue:

for i in range(5):
    if i == 2:
        continue
    print(i)

Output:

0
1
3
4


---

for...else and while...else

Python supports else with loops, which runs only if the loop wasn't terminated by break.

 Example:

for i in range(3):
    print(i)
else:
    print("Loop finished without break")


---


Array 

In Python, the term "array" can refer to multiple things, but it's important to know that:

>  Python doesn't have a built-in array data type like some other languages. Instead, we use:

Lists (for general-purpose arrays)

The array module (for efficient, fixed-type arrays)

Or NumPy arrays (for advanced numerical operations)





---

1. Python List (Most Common "Array")

Lists are dynamic and can store different types of items.

🔹 Creating a list:

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

🔹 Accessing elements:

print(fruits[0])  # Output: apple

🔹 Modifying elements:

fruits[1] = "mango"

🔹 Adding elements:

fruits.append("orange")      # Add at the end
fruits.insert(1, "kiwi")     # Insert at index 1

🔹 Removing elements:

fruits.remove("apple")
fruits.pop()       # Removes last item

🔹 Looping through a list:

for fruit in fruits:
    print(fruit)


---

2. array Module (Fixed Data Type)

For efficiency when working with numbers of the same type.

🔹 Import and create:

import array

nums = array.array('i', [1, 2, 3, 4])  # 'i' means integer

🔹 Common methods:

nums.append(5)
nums.remove(2)
print(nums[0])  # Access first element


---

 3. NumPy Arrays (For Scientific/Numeric Work)

Much more powerful, used in data science and machine learning.

import numpy as np

arr = np.array([1, 2, 3, 4])
print(arr[1])  # Output: 2

> 🔸 NumPy arrays support vectorized operations (faster and more powerful than lists).




---

Summary Table:

Type Use Case Fixed Type Requires Import

List General-purpose array No
array.array Memory-efficient, same-type elements Yes (array)
NumPy array Scientific computing, large datasets Yes (numpy)



---


Function 

In Python, functions are reusable blocks of code that perform a specific task. They help keep code organized, avoid repetition, and make it easier to debug.


---

1. Defining a Function

🔹 Syntax:

def function_name(parameters):
    # code block
    return result


---

 Example 1: A simple function with no parameters

def greet():
    print("Hello, Python!")

greet()  # Call the function


---

 Example 2: Function with parameters

def greet(name):
    print("Hello,", name)

greet("Alice")


---

 Example 3: Function with return value

def add(a, b):
    return a + b

result = add(3, 5)
print(result)  # Output: 8


---

2. Default Parameters

You can provide default values for parameters.

def greet(name="Guest"):
    print("Hello,", name)

greet()           # Hello, Guest
greet("Charlie")  # Hello, Charlie


---

3. Keyword Arguments

You can pass arguments by name.

def introduce(name, age):
    print(f"My name is {name}, and I'm {age} years old.")

introduce(age=25, name="David")


---

4. Variable Number of Arguments

🔹 *args for many positional arguments

def total(*numbers):
    return sum(numbers)

print(total(1, 2, 3))  # Output: 6

🔹 **kwargs for many keyword arguments

def show_info(**info):
    for key, value in info.items():
        print(key, ":", value)

show_info(name="Sam", age=30)


---

 5. Lambda (Anonymous) Functions

A quick way to write small functions.

square = lambda x: x ** 2
print(square(5))  # Output: 25


---



Class and Object 

In Python, classes and objects are the foundation of Object-Oriented Programming (OOP). A class is like a blueprint, and an object is an actual instance of that blueprint.


---

1. Class and Object Basics

🔹 Defining a Class

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.")

🔹 Creating an Object (Instance)

p1 = Person("Alice", 30)
p1.greet()  # Output: Hello, my name is Alice and I am 30 years old.


---

 2. Key Concepts

Concept Description

class Used to define a new user-defined type
object An instance of a class
__init__() Constructor method — called automatically when a new object is created
self Refers to the current instance of the class
Method A function defined inside a class
Attribute A variable that belongs to an object



---

 3. Adding More Methods

class Circle:
    def __init__(self, radius):
        self.radius = radius

    def area(self):
        return 3.14 * self.radius ** 2

    def perimeter(self):
        return 2 * 3.14 * self.radius

c = Circle(5)
print("Area:", c.area())
print("Perimeter:", c.perimeter())


---

 4. Modifying Object Attributes

p1 = Person("Bob", 25)
p1.age = 26
print(p1.age)  # Output: 26


---

5. Deleting Attributes or Objects

del p1.age    # Deletes the 'age' attribute
del p1        # Deletes the object itself


---

 6. Class vs Instance Attributes

class Dog:
    species = "Canine"  # Class attribute (shared by all objects)

    def __init__(self, name):
        self.name = name  # Instance attribute (unique to each object)

d1 = Dog("Max")
d2 = Dog("Bella")

print(d1.species)  # Output: Canine
print(d1.name)     # Output: Max


---

7. Inheritance (Basic)

class Animal:
    def speak(self):
        print("Animal speaks")

class Dog(Animal):
    def bark(self):
        print("Woof!")

d = Dog()
d.speak()  # Inherited method
d.bark()   # Dog's own method


---

Summary:

Term Example

Class class Person:
Object p = Person("Tom", 25)
Constructor def __init__(self):
Method def greet(self):
Attribute self.name = name


Comments