Learn CodingPython

Python Programming

Table of Contents

Beginner — Learn the Basics First

Python is one of the most beginner-friendly programming languages. Its clear syntax and strong community support make it an excellent first language. This guide walks you through all the foundational concepts every new programmer needs to know — from installing Python to writing functions.


Introduction to Python

What is Python?

Python is a high-level, interpreted programming language that emphasizes code readability. Designed by Guido van Rossum and released in 1991, Python has grown to become one of the most popular programming languages globally. It supports multiple programming paradigms, such as object-oriented, procedural, and functional programming.

Its simplicity allows beginners to focus on learning programming logic rather than complicated syntax. Whether you’re building a website, automating tasks, analyzing data, or experimenting with AI, Python provides the tools and flexibility to do it all.

Installing Python and Setting Up IDEs

Before you write any code, you need to install Python. Visit the official Python website and download the latest version compatible with your operating system. During installation, make sure to check the box labeled “Add Python to PATH” — this ensures you can run Python from the command line.

To make coding easier, it’s best to use an Integrated Development Environment (IDE). IDEs like VS Code, PyCharm, or Thonny provide features such as syntax highlighting, auto-completion, and debugging tools that help beginners code efficiently.

Running Your First Python Script

Once Python is installed and your IDE is ready, it’s time to write your first program. Open your IDE, create a new file called hello.py, and type the following:

print("Hello, World!")

Save the file and run it. The output will be:

Hello, World!

This simple line demonstrates how Python uses the print() function to display information on the screen. You’re now officially a Python programmer!


Basic Syntax and Variables

Variables and Data Types

Variables store data in memory, allowing your programs to operate on that data. In Python, you don’t need to declare the type of a variable — it’s determined dynamically when the code runs.

name = "Alice"    # String
age = 25          # Integer
height = 5.6      # Float
is_student = True # Boolean

Python supports four basic data types:

  • int: Whole numbers

  • float: Numbers with decimals

  • str: Text

  • bool: True or False values

Naming Conventions

Naming variables well improves code readability. Follow these practices:

  • Use lowercase letters and underscores: user_name

  • Avoid special characters and spaces

  • Do not use Python keywords like def, class, or if

Type Casting

Python allows conversion between types using built-in functions:

age = "23"
converted_age = int(age)
print(converted_age + 2)  # Output: 25

This process, called type casting, is essential when dealing with user input or performing mathematical operations.


Input & Output

The input() and print() Functions

Python allows user interaction through the input() function and displays information using print().

name = input("What is your name? ")
print("Hello, " + name)

Here, input() collects user input as a string, and print() displays a message.

String Formatting Techniques

Readable code often involves formatting strings neatly.

Python provides multiple ways to format strings. Among them, f-strings are the most modern and readable option.

Using f-strings (Recommended)
This method is concise and preferred in Python 3.6+:

name = "Bob"
print(f"Welcome, {name}")

Using the .format() method

Introduced in Python 3.0, this approach allows placeholders to be replaced by values:

print("Welcome, {}".format(name))

Using % formatting

This older style is similar to C-style formatting:

print("Welcome, %s" % name)

Although all three work, f-strings are generally the clearest and fastest.
Each method has its use case, but f-strings offer the cleanest syntax and best performance.


Operators

Arithmetic and Comparison Operators

Python uses standard arithmetic operators:

  • + (addition)

  • - (subtraction)

  • * (multiplication)

  • / (division)

  • ** (exponentiation)

And comparison operators:

  • == (equal to)

  • != (not equal to)

  • <, >, <=, >=

a = 10
b = 3
print(a + b)   # 13
print(a > b)   # True

Assignment and Logical Operators

Assignment uses =, and can be combined with arithmetic:

x = 5
x += 2  # x becomes 7

Logical operators include:

  • and

  • or

  • not

print(True and False)  # False

 

Identity and Membership Operators

x = [1, 2, 3]
y = x
print(x is y)        # True
print(2 in x)        # True

is checks object identity, and in checks for membership within sequences.


Conditional Statements

Using if, elif, and else

Conditions allow programs to make decisions.

temperature = 30
if temperature > 35:
    print("It's hot.")
elif temperature < 20:
    print("It's cold.")
else:
    print("It's pleasant.")

Nested Conditions

Python supports nesting for complex logic:

score = 85
if score >= 60:
    if score >= 80:
        print("Grade: A")
    else:
        print("Grade: B")
else:
    print("Fail")

Although nesting is powerful, too much of it can reduce code clarity.


Loops

for and while Loops

Use loops to repeat actions.

for loop:

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

while loop:

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

 

break, continue, and pass

These control flow keywords alter loop behavior:

for i in range(5):
    if i == 3:
        break  # exits loop
    if i == 1:
        continue  # skips this iteration
    print(i)

def future_function():
    pass  # placeholder

Use them carefully to avoid confusing logic.


Data Structures

Lists

Lists in Python are ordered collections of items.
Here’s an example:

fruits = ["apple", "banana", "cherry"]
print(fruits[0])  # apple

You can modify lists after creating them, as they are mutable. Additionally, they can store elements of different data types, including strings, numbers, or even other lists.

Tuples

Tuples are like lists but immutable:

dimensions = (800, 600)
print(dimensions[1])

They’re great for storing fixed-size collections.

Sets

Sets store unique, unordered items:

colors = {"red", "blue", "green"}
print("blue" in colors)

They automatically remove duplicates.

Dictionaries

Dictionaries in Python store key-value pairs, making them ideal for representing structured data.
For example:

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

They allow you to access values efficiently using keys, rather than relying on index positions.
Thanks to this flexibility, dictionaries are widely used for configurations, JSON-like data, and lookups.


Functions

Defining and Calling Functions

Functions reduce repetition and improve code clarity.

def greet(name):
    return f"Hello, {name}"

print(greet("Sam"))

Parameters and Return Values

Functions can accept multiple parameters and return results:

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

print(add(3, 5))  # 8

 

Using *args and **kwargs

To accept a variable number of arguments:

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

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

def describe_person(**kwargs):
    return kwargs

print(describe_person(name="Jane", age=30))

These tools make your functions more flexible and reusable.


Intermediate — Strengthen Your Core Knowledge

At this stage in your Python journey, you’re ready to deepen your understanding of the language. You’ll now explore Python’s more powerful built-in features, write cleaner and more efficient code, and organize your programs for reusability and scalability.


String Manipulation

String Methods: split(), replace(), find(), and More

Strings are essential in almost every Python program. Python includes many built-in methods to manipulate string data without the need for external libraries.

  • split() breaks a string into a list of words or characters.

    text = "Learn Python Programming"
    words = text.split()
    print(words)  # ['Learn', 'Python', 'Programming']
  • replace() swaps a part of the string with another.

    sentence = "I love Java"
    updated = sentence.replace("Java", "Python")
    print(updated)  # I love Python
  • find() returns the index of the first occurrence of a substring.

    message = "Intermediate Python"
    print(message.find("Python"))  # 13

Other useful string methods include lower(), upper(), strip(), startswith(), and endswith(). Together, they help you clean, search, and format string data efficiently.

Slicing and Indexing

Python allows you to access parts of a string using indexing and slicing. Indexing starts at 0.

word = "Python"
print(word[0])    # P
print(word[-1])   # n

Slicing extracts a substring:

print(word[0:3])  # Pyt
print(word[:])    # Python (entire string)
print(word[::-1]) # nohtyP (reversed)

These tools are critical when working with textual data, especially in automation and data processing tasks.


List and Dictionary Comprehensions

Writing Concise Loops

List comprehensions offer a compact way to generate lists.

# Traditional loop
squares = []
for i in range(5):
    squares.append(i * i)

# List comprehension
squares = [i * i for i in range(5)]
print(squares)  # [0, 1, 4, 9, 16]

This syntax reduces boilerplate code and improves readability.

Conditional Logic Inside Comprehensions

List comprehensions also support if conditions:

even_squares = [x * x for x in range(10) if x % 2 == 0]
print(even_squares)  # [0, 4, 16, 36, 64]

Similarly, you can use dictionary comprehensions to construct dictionaries dynamically:

words = ["apple", "banana", "cherry"]
length_map = {word: len(word) for word in words}
print(length_map)  # {'apple': 5, 'banana': 6, 'cherry': 6}

Comprehensions promote clean, expressive code that’s easy to maintain.


Error Handling in Python

try, except, finally

Errors, or exceptions, occur when the program encounters something unexpected. Python lets you handle such cases gracefully using try, except, and finally.

try:
    result = 10 / 0
except ZeroDivisionError:
    print("Cannot divide by zero.")
finally:
    print("Execution completed.")
  • The try block contains the code that might cause an error.

  • The except block defines how to handle specific exceptions.

  • The finally block always executes, whether an error occurred or not.

Custom Exceptions

In some cases, built-in exceptions are not enough. You can define your own:

class NegativeNumberError(Exception):
    pass

def square_root(x):
    if x < 0:
        raise NegativeNumberError("Negative value not allowed.")
    return x ** 0.5

print(square_root(16))  # 4.0

By creating custom exceptions, your code becomes more descriptive and user-friendly.


Modules and Packages

Using import, from, and as

Modules are Python files containing reusable functions, classes, or variables. You can import them into your project in multiple ways.

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

from math import pi
print(pi)  # 3.141592653589793

import math as m
print(m.ceil(2.3))  # 3

Creating and Using Your Own Modules

You can organize your functions into modules. Create a file called utils.py:

# utils.py
def greet(name):
    return f"Hello, {name}"

Then import and use it in another file:

from utils import greet
print(greet("Pythonista"))

This promotes code reusability and better structure.

pip and Installing Third-Party Packages

pip is Python’s package installer. You can use it to install external libraries.

pip install requests

After installation, import and use the package:

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

Packages dramatically expand what Python can do, from web development to machine learning.


File Handling in Python

Reading and Writing Files

Python provides the open() function to interact with files.

# Writing
with open("example.txt", "w") as f:
    f.write("This is a test.")

# Reading
with open("example.txt", "r") as f:
    content = f.read()
    print(content)

The with statement ensures files are automatically closed after usage.

Working with CSV and JSON

For structured data, use the csv and json modules.

CSV Example:

import json

data = {"name": "Alice", "age": 25}
json_string = json.dumps(data)
print(json_string)  # {"name": "Alice", "age": 25}

JSON Example:

import json

data = {"name": "Alice", "age": 25}
json_string = json.dumps(data)
print(json_string)  # {"name": "Alice", "age": 25}

These formats are widely used in APIs and data exchange between applications.


Object-Oriented Programming (OOP) in Python

Classes and Objects

OOP is a paradigm where code is organized using “objects”, which are instances of “classes”. A class acts as a blueprint.

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

pet = Dog()
pet.bark()  # Woof!

Constructors (__init__)

The constructor initializes object properties when an instance is created.

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

p = Person("Alice", 30)
print(p.name)  # Alice

Inheritance, Encapsulation, Polymorphism

These are core principles of OOP:

  • Inheritance allows a class to acquire properties from another class:

    class Animal:
        def speak(self):
            print("Animal sound")
    
    class Cat(Animal):
        def speak(self):
            print("Meow")
    
    kitty = Cat()
    kitty.speak()  # Meow
    
  • Encapsulation restricts direct access to data:

    class BankAccount:
        def __init__(self):
            self.__balance = 0  # private variable
    
        def deposit(self, amount):
            self.__balance += amount
    
        def get_balance(self):
            return self.__balance
  • Polymorphism allows methods to be redefined by child classes.

    for animal in [Cat(), Animal()]:
        animal.speak()

Understanding self, __str__, and __repr__

  • self represents the current instance.

  • __str__() defines what print() should return for an object.

  • __repr__() provides a representation useful for debugging.

    class Book:
        def __init__(self, title):
            self.title = title
    
        def __str__(self):
            return f"Book title: {self.title}"
    
        def __repr__(self):
            return f"Book('{self.title}')"
    
    b = Book("Python Basics")
    print(b)        # Book title: Python Basics
    print(repr(b))  # Book('Python Basics')
    

Advanced — Master Python

Once you’re confident with Python basics and intermediate concepts, it’s time to level up. The advanced features of Python empower you to write efficient, elegant, and scalable code. From custom iterators to multithreading, these topics will help you think like a professional Python developer.


Iterators and Generators

iter() and next()

In Python, an iterator is an object that represents a stream of data. You can iterate through this stream one element at a time using next().

numbers = [10, 20, 30]
it = iter(numbers)
print(next(it))  # 10
print(next(it))  # 20

Any object with a __iter__() method is iterable, and any object with a __next__() method is an iterator.

yield and Custom Generator Functions

Generators simplify the process of creating iterators. Rather than storing all elements in memory, a generator yields items one at a time.

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

for num in count_up_to(3):
    print(num)

Compared to lists, generators are memory-efficient and perfect for processing large datasets or streams.


Decorators in Python

Function Decorators

A decorator is a function that modifies the behavior of another function. This is useful for adding logging, access control, caching, and more — without modifying the original function’s code.

def logger(func):
    def wrapper():
        print("Function is being called.")
        func()
        print("Function call ended.")
    return wrapper

@logger
def greet():
    print("Hello!")

greet()

Here, @logger wraps the greet function to add extra behavior.

Chaining Decorators

You can apply multiple decorators to a single function. They execute in the order they’re stacked.

def decorator_one(func):
    def wrapper():
        print("Decorator One")
        func()
    return wrapper

def decorator_two(func):
    def wrapper():
        print("Decorator Two")
        func()
    return wrapper

@decorator_one
@decorator_two
def say_hi():
    print("Hi!")

say_hi()

This approach provides a modular and flexible way to enhance functions.


Lambda Functions and Functional Programming in Python

lambda, map(), filter(), and reduce()

Lambda functions are anonymous, one-line functions that are especially useful in functional programming.

square = lambda x: x * x
print(square(4))  # 16

map() applies a function to every item in a list:

nums = [1, 2, 3]
squared = list(map(lambda x: x**2, nums))
print(squared)  # [1, 4, 9]

filter() selects items based on a condition:

even = list(filter(lambda x: x % 2 == 0, nums))
print(even)  # [2]

reduce() (from functools) applies a rolling computation:

from functools import reduce
total = reduce(lambda x, y: x + y, nums)
print(total)  # 6

These techniques promote clean, declarative code that focuses on what rather than how.


Regular Expressions (Regex)

Using the re Module

The re module allows pattern-based string processing using regular expressions.

import re
text = "Python 3.11 is awesome"
match = re.search(r"\d+\.\d+", text)
print(match.group())  # 3.11

Pattern Matching, Groups, Substitution

  • re.match() checks from the start of a string.

  • re.search() finds the first match anywhere.

  • re.findall() returns all matches.

Grouping captures parts of the match:

match = re.search(r"(\d+)\.(\d+)", text)
print(match.groups())  # ('3', '11')

Substitution replaces parts of a string:

new_text = re.sub(r"awesome", "powerful", text)
print(new_text)  # Python 3.11 is powerful

Regex is invaluable for validating emails, parsing logs, and cleaning data.


Working with Dates and Time

The datetime Module

Python’s datetime module enables precise manipulation of dates and times.

from datetime import datetime
now = datetime.now()
print(now)  # e.g., 2025-06-24 19:00:00

Timestamps, Formatting, Parsing

You can convert between strings and datetime objects:

# Formatting datetime as string
formatted = now.strftime("%Y-%m-%d %H:%M")
print(formatted)

# Parsing string into datetime
dt = datetime.strptime("2025-06-24", "%Y-%m-%d")
print(dt.year)  # 2025

For Unix timestamps:

timestamp = now.timestamp()
print(timestamp)

Understanding time zones and durations (timedelta) becomes essential for scheduling and analytics applications.


Multithreading and Multiprocessing in Python

threading and multiprocessing Modules

Python allows concurrent execution of code using threads or processes.

  • Multithreading is useful for I/O-bound tasks (e.g., file reading).

  • Multiprocessing is best for CPU-bound tasks (e.g., computation-heavy).

Multithreading Example:

import threading

def task():
    print("Running in a thread")

t = threading.Thread(target=task)
t.start()
t.join()

Multiprocessing Example:

from multiprocessing import Process

def task():
    print("Running in a process")

p = Process(target=task)
p.start()
p.join()

When and Why to Use Them

Use threads when tasks spend time waiting (e.g., downloading). Use processes when tasks require intense computation. This distinction helps optimize resource use and performance.


Advanced OOP Concepts in Python

Class Methods and Static Methods

A class method takes the class as its first argument and is defined using @classmethod.

class Circle:
    pi = 3.14

    @classmethod
    def area(cls, radius):
        return cls.pi * radius ** 2

A static method doesn’t take instance or class as its argument.

class Math:
    @staticmethod
    def add(x, y):
        return x + y

Multiple Inheritance

Python supports multiple inheritance, allowing a class to inherit from more than one base class.

class A:
    def method(self):
        print("A")

class B:
    def method(self):
        print("B")

class C(A, B):
    pass

obj = C()
obj.method()  # A (due to Method Resolution Order)

Magic Methods (__add__, __len__, etc.)

Magic methods provide special behavior for built-in operations.

class Book:
    def __init__(self, pages):
        self.pages = pages

    def __len__(self):
        return self.pages

book = Book(250)
print(len(book))  # 250

These methods include __add__, __str__, __eq__, and more — allowing your classes to behave like native types.


Working with APIs

Using requests to Fetch Data

Python’s requests library simplifies API communication.

import requests
response = requests.get("https://jsonplaceholder.typicode.com/posts/1")
print(response.status_code)

Consuming REST APIs

REST APIs provide access to external data and services. You send HTTP requests and receive responses, often in JSON format.

data = response.json()
print(data["title"])

You can also send POST requests:

payload = {"title": "New Post", "body": "Hello!", "userId": 1}
response = requests.post("https://jsonplaceholder.typicode.com/posts", json=payload)
print(response.json())

Parsing JSON Responses

The .json() method converts the raw JSON string into a Python dictionary. From there, you can easily access and manipulate the data.


Thanks for visiting! Explore the categories below for more exciting and useful content.


Leave a Reply

Your email address will not be published. Required fields are marked *