Python Tutorial

Beginner-Friendly Guide by skillplayground

Python Introduction

Python is a high-level, versatile programming language known for its simple and readable syntax. It is widely used in web development, data analysis, automation, artificial intelligence, and more.

  • Write programs with fewer lines of code, improving readability.
  • Automatic detection of variable types at runtime—no need for explicit declarations.
  • Supports object-oriented, functional, and procedural programming styles.
  • Dynamically typed and includes automatic garbage collection.

Hello World Program in Python

# This is a comment. It will not be executed.
print("Hello, World!")

Output:

Hello, World!

Explanation:

  • print() is a built-in Python function that displays text on the screen.
  • "Hello, World!" is a string (sequence of characters in quotes).
  • Python uses indentation (spaces or tabs) to define code blocks, unlike C, C++, or Java which use braces {}.

Key Takeaways:

  • Python is beginner-friendly and readable.
  • Indentation is crucial for defining code structure.
  • Versatile for many domains (web, data, automation, etc.).

Input and Output in Python

Python provides simple functions for user interaction and displaying output. The print() function displays output, while input() takes user input.

Taking Input Using input()

name = input("Enter your name: ")
print("Hello,", name, "! Welcome!")

Output:

Enter your name: skillplayground
Hello, skillplayground ! Welcome!

Printing Output Using print()

print("Hello, World!")

Output:

Hello, World!

Printing Variables

s = "Brad"
print(s)

s = "Anjelina"
age = 25
city = "New York"
print(s, age, city)

Output:

Brad
Anjelina 25 New York

Taking Multiple Inputs in One Line

x, y = input("Enter two numbers: ").split()
print(x, y)

Output:

Enter two numbers: 10 20
10 20

Taking Different Types of User Input

i = int(input("How old are you?: "))
f = float(input("Evaluate 7/2: "))

print(i, f)

Output:

How old are you?: 23
Evaluate 7/2: 3.5
23 3.5

Key Takeaways:

  • input() always returns a string—use typecasting for numbers.
  • print() can display multiple values separated by commas.
  • Use split() to take multiple inputs in one line.

Python Variables

Variables store data that can be referenced and manipulated during program execution. Python infers the variable type from the value assigned—no need for explicit type declarations.

x = 5
name = "Samantha"
print(x)
print(name)

Output:

5
Samantha

Rules for Naming Variables

  • Can contain letters, digits, and underscores (_).
  • Cannot start with a digit.
  • Case-sensitive (myVar and myvar are different).
  • Avoid Python keywords (e.g., if, for).

Valid variable names:

age = 21
_colour = "lilac"
total_score = 90

Invalid variable names:

1name = "Error"      # Starts with a digit
class = 10           # 'class' is a reserved keyword
user-name = "Doe"    # Contains a hyphen

Assigning Values to Variables

  • Basic Assignment: x = 5
  • Dynamic Typing: Variables can change type during execution.
x = 10
x = "Now a string"

Multiple Assignments

  • Same Value: a = b = c = 100
  • Different Values: x, y, z = 1, 2.5, "Python"
a = b = c = 100
print(a, b, c)

x, y, z = 1, 2.5, "Python"
print(x, y, z)

Output:

100 100 100
1 2.5 Python

Concept of Object Reference

Variables reference objects in memory, not the actual value. Reassigning a variable creates a new reference.

x = 5
y = x
x = 'skillplayground'
y = "Computer"

Type and Casting a Variable

print(type(5))           # <class 'int'>
print(type("hello"))     # <class 'str'>
print(int("123"))        # 123
print(float("3.14"))     # 3.14
print(str(100))          # '100'

Deleting a Variable

x = 10
del x
print(x)  # Raises NameError

Output:

ERROR!
Traceback (most recent call last):
  File "", line 3, in 
NameError: name 'x' is not defined

Key Takeaways:

  • Variables are references to objects.
  • Python is dynamically typed.
  • Use del to delete variables.

Python Operators

Operators are special symbols used to perform operations on values and variables (operands).

Arithmetic Operators

a = 15
b = 4

print("Addition:", a + b)         # 19
print("Subtraction:", a - b)      # 11
print("Multiplication:", a * b)   # 60
print("Division:", a / b)         # 3.75
print("Floor Division:", a // b)  # 3
print("Modulus:", a % b)          # 3
print("Exponentiation:", a ** b)  # 50625

Comparison Operators

a = 13
b = 33

print(a > b)   # False
print(a < b) # True print(a == b) # False print(a != b) # True print(a >= b)  # False
print(a <= b)  # True

Logical Operators

a = True
b = False

print(a and b)  # False
print(a or b)   # True
print(not a)    # False

Bitwise Operators

a = 10
b = 4

print(a & b)    # 0
print(a | b)    # 14
print(~a)       # -11
print(a ^ b)    # 14
print(a >> 2)   # 2
print(a << 2)   # 40

Assignment Operators

a = 10
b = a
b += a
b -= a
b *= a
b <<= a

Identity Operators

a = 10
b = 20
c = a

print(a is not b)   # True
print(a is c)       # True

Membership Operators

x = 24
y = 20
lst = [10, 20, 30, 40, 50]

if x not in lst:
    print("x is NOT present in given list")
if y in lst:
    print("y is present in given list")

Ternary Operator

a, b = 10, 20
min = a if a < b else b
print(min)    # 10

Operator Precedence and Associativity

expr = 10 + 20 * 30
print(expr)    # 610

print(100 / 10 * 10)    # 100.0
print(5 - 2 + 3)        # 6
print(5 - (2 + 3))      # 0
print(2 ** 3 ** 2)      # 512

Key Takeaways:

  • Operators perform operations on operands.
  • Operator precedence affects evaluation order.
  • Use is for identity, in for membership.

Python Keywords

Keywords are reserved words with special meaning in Python. They cannot be used as variable, function, or class names.

Getting a List of All Python Keywords

import keyword
print("The list of keywords are:")
print(keyword.kwlist)

Output:

The list of keywords are:  
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

Keywords as Variable Names

for = 10
print(for)

Output:

  File "Solution.py", line 1
    for = 10
        ^
SyntaxError: invalid syntax

Keyword Categories

CategoryKeywords
Value KeywordsTrue, False, None
Operator Keywordsand, or, not, is, in
Control Flow Keywordsif, else, elif, for, while, break, continue, pass, try, except, finally, raise, assert
Function and Classdef, return, lambda, yield, class
Context Managementwith, as
Import and Moduleimport, from
Scope and Namespaceglobal, nonlocal
Async Programmingasync, await

Keywords vs Identifiers

AspectKeywordsIdentifiers
DefinitionReserved words with special meaning in PythonNames for variables, functions, etc.
UsageCannot be used as variable namesCan be used as variable names
Examplesif, else, for, whilex, number, sum, result
CustomizationFixed by Python, cannot be redefinedUser-defined, can be changed

Key Takeaways:

  • Keywords are reserved and cannot be used as identifiers.
  • Identifiers are user-defined names for variables, functions, etc.

Python Data Types

Data types classify data items and determine what operations can be performed on them. Everything in Python is an object.

  • Numeric Types: int, float, complex
  • Sequence Types: str, list, tuple
  • Mapping Type: dict
  • Boolean Type: bool
  • Set Types: set, frozenset
  • Binary Types: bytes, bytearray, memoryview

Example: Assigning Different Data Types

x = 50                # int
x = 60.5              # float
x = "Hello World"     # string
x = ["skill", "play", "ground"]  # list
x = ("skill", "play", "ground")  # tuple

Numeric Data Types

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

b = 5.0
print(type(b))      # <class 'float'>

c = 2 + 4j
print(type(c))      # <class 'complex'>

Sequence Data Types

  • String: str – sequence of Unicode characters.
  • List: list – ordered, mutable collection.
  • Tuple: tuple – ordered, immutable collection.

Boolean Data Type

print(type(True))    # <class 'bool'>
print(type(False))   # <class 'bool'>

Set Data Type

s1 = set("skillplayground")
print(s1)

Dictionary Data Type

d = {1: 'skill', 2: 'play', 3: 'ground'}
print(d)

Key Takeaways:

  • Python supports various built-in data types.
  • Use type() to check the type of a variable.

Python Strings

Strings are sequences of characters inside quotes. Python does not have a separate character type—a single character is a string of length one.

Creating a String

s1 = 'skillplayground'
s2 = "skillplayground"
print(s1)
print(s2)

Output:

skillplayground
skillplayground

Multi-line Strings

s = """I am Learning
Python String on skillplayground"""
print(s)

s = '''I'm a 
Pythonista'''
print(s)

Accessing Characters

s = "skillplayground"
print(s[0])   # First character
print(s[4])   # Fifth character
print(s[-1])  # Last character

String Slicing

s = "skillplayground"
print(s[1:4])    # Characters from index 1 to 3
print(s[:3])     # First three characters
print(s[3:])     # Characters from index 3 to end
print(s[::-1])   # Reversed string

String Iteration

s = "Python"
for char in s:
    print(char)

String Immutability

s = "skillplayground"
s = "S" + s[1:]  
print(s)

Updating and Deleting Strings

s = "hello skill"
s1 = "H" + s[1:]                  
s2 = s.replace("skill", "skillplayground")  
print(s1)
print(s2)

s = "GfG"
del s
# print(s)  # Raises NameError

Common String Methods

s = "skillplayground"
print(len(s))              # 15
print(s.upper())           # SKILLPLAYGROUND
print(s.lower())           # skillplayground
print("   skill   ".strip())  # skill
print("Python is fun".replace("fun", "awesome"))  # Python is awesome

Concatenation and Repetition

s1 = "Hello"
s2 = "World"
print(s1 + " " + s2)   # Hello World

s = "Hello "
print(s * 3)           # Hello Hello Hello 

Formatting Strings

name = "Jake"
age = 22
print(f"Name: {name}, Age: {age}")

s = "My name is {} and I am {} years old.".format("Emily", 22)
print(s)

String Membership Testing

s = "skillplayground"
print("skill" in s)    # True
print("GfG" in s)      # False

Key Takeaways:

  • Strings are immutable and indexed.
  • Use slicing and methods for manipulation.
  • Use in to check for substrings.

Python Lists

Lists are ordered, mutable collections that can store elements of different types. They are dynamic and resizable.

Creating a List

a = [1, 2, 3, 4, 5]
b = ['apple', 'banana', 'cherry']
c = [1, 'hello', 3.14, True]
print(a)
print(b)
print(c)

Using list() Constructor

a = list((1, 2, 3, 'apple', 4.5))
print(a)

b = list("SPG")
print(b)

Creating Lists with Repeated Elements

a = [2] * 5
b = [0] * 7
print(a)
print(b)

Accessing List Elements

a = [10, 20, "SPG", 40, True]
print(a[0])      # 10
print(a[-1])     # True
print(a[1:4])    # [20, 'SPG', 40]

Adding Elements

a = []
a.append(10)
a.insert(0, 5)
a.extend([15, 20, 25])
a.clear()

Updating Elements

a = [10, 20, 30, 40, 50]
a[1] = 25
print(a)

Removing Elements

a = [10, 20, 30, 40, 50]
a.remove(30)
popped_val = a.pop(1)
del a[0]

Iterating Over Lists

a = ['apple', 'banana', 'cherry']
for item in a:
    print(item)

Nested Lists

matrix = [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
]
print(matrix[1][2])  # 6

List Comprehension

squares = [x**2 for x in range(1, 6)]
print(squares)  # [1, 4, 9, 16, 25]

Key Takeaways:

  • Lists are mutable and ordered.
  • Support various methods for manipulation.
  • List comprehensions provide concise creation.

Python Tuples

Tuples are immutable, ordered collections. Once created, their elements cannot be changed.

Creating a Tuple

tup = ()
tup = ('skill', 'play')
li = [1, 2, 4, 5, 6]
print(tuple(li))
tup = tuple('skill')
print(tup)

Tuple with Mixed Data Types

tup = (5, 'Welcome', 7.5, True, [1, 2, 3], {'key': 'value'})
print(tup)

Accessing Tuple Elements

tup = tuple("skill")
print(tup[0])      # s
print(tup[1:4])    # ('k', 'i', 'l')
print(tup[:3])     # ('s', 'k', 'i')

Tuple Unpacking

tup = ("skill", "play", "ground")
a, b, c = tup
print(a)
print(b)
print(c)

Concatenation of Tuples

tup1 = (0, 1, 2, 3)
tup2 = ('skill', 'play', 'ground')
tup3 = tup1 + tup2
print(tup3)

Slicing a Tuple

tup = tuple('SKILLPLAYGROUND')
print(tup[1:])     # ('K', 'I', 'L', 'L', 'P', 'L', 'A', 'Y', 'G', 'R', 'O', 'U', 'N', 'D')
print(tup[::-1])   # reversed
print(tup[4:9])    # ('L', 'P', 'L', 'A', 'Y')

Deleting a Tuple

tup = (0, 1, 2, 3, 4)
del tup
# print(tup)  # Raises NameError

Tuple Unpacking with Asterisk (*)

tup = (1, 2, 3, 4, 5)
a, *b, c = tup
print(a)  # 1
print(b)  # [2, 3, 4]
print(c)  # 5

Key Takeaways:

  • Tuples are immutable and ordered.
  • Support unpacking and slicing.
  • Use del to delete the entire tuple.

Python Dictionaries

Dictionaries store data as key-value pairs. Keys must be unique and immutable; values can be any type.

Creating a Dictionary

a = {1: 'skill', 2: 'play', 3: 'ground'}
b = dict(a="skill", b="play", c="ground")
print(a)
print(b)

Accessing Items

d = { "name": "Kat", 1: "Python", (1, 2): [1, 2, 4] }
print(d["name"])
print(d.get("name"))

Adding and Updating Items

d = {1: 'skill', 2: 'play', 3: 'ground'}
d["age"] = 22
d[1] = "Python dict"
print(d)

Removing Items

d = {1: 'skill', 2: 'play', 3: 'ground', 'age': 22}
del d["age"]
val = d.pop(1)
key, val = d.popitem()
d.clear()

Iterating Through a Dictionary

d = {1: 'skill', 2: 'play', 'age': 22}
for key in d:
    print(key)
for value in d.values():
    print(value)
for key, value in d.items():
    print(f"{key}: {value}")

Nested Dictionaries

d = {1: 'skill', 2: 'play', 3: {'A': 'Welcome', 'B': 'To', 'C': 'skillplayground'}}
print(d)

Key Takeaways:

  • Dictionaries are mutable and store key-value pairs.
  • Keys must be unique and immutable.
  • Support nesting and various methods for manipulation.

Python Sets

Sets are unordered collections of unique, mutable, and iterable elements. They do not allow duplicates and are not indexed.

Creating a Set

s = {1, 2, 3, 4}
print(s)

s = set("skillplayground")
print(s)

s = set(["SPG", "For", "skill"])
print(s)

Unordered, Unindexed, and Mutable

s = {3, 1, 4, 1, 5, 9, 2}
print(s)
try:
    print(s[0])
except TypeError as e:
    print(e)

Adding Elements

s = {1, 2, 3}
s.add(4)
s.update([5, 6])
print(s)

Accessing a Set

s = {"skill", "play", "skill"}
for i in s:
    print(i, end=" ")
print("\n", "skill" in s)

Removing Elements

s = {1, 2, 3, 4, 5}
s.remove(3)
s.discard(4)
val = s.pop()
s.clear()

Frozen Sets

fs = frozenset([1, 2, 3, 4, 5])
print(fs)

Typecasting Objects into Sets

li = [1, 2, 3, 3, 4, 5, 5, 6, 2]
s = set(li)
print(s)

s = "skillplayground"
s = set(s)
print(s)

d = {1: "One", 2: "Two", 3: "Three"}
s = set(d)
print(s)

Key Takeaways:

  • Sets are unordered and do not allow duplicates.
  • Use add() and update() to add elements.
  • Use frozenset for immutable sets.

Python Arrays

Python does not have a built-in array type, but similar functionality is available using lists, the array module, and NumPy arrays.

Python Lists as Arrays

a = [1, "Hello", [3.14, "world"]]
a.append(2)
print(a)

NumPy Arrays

import numpy as np
a = np.array([1, 2, 3, 4])
print(a * 2)

res = np.array([[1, 2], [3, 4]])
print(res * 2)

Python Array Module

import array as arr
a = arr.array('i', [1, 2, 3])
print(a[0])  # 1
a.append(5)
a.insert(1, 4)
a.remove(1)
a.pop(2)
print(a)

Slicing Arrays

import array as arr
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b = arr.array('i', a)
print(b[3:8])
print(b[5:])
print(b[:])

Searching and Updating

import array
a = array.array('i', [1, 2, 3, 1, 2, 5])
print(a.index(2))  # 1
a[2] = 6
print(a)

Array Operations

import array
a = array.array('i', [1, 2, 3, 4, 2, 5, 2])
print(a.count(2))  # 3
a.reverse()
print(*a)
a.extend([6, 7, 8, 9, 10])
print(a)

Key Takeaways:

  • Use lists for general-purpose arrays.
  • Use array module for homogeneous data.
  • Use NumPy for advanced numerical operations.

Control Flow: Conditional Statements and Loops

Conditional Statements

If Statement

age = 20
if age >= 18:
    print("Eligible to vote.")

Short-Hand if

age = 19
if age > 18: print("Eligible to Vote.")

If-Else Statement

age = 10
if age <= 12:
    print("Travel for free.")
else:
    print("Pay for ticket.")

Short-Hand if-else (Ternary Operator)

marks = 45
res = "Pass" if marks >= 40 else "Fail"
print(f"Result: {res}")

elif Statement

age = 25
if age <= 12:
    print("Child.")
elif age <= 19:
    print("Teenager.")
elif age <= 35:
    print("Young adult.")
else:
    print("Adult.")

Nested if-else

age = 70
is_member = True

if age >= 60:
    if is_member:
        print("30% senior discount!")
    else:
        print("20% senior discount.")
else:
    print("Not eligible for a senior discount.")

Match-Case Statement

number = 2
match number:
    case 1:
        print("One")
    case 2 | 3:
        print("Two or Three")
    case _:
        print("Other number")

Loops in Python

For Loop

n = 4
for i in range(0, n):
    print(i)

Iterating Over Sequences

li = ["skill", "play", "ground"]
for x in li:
    print(x)

Iterating by Index

li = ["skill", "play", "ground"]
for index in range(len(li)):
    print(li[index])

While Loop

cnt = 0
while cnt < 3:
    cnt = cnt + 1
    print("Hello skill")

Infinite While Loop

while True:
    print("Hello skill")

Nested Loops

for i in range(1, 5):
    for j in range(i):
        print(i, end=' ')
    print()

Loop Control Statements

Continue Statement

for letter in 'skillplayground':
    if letter == 'l' or letter == 'd':
        continue
    print('Current Letter :', letter)

Break Statement

for letter in 'skillplayground':
    if letter == 'l' or letter == 'd':
        break
print('Current Letter :', letter)

Pass Statement

for letter in 'skillplayground':
    pass
print('Last Letter :', letter)

Key Takeaways:

  • Use if, elif, else for conditional logic.
  • Use for and while loops for iteration.
  • Control loop execution with break, continue, and pass.

Python Functions

Functions are reusable blocks of code that perform specific tasks. They help organize code and avoid repetition.

Defining and Calling a Function

def fun():
    print("Welcome to skillplayground")

fun()

Function Arguments

def evenOdd(x):
    if x % 2 == 0:
        return "Even"
    else:
        return "Odd"

print(evenOdd(16))
print(evenOdd(7))

Types of Function Arguments

  • Default Arguments:
    def myFun(x, y=50):
        print("x:", x)
        print("y:", y)
    
    myFun(10)
  • Keyword Arguments:
    def student(fname, lname):
        print(fname, lname)
    
    student(fname='skill', lname='playground')
    student(lname='playground', fname='skill')
  • Positional Arguments:
    def nameAge(name, age):
        print("Hi, I am", name)
        print("My age is", age)
    
    nameAge("Olivia", 27)
    nameAge(27, "Olivia")
  • Arbitrary Arguments:
    def myFun(*args, **kwargs):
        print("Non-Keyword Arguments (*args):")
        for arg in args:
            print(arg)
        print("\nKeyword Arguments (**kwargs):")
        for key, value in kwargs.items():
            print(f"{key} == {value}")
    
    myFun('Hey', 'Welcome', first='skill', mid='play', last='ground')

Nested Functions

def f1():
    s = 'I love skillplayground'
    def f2():
        print(s)
    f2()
f1()

Anonymous Functions (lambda)

def c1(x): return x*x*x
c2 = lambda x: x*x*x

print(c1(7))
print(c2(7))

Return Statement

def sq_value(num):
    """Returns the square value of the entered number"""
    return num**2

print(sq_value(2))
print(sq_value(-4))

Pass by Reference vs Pass by Value

def myFun(x):
    x[0] = 20

lst = [10, 11, 12, 13]
myFun(lst)
print(lst)   # [20, 11, 12, 13]

def myFun2(x):
    x = 20

a = 10
myFun2(a)
print(a)     # 10

Recursive Functions

def factorial(n):
    if n == 0:  
        return 1
    else:
        return n * factorial(n - 1)
      
print(factorial(4))

Key Takeaways:

  • Functions promote code reuse and organization.
  • Support various argument types and recursion.
  • Mutable objects can be changed inside functions; immutable cannot.

Object-Oriented Programming (OOP) in Python

OOP organizes code using objects and classes to represent real-world entities and their behaviors.

Class

class Dog:
    species = "Canine"  # Class attribute

    def __init__(self, name, age):
        self.name = name  # Instance attribute
        self.age = age    # Instance attribute

Objects

dog1 = Dog("Buddy", 3)
print(dog1.name) 
print(dog1.species)

Four Pillars of OOP

  • Inheritance: Child class acquires properties/methods from parent class.
  • Polymorphism: Same operation, different behavior.
  • Encapsulation: Bundling data and methods, restricting access.
  • Abstraction: Hiding internal details, exposing only necessary functionality.

Key Takeaways:

  • OOP enables modular, maintainable, and scalable code.
  • Classes are blueprints; objects are instances.
  • Supports inheritance, polymorphism, encapsulation, and abstraction.

Python Exception Handling

Exception handling lets you manage unexpected events (like invalid input or missing files) without crashing your program.

Basic Example

n = 10
try:
    res = n / 0
except ZeroDivisionError:
    print("Cannot divide by zero.")

Difference Between Errors and Exceptions

  • Error: Issues in program logic (e.g., SyntaxError), occur at compile time.
  • Exception: Problems at runtime, can be managed (e.g., ZeroDivisionError).

Syntax of Exception Handling

try:
    n = 0
    res = 100 / n
except ZeroDivisionError:
    print("You can't divide by zero!")
except ValueError:
    print("Enter a valid number!")
else:
    print("Result is", res)
finally:
    print("Execution complete.")

Catching Specific Exceptions

try:
    x = int("str")
    inv = 1 / x
except ValueError:
    print("Not Valid!")
except ZeroDivisionError:
    print("Zero has no inverse!")

Catching Multiple Exceptions

a = ["10", "twenty", 30]
try:
    total = int(a[0]) + int(a[1])  
except (ValueError, TypeError) as e:
    print("Error:", e)
except IndexError:
    print("Index out of range.")

Catch-All Handlers

try:
    res = "100" / 20 
except ArithmeticError:
    print("Arithmetic problem.")
except:
    print("Something went wrong!")

Raising an Exception

def set(age):
    if age < 0:
        raise ValueError("Age cannot be negative.")
    print(f"Age set to {age}")

try:
    set(-5)
except ValueError as e:
    print(e)

Key Takeaways:

  • Use try, except, else, finally for robust error handling.
  • Catch specific exceptions for better debugging.
  • Raise exceptions to signal invalid states.

File Handling in Python

File handling allows you to create, read, write, and close files for persistent data storage.

Opening a File

file = open('filename.txt', 'mode')

Closing a File

file = open("skill.txt", "r")
# Perform file operations
file.close()

Checking File Properties

f = open("skill.txt", "r")
print("Filename:", f.name)
print("Mode:", f.mode)
print("Is Closed?", f.closed)
f.close()
print("Is Closed?", f.closed)

Reading a File

file = open("skill.txt", "r")
content = file.read()
print(content)
file.close()

Writing to a File

with open("skill.txt", "w") as file:
    file.write("Hello, Python!\n")
    file.write("File handling is easy with Python.")

Using the with Statement

with open("skill.txt", "r") as file:
    content = file.read()
    print(content)

Handling Exceptions When Closing a File

try:
    file = open("skill.txt", "r")
    content = file.read()
    print(content)
finally:
    file.close()

Key Takeaways:

  • Always close files to free resources.
  • Use with for automatic file closing.
  • Handle exceptions to avoid file corruption.

Python Modules and Packages

Modules

A module is a file containing Python definitions and statements (functions, classes, variables). Modules help organize code into separate files.

Creating a Module

# calc.py
def add(x, y):
    return x + y

def subtract(x, y):
    return x - y

Importing a Module

import calc
print(calc.add(10, 2))

Import Specific Items

from math import sqrt, factorial
print(sqrt(16))
print(factorial(6))

Import All Names

from math import *
print(sqrt(25))

Import With Alias

import math as m
print(m.pi)

Types of Modules

  • Built-in Modules: math, random, os
  • User-Defined Modules: Your own .py files
  • External Modules: Installed via pip (e.g., numpy, requests)
  • Package Modules: Directory with multiple modules and __init__.py

Locating a Module

import sys
for p in sys.path:
    print(p)

Python Packages

Packages are directories containing modules and an __init__.py file. They help organize and distribute code.

Example Package Structure

math_operations/
    __init__.py
    calculate.py
    basic/
        __init__.py
        add.py
        sub.py
    advanced/
        __init__.py
        multiply.py
        divide.py

Using the Package

from math_operations import calculate, add, subtract, multiply, divide

calculate()
print("Addition:", add(5, 3))
print("Subtraction:", subtract(10, 4))
print("Multiplication:", multiply(4, 2))
print("Division:", divide(10, 2))

Popular Python Packages

  • Web Frameworks: Flask, Django, FastAPI, Pyramid, Tornado, Falcon, CherryPy, Bottle
  • AI & Machine Learning: NumPy, Pandas, SciPy, XGBoost, StatsModels, Matplotlib, Seaborn, Scikit-learn, TensorFlow, PyTorch, Keras, spaCy, NLTK, OpenCV
  • GUI Applications: Tkinter, PyQT5, Kivy, PySide, PySimpleGUI
  • Web Scraping & Automation: Requests, BeautifulSoup, Selenium, Scrapy
  • Game Development: PyGame, Pyglet, Arcade

Key Takeaways:

  • Modules and packages organize code for reuse and maintainability.
  • Import built-in, user-defined, or external modules as needed.
  • Packages group related modules for distribution.

Frequently Asked Questions (FAQ)

Q1: What makes Python suitable for beginners?
Python’s simple, readable syntax and dynamic typing make it easy to learn and use, even for those new to programming.
Q2: How does Python handle variable types?
Python automatically detects variable types at runtime. You do not need to declare types explicitly.
Q3: What is the difference between a list and a tuple?
Lists are mutable (can be changed), while tuples are immutable (cannot be changed after creation).
Q4: How do I install external Python packages?
Use the pip command in your terminal, e.g., pip install numpy.
Q5: What is the purpose of the __init__.py file in a package?
It tells Python to treat the directory as a package and can be used to initialize package-level variables.
Q6: How do I handle errors in Python?
Use try, except, else, and finally blocks to catch and handle exceptions gracefully.
Q7: Are Python strings mutable?
No, strings are immutable. Any operation that modifies a string creates a new string.
Q8: What is the difference between == and is?
== checks for value equality, while is checks if two variables reference the same object in memory.
Q9: How do I read and write files safely in Python?
Use the with statement to open files. It ensures files are closed automatically, even if an error occurs.
Scroll to Top