Python For Beginner

By admin , 4 June, 2026

๐Ÿ Python For Beginners

What is Python?

Python is a high-level, interpreted programming language known for its simplicity and readability. It is widely used in web development, data analysis, machine learning, automation, and more.

Why Learn Python?

  • Beginner-friendly syntax
  • Extensive libraries and frameworks
  • Strong community support
  • Versatile for various applications

Setting Up Python

On Windows

  1. Visit python.org and download the Windows installer.
  2. Run the installer and check "Add Python to PATH".
  3. Choose Customize Installation for pip, IDLE, and dev tools.
  4. Verify the installation:
python --version
pip --version

On Linux (Debian/Ubuntu)

sudo apt update && sudo apt upgrade -y
sudo apt install python3 python3-pip -y

# Verify
python3 --version
pip3 --version

On Linux (Red Hat/CentOS)

sudo yum install python3 python3-pip -y

Recommended Editors

  • VS Code โ€” Download from code.visualstudio.com. Install the Python Extension.
  • PyCharm โ€” Download from jetbrains.com/pycharm. Free Community Edition available.
  • Jupyter Notebook โ€” Install with pip install notebook, launch with jupyter notebook.

Virtual Environments

Windows:

python -m venv myenv
myenv\Scripts\activate
deactivate

Linux:

python3 -m venv myenv
source myenv/bin/activate
deactivate

Install Essential Libraries

pip install numpy pandas matplotlib
python -m pip install --upgrade pip

Basic Syntax

Hello World

print("Hello, World!")

Comments

# Single-line comment
print("Hello, World!")  # Inline comment

# Multi-line using # symbols
# This is a comment
# written in more than one line

"""
Multi-line using triple quotes.
Python ignores string literals not assigned to a variable.
"""
print("Hello, World!")

1. Operators

Arithmetic Operators

OperatorDescription
+Addition
-Subtraction
*Multiplication
/Division
%Modulus (remainder)
//Floor division
**Exponentiation
a = 10
b = 5
print(a + b)  # Output: 15
print(a - b)  # Output: 5

Comparison Operators

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

Logical Operators

OperatorDescription
andReturns True if both conditions are true
orReturns True if at least one condition is true
notReverses the result

2. Variables and Data Types

Variables store data. Data types tell Python what kind of data you are storing.

TypeExampleDescription
Integer5Whole numbers
Float3.14Numbers with decimal points
String"Alice"Text
BooleanTrueTrue or False values
x         = 5        # Integer
y         = 3.14     # Float
name      = "Alice"  # String
is_active = True     # Boolean

3. Lists

A list is a collection of items. Each item can be accessed by its index (starting at 0). Lists are flexible โ€” you can change, add, or remove items.

fruits = ["apple", "banana", "cherry"]
print(fruits[0])        # Output: apple
fruits.append("orange") # Adds to end

Advanced List Operations

# Slicing
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4])  # Output: [2, 3, 4]

# List Comprehension
squares = [x**2 for x in range(5)]
print(squares)       # Output: [0, 1, 4, 9, 16]

# Sorting and Reversing
numbers = [5, 2, 9, 1]
numbers.sort()       # [1, 2, 5, 9]
numbers.reverse()    # [9, 5, 2, 1]

4. Tuples

A tuple is like a list but immutable โ€” once created, you cannot change, add, or remove elements.

my_tuple = (1, 2, 3, "apple", True)
print(my_tuple)  # Output: (1, 2, 3, 'apple', True)

# my_tuple[1] = 10  # This will raise an error!

# Tuple with one element needs a trailing comma
single_tuple = (5,)  # Correct - this is a tuple
not_a_tuple  = (5)   # Wrong - this is just an integer

5. Dictionaries

A dictionary stores key-value pairs. Use the key to access the corresponding value.

person = {"name": "Alice", "age": 25}
print(person["name"])  # Output: Alice

6. Conditional Statements

Conditional statements let you run different code depending on whether a condition is true or false.

x = 10
if x > 5:
    print("x is greater than 5")
else:
    print("x is less than or equal to 5")

7. Loops

For Loop

Use when you know how many times to repeat.

for i in range(5):
    print(i)  # Output: 0, 1, 2, 3, 4

While Loop

Use when you want to repeat until a condition is met.

count = 0
while count < 5:
    print(count)
    count += 1  # Output: 0, 1, 2, 3, 4

8. Functions

A function is a reusable block of code. Functions help keep code organized and efficient.

def greet(name):
    return "Hello, " + name

print(greet("Alice"))  # Output: Hello, Alice

def square(x):
    return x * x

print(square(4))  # Output: 16

9. Classes and Objects

A class is a blueprint for creating objects. An object is an instance of a class.

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age  = age

    def greet(self):
        return f"Hello, my name is {self.name} and I am {self.age} years old."

person1 = Person("Alice", 25)
print(person1.greet())

10. Importing Libraries

Python has many built-in libraries (modules). Import them to use their functionality.

import math
print(math.sqrt(16))  # Output: 4.0

11. Fibonacci Series

def fib(n):
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a + b
    print()

fib(1000)
# Output: 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987

Fibonacci in the Stock Market

Fibonacci retracement levels are used in trading to identify potential support and resistance levels.

def fib(n):
    a, b = 0, 1
    sequence = []
    while a < n:
        sequence.append(a)
        a, b = b, a + b
    return sequence

max_price = 1000
retracement_levels = fib(max_price)
print("Fibonacci retracement levels:", retracement_levels)
# Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987]

When to Buy & Sell?

  • Buy: When the price retraces to 61.8%, 50%, or 38.2% and bounces up.
  • Sell: When the price rises to 38.2%, 50%, or 61.8% and struggles to go higher.

Key levels: 38.2%, 50%, 61.8%, 78.6%

These are calculated by dividing each number in the sequence by the number two places ahead. For example: 55 รท 144 โ‰ˆ 38.2%

Example Trading Strategy

  1. Stock peaks at โ‚น1000
  2. Drops to โ‚น618 (61.8%) โ†’ Buy
  3. Rises to โ‚น786 (78.6%) โ†’ Sell
  4. If it breaks โ‚น1000, wait for new Fibonacci extension levels.

12. String Manipulation

# Concatenation
greeting = "Hello"
name     = "Alice"
message  = greeting + ", " + name
print(message)  # Output: Hello, Alice

# String Methods
text = "hello world"
print(text.upper())                    # Output: HELLO WORLD
print(text.replace("world", "Python")) # Output: hello Python

# String Formatting with f-strings
name = "Alice"
age  = 25
message = f"My name is {name} and I am {age} years old."
print(message)

13. Exception Handling

Handle errors gracefully using try and except.

try:
    x = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero!")

# With else and finally
try:
    x = 10 / 2
except ZeroDivisionError:
    print("Cannot divide by zero!")
else:
    print("Division successful!")
finally:
    print("This will always run.")

14. Lambda Functions

Lambda functions are small anonymous functions using the lambda keyword. Useful in map(), filter(), and sorted().

# Regular function
def add(x, y):
    return x + y

# Lambda equivalent
add_lambda = lambda x, y: x + y
print(add_lambda(2, 3))  # Output: 5

15. Map, Filter, and Reduce

# Map โ€” applies a function to all items
numbers = [1, 2, 3, 4]
squared = list(map(lambda x: x**2, numbers))
print(squared)  # Output: [1, 4, 9, 16]

# Filter โ€” keeps items matching a condition
numbers      = [1, 2, 3, 4, 5]
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)  # Output: [2, 4]

# Reduce โ€” reduces list to a single value
from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, numbers)
print(product)  # Output: 24

16. File Handling

# Writing to a file
with open("example.txt", "w") as file:
    file.write("Hello, world!")

# Reading from a file
with open("example.txt", "r") as file:
    content = file.read()
    print(content)  # Output: Hello, world!

# Reading large files line by line
with open("large_file.txt", "r") as file:
    for line in file:
        print(line.strip())

# Appending to a file
with open("log.txt", "a") as file:
    file.write("New log entry\n")

17. Regular Expressions (Regex)

Regex are patterns used to search, validate, and modify text. Python provides the built-in re module.

Finding a Word

import re
text  = "I love learning Python!"
match = re.search(r"Python", text)
if match:
    print("Found 'Python' in the text!")

Finding a Number

text  = "My favorite number is 42."
match = re.search(r"\d+", text)
if match:
    print("Found number:", match.group())  # Output: 42

Validating an Email

email   = "user@example.com"
pattern = r"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"
if re.match(pattern, email):
    print("Valid email!")

Extracting a Date

text = "The event is on 15/08/2025."
date = re.search(r"\d{2}/\d{2}/\d{4}", text)
if date:
    print("Found date:", date.group())  # Output: 15/08/2025

Replacing Spaces with Underscores

text          = "Hello World!"
modified_text = re.sub(r"\s", "_", text)
print(modified_text)  # Output: Hello_World!

Find All Numbers

text    = "I have 3 apples, 7 bananas, and 12 cherries."
numbers = re.findall(r"\d+", text)
print("Numbers found:", numbers)  # Output: ['3', '7', '12']

Strong Password Check

password = "Secure@123"
pattern  = r"^(?=.*[A-Z])(?=.*[a-z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"
if re.match(pattern, password):
    print("Strong password!")

Extract All Email Addresses

text   = "Contact us at support@example.com or sales@company.org."
emails = re.findall(r"[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+", text)
print("Emails found:", emails)

Extract Hashtags from a Tweet

tweet    = "Learning #Python and #Regex is fun! #Coding"
hashtags = re.findall(r"#\w+", tweet)
print("Hashtags found:", hashtags)  # ['#Python', '#Regex', '#Coding']

Remove Extra Spaces

text         = "Python  is   awesome!"
cleaned_text = re.sub(r"\s+", " ", text)
print(cleaned_text)  # Output: Python is awesome!

18. Working with Dates and Times

from datetime import datetime

# Get current date and time
now = datetime.now()
print(now)  # 2025-01-25 14:30:45.123456

# Format date and time
formatted = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted)  # 2025-01-25 14:30:45

19. Modules and Packages

# Importing a built-in module
import math
print(math.sqrt(16))  # Output: 4.0

# Creating your own module (mymodule.py)
def greet(name):
    return f"Hello, {name}!"

# Using it in another file
import mymodule
print(mymodule.greet("Alice"))  # Output: Hello, Alice!

20. Object-Oriented Programming (OOP)

OOP organises code into objects that represent real-world things. Think of a car โ€” it has features (data) like brand and model, and can perform actions like starting or stopping.

i) Class โ€” A Blueprint

class Car:
    wheels = 4  # Class attribute

    def __init__(self, brand, model):
        self.brand = brand  # Instance attribute
        self.model = model

    def display_info(self):
        print(f"{self.brand} {self.model} has {self.wheels} wheels.")

ii) Object โ€” An Instance

my_car = Car("Toyota", "Corolla")
my_car.display_info()  # Output: Toyota Corolla has 4 wheels.

iii) Attributes

print(my_car.brand)  # Instance attribute
print(Car.wheels)    # Class attribute

iv) Methods

class Dog:
    def __init__(self, name, breed):
        self.name  = name
        self.breed = breed

    def bark(self):
        print(f"{self.name} says Woof!")

dog = Dog("Buddy", "Golden Retriever")
dog.bark()  # Buddy says Woof!

v) Inheritance โ€” Reusing Code

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

class Dog(Animal):
    def speak(self):
        print("Dog barks")

dog = Dog()
dog.speak()  # Dog barks

vi) Encapsulation โ€” Hiding Data

class Car:
    def __init__(self, brand, speed):
        self.__brand = brand  # Private
        self.__speed = speed

    def accelerate(self, increment):
        if increment > 0:
            self.__speed += increment

    def brake(self, decrement):
        if decrement > 0 and self.__speed - decrement >= 0:
            self.__speed -= decrement

    def get_speed(self):
        return self.__speed

my_car = Car("Toyota", 50)
my_car.accelerate(30)
print(my_car.get_speed())  # 80
my_car.brake(20)
print(my_car.get_speed())  # 60

vii) Polymorphism โ€” One Method, Different Behaviors

class Cat:
    def speak(self):
        print("Meow")

class Dog:
    def speak(self):
        print("Woof")

animals = [Cat(), Dog()]
for animal in animals:
    animal.speak()  # Meow, then Woof

viii) Abstraction โ€” Hiding Complexity

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def speak(self):
        pass  # Must be defined in child classes

class Dog(Animal):
    def speak(self):
        print("Woof")

dog = Dog()
dog.speak()  # Woof

OOP Summary

ConceptDescription
ClassA blueprint for creating objects
ObjectA real instance of a class
AttributesData stored in an object
MethodsActions an object can perform
InheritanceReuse code from another class
EncapsulationHide and protect internal data
PolymorphismOne method name, different behaviors
AbstractionHide complexity, show only essentials

21. Decorators

Decorators modify or enhance a function without changing its actual code.

def decorator(func):
    def wrapper():
        print("Before function call")
        func()
        print("After function call")
    return wrapper

@decorator
def say_hello():
    print("Hello!")

say_hello()
# Before function call
# Hello!
# After function call

22. Iterators and Generators

Iterator

An iterator goes through items one by one using iter() and next().

numbers  = [1, 2, 3]
iterator = iter(numbers)
print(next(iterator))  # Output: 1

Generator

A generator uses the yield keyword to return values one at a time, saving memory.

def count_up_to(n):
    count = 1
    while count <= n:
        yield count
        count += 1

counter = count_up_to(3)
for num in counter:
    print(num)  # Output: 1, 2, 3

23. List and Dictionary Comprehensions

# List Comprehension
numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares)   # Output: [1, 4, 9, 16, 25]

# Dictionary Comprehension
names    = ["Alice", "Bob", "Charlie"]
ages     = [25, 30, 35]
age_dict = {name: age for name, age in zip(names, ages)}
print(age_dict)  # {'Alice': 25, 'Bob': 30, 'Charlie': 35}

24. Enumerate

enumerate() gives both the index and value when looping.

fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")
# 0: apple
# 1: banana
# 2: cherry

25. Zip

zip() combines multiple iterables into tuples.

names    = ["Alice", "Bob", "Charlie"]
scores   = [85, 90, 95]
combined = list(zip(names, scores))
print(combined)  # [('Alice', 85), ('Bob', 90), ('Charlie', 95)]

26. Set Operations

Sets are unordered collections of unique elements.

set1 = {1, 2, 3}
set2 = {3, 4, 5}

# Union
print(set1 | set2)  # {1, 2, 3, 4, 5}

# Intersection
print(set1 & set2)  # {3}

# Difference
print(set1 - set2)  # {1, 2}

27. Handling Timeouts and Delays (time.sleep)

import time
print("Starting...")
time.sleep(2)  # Pauses for 2 seconds
print("2 seconds later...")

28. Context Managers (with statement)

Context managers automatically set up and clean up resources like files or database connections.

with open("example.txt", "w") as file:
    file.write("This is a test file.")
# File is closed automatically โ€” no need to call file.close()

29. Multi-threading

Run multiple threads concurrently โ€” useful for I/O-bound tasks.

import threading

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

thread1 = threading.Thread(target=print_numbers)
thread2 = threading.Thread(target=print_numbers)

thread1.start()
thread2.start()

thread1.join()
thread2.join()

Common Use Cases

  • Web Scraping โ€” scrape multiple pages concurrently
  • File Downloads โ€” download multiple files simultaneously
  • Server Requests โ€” handle multiple client requests at once
  • Real-time Applications โ€” games, sensor input, network data
  • Background Tasks โ€” logging, syncing while main app runs
  • Database Operations โ€” run multiple queries in parallel
  • ML Model Training โ€” run experiments concurrently
  • Chatbots โ€” handle multiple user conversations at once

30. Decorators with Arguments

def repeat(n):
    def decorator(func):
        def wrapper(*args, **kwargs):
            for _ in range(n):
                func(*args, **kwargs)
        return wrapper
    return decorator

@repeat(3)
def greet(name):
    print(f"Hello, {name}!")

greet("Alice")
# Hello, Alice!
# Hello, Alice!
# Hello, Alice!

31. Handling JSON Data

import json

# Python to JSON
person    = {"name": "Alice", "age": 25}
json_data = json.dumps(person)
print(json_data)  # {"name": "Alice", "age": 25}

# JSON to Python
json_string = '{"name": "Alice", "age": 25}'
person      = json.loads(json_string)
print(person)     # {'name': 'Alice', 'age': 25}

32. Working with CSV Files

# Reading from a CSV file
import csv
with open('data.csv', 'r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

# Writing to a CSV file
data = [["name", "age"], ["Alice", 25], ["Bob", 30]]
with open('output.csv', 'w', newline='') as file:
    writer = csv.writer(file)
    writer.writerows(data)

33. Handling Large Data with Pandas

import pandas as pd

data = {"name": ["Alice", "Bob", "Charlie"], "age": [25, 30, 35]}
df   = pd.DataFrame(data)

print(df)
print(df["name"])           # Access a column
print(df[df["age"] > 30])   # Filter rows

34. Working with SQLite (Database)

import sqlite3

conn   = sqlite3.connect('example.db')
cursor = conn.cursor()

# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS users
    (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')

# Insert data
cursor.execute('''INSERT INTO users (name, age) VALUES ('Alice', 25)''')
conn.commit()

# Query data
cursor.execute('''SELECT * FROM users''')
print(cursor.fetchall())  # Output: [(1, 'Alice', 25)]

conn.close()

35. Working with APIs (requests Library)

The requests library makes it easy to send HTTP requests and work with responses.

GET Request โ€” Fetch Data

import requests

response = requests.get("https://api.github.com")
print(response.status_code)  # 200
print(response.json())

POST Request โ€” Send Data

data     = {"name": "Alice", "age": 25}
response = requests.post("https://api.example.com", json=data)
print(response.status_code)  # 201

36. Web Scraping with BeautifulSoup

BeautifulSoup parses HTML to extract useful information from web pages.

from bs4 import BeautifulSoup
import requests

response = requests.get("https://example.com")
soup     = BeautifulSoup(response.text, 'html.parser')

for link in soup.find_all('a'):
    print(link.get('href'))
# Prints all hyperlink URLs on the page

37. Multiprocessing

Run multiple processes simultaneously โ€” useful for CPU-bound tasks.

from multiprocessing import Process

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

process = Process(target=print_numbers)
process.start()
process.join()

38. Asyncio (Asynchronous Programming)

Write code that performs tasks while waiting for others to finish, making programs more efficient.

import asyncio

async def greet():
    await asyncio.sleep(1)
    print("Hello, Async!")

asyncio.run(greet())

39. Custom Exceptions

class CustomError(Exception):
    pass

try:
    raise CustomError("An error occurred!")
except CustomError as e:
    print(e)  # An error occurred!

40. YAML Files

import yaml

data        = {"name": "Alice", "age": 25}
yaml_string = yaml.dump(data)
print(yaml_string)
# age: 25
# name: Alice

42. Type Hinting

Type hints make code easier to understand and help catch errors with tools like mypy.

def add(a: int, b: int) -> int:
    return a + b

43. ConfigParser

Read and write .ini configuration files.

import configparser

config = configparser.ConfigParser()
config.read("config.ini")
print(config["DEFAULT"]["Setting"])

44. Command-Line Interfaces (argparse)

import argparse

parser = argparse.ArgumentParser(description="A simple CLI tool.")
parser.add_argument("--name", type=str, help="Enter your name.")
args   = parser.parse_args()

print(f"Hello, {args.name}!")

Run from terminal:

python your_program.py --name John
# Output: Hello, John!

45. Advanced String Formatting (f-strings)

F-strings (Python 3.6+) embed variables and expressions directly inside strings. They are faster and more readable than older methods.

# Variable insertion
name = "Alice"
age  = 25
print(f"{name} will be {age + 5} years old in 5 years.")

# Inline expression
width  = 5
height = 10
print(f"The area of the rectangle is {width * height}.")

# Number formatting
pi = 3.14159
print(f"Pi rounded to two decimal places is {pi:.2f}.")

Python For Beginners โ€” Complete Reference Guide

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.