0% found this document useful (0 votes)
2 views18 pages

Python Programming For Beginners

This document is a comprehensive guide for beginners in Python programming, covering essential topics such as variables, data types, control flow, functions, and object-oriented programming. It highlights Python's versatility and readability, making it suitable for various applications like web development and data analysis. By the end of the guide, readers will gain foundational skills to write Python scripts and continue learning advanced concepts.

Uploaded by

zlfvx80d0
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views18 pages

Python Programming For Beginners

This document is a comprehensive guide for beginners in Python programming, covering essential topics such as variables, data types, control flow, functions, and object-oriented programming. It highlights Python's versatility and readability, making it suitable for various applications like web development and data analysis. By the end of the guide, readers will gain foundational skills to write Python scripts and continue learning advanced concepts.

Uploaded by

zlfvx80d0
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming for Beginners

This beginner-friendly guide covers the core concepts of Python programming, from variables and
data types through functions, object-oriented design, and error handling, using clear examples
throughout. Python's readable syntax and versatile ecosystem make it ideal for web development,
data analysis, automation, and scientific computing, and this document introduces each topic with
practical, runnable code. By the end of this guide, readers will have the foundational skills to write
useful Python scripts and the vocabulary to continue learning more advanced topics.

Open Knowledge Series | 2025


Table of Contents

1. Introduction to Python

2. Variables and Data Types

3. Collections: Lists, Tuples, Sets, Dicts

4. Control Flow

5. Functions

6. Object-Oriented Programming

7. Error Handling

8. File I/O

9. Modules and Packages

10. Virtual Environments and pip


1. Introduction to Python

Python is a high-level, interpreted, general-purpose programming language created by


Guido van Rossum and first released in 1991. Python's design philosophy emphasizes code
readability, with significant use of whitespace and a syntax that reads almost like
English. The language has grown into one of the world's most popular programming
languages, consistently ranking in the top three across surveys like the Stack Overflow
Developer Survey and the TIOBE index.

Python's versatility is a major reason for its popularity. The same language is used to
write simple automation scripts, build large web applications, train machine learning
models, and analyze scientific data. Companies like Google, Instagram, Spotify, and NASA
rely heavily on Python.

The Python community maintains the Python Package Index (PyPI), which hosts hundreds of
thousands of third-party packages. Tools like pip let you install these packages
instantly. Popular packages include NumPy (numerical computing), pandas (data analysis),
Django (web framework), Flask (lightweight web framework), and TensorFlow (machine
learning).

To get started, download Python from [Link] or install it via your system's package
manager. Verify your installation:
python3 --version
python3 -c "print('Hello, World!')"
2. Variables and Data Types

Variables store values that your program can use and manipulate. In Python, you don't
declare a variable's type--it's inferred from the assigned value.

name = "Alice"
age = 30
height = 5.9
is_student = True
nothing = None

Python's built-in data types:

Strings (str):
greeting = "Hello, World!"
multiline = 'Line one
Line two' # triple-quoted string
escaped = "She said "hello""
raw = r"C:\Users\name" raw string ignores backslash escapes

String methods:
[Link]() "HELLO, WORLD!"
[Link]() "hello, world!"
[Link]() remove leading/trailing whitespace
[Link]("World", "Python")
[Link](", ") split into list
len(greeting) length
f"Name: {name}, Age: {age}" f-string formatting

Numbers:
Integer: x = 42
Float: pi = 3.14159
Complex: z = 2 + 3j
Operations: + - * / // % **
x // 3 integer division (floor)
x % 3 modulo (remainder)
2 ** 10 exponentiation (1024)

Booleans:
True, False
bool(0) == False, bool(1) == True, bool("") == False
Logical operators: and, or, not
3. Collections: Lists, Tuples, Sets, Dicts

Python provides four built-in collection types, each with different characteristics.

Lists -- ordered, mutable:


fruits = ["apple", "banana", "cherry"]
[Link]("date")
[Link](1, "avocado")
[Link]("banana")
popped = [Link]()
[Link]()
[Link]()
fruits[0] first item
fruits[-1] last item
fruits[1:3] slice
len(fruits) length
"apple" in fruits membership test

List comprehensions:
squares = [x**2 for x in range(10)]
evens = [x for x in range(20) if x % 2 == 0]
pairs = [(x, y) for x in range(3) for y in range(3)]

Tuples -- ordered, immutable:


point = (3, 7)
x, y = point unpacking
single = (42,) one-element tuple needs trailing comma

Sets -- unordered, unique:


s = {1, 2, 3, 2, 1} {1, 2, 3}
[Link](4)
[Link](2)
a | b union
a & b intersection
a - b difference

Dictionaries -- key-value pairs:


person = {"name": "Alice", "age": 30}
person["email"] = "alice@[Link]"
[Link]("phone", "N/A") safe access with default
[Link]({"age": 31})
del person["age"]
[Link](), [Link](), [Link]()
for key, val in [Link]():
print(f"{key}: {val}")
4. Control Flow

Control flow determines the order in which Python executes statements.

Conditionals:
temperature = 72

if temperature > 90:


print("Hot")
elif temperature > 70:
print("Warm")
elif temperature > 50:
print("Cool")
else:
print("Cold")

Ternary expression:
status = "adult" if age >= 18 else "minor"

For loops:
for fruit in ["apple", "banana", "cherry"]:
print(fruit)

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

for i in range(2, 10, 2): 2, 4, 6, 8


print(i)

for i, fruit in enumerate(fruits, start=1):


print(f"{i}. {fruit}")

for key, val in [Link]():


print(f"{key} = {val}")

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

Break and continue:


for n in range(10):
if n == 3:
continue skip this iteration
if n == 7:
break exit loop
print(n)

Pass:
if condition:
pass placeholder for future code

Match statement (Python 3.10+):


match command:
case "quit":
quit()
case "help":
show_help()
case _:
print("Unknown command")
5. Functions

Functions are reusable blocks of code that perform a specific task.

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

message = greet("Alice")

Default parameters:
def power(base, exponent=2):
return base ** exponent

power(3) 9
power(3, 3) 27

Keyword arguments:
def create_user(name, age, email=""):
return {"name": name, "age": age, "email": email}

create_user(name="Alice", age=30)
create_user("Bob", email="bob@[Link]", age=25)

Variable arguments:
def sum_all(*args):
return sum(args)

sum_all(1, 2, 3, 4) 10

def display(**kwargs):
for k, v in [Link]():
print(f"{k}: {v}")

display(name="Alice", age=30)

Lambda functions:
double = lambda x: x * 2
add = lambda x, y: x + y
sorted(items, key=lambda x: x[1])

Type hints (Python 3.5+):


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

def greet(name: str, times: int = 1) -> list[str]:


return [f"Hello, {name}!"] * times

Scope:
x = 10 global
def func():
x = 20 local, shadows global
global x declare use of global x
nonlocal x access enclosing scope
6. Object-Oriented Programming

Python is a fully object-oriented language. Classes let you define custom types that
bundle data and behavior.

Basic class:
class Dog:
species = "Canis lupus familiaris" class variable

def __init__(self, name, breed):


[Link] = name instance variable
[Link] = breed

def bark(self):
return f"{[Link]} says Woof!"

def __repr__(self):
return f"Dog('{[Link]}', '{[Link]}')"

rex = Dog("Rex", "German Shepherd")


print([Link]())

Inheritance:
class Animal:
def __init__(self, name):
[Link] = name
def speak(self):
raise NotImplementedError

class Cat(Animal):
def speak(self):
return f"{[Link]} says Meow!"

class Dog(Animal):
def speak(self):
return f"{[Link]} says Woof!"

animals = [Cat("Whiskers"), Dog("Rex")]


for a in animals:
print([Link]()) polymorphism

Special (dunder) methods:


__init__ constructor
__str__ str() representation
__repr__ developer representation
__len__ len() support
__eq__ == operator
__lt__ < operator
__add__ + operator
__getitem__ [] indexing
Dataclasses (Python 3.7+):
from dataclasses import dataclass

@dataclass
class Point:
x: float
y: float

def distance(self) -> float:


return (self.x**2 + self.y**2) ** 0.5

p = Point(3.0, 4.0)
print([Link]()) 5.0
7. Error Handling

Errors and exceptions are inevitable. Python's exception system lets you handle them
gracefully.

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

try:
x = int("not a number")
except ValueError as e:
print(f"Conversion failed: {e}")

Multiple exceptions:
try:
data = fetch_data()
except ConnectionError:
print("Network issue")
except TimeoutError:
print("Request timed out")
except (ValueError, KeyError) as e:
print(f"Data error: {e}")
else:
process(data) runs if no exception
finally:
cleanup() always runs

Raising exceptions:
def divide(a, b):
if b == 0:
raise ValueError("Divisor cannot be zero")
return a / b

Custom exceptions:
class ValidationError(Exception):
def __init__(self, field, message):
[Link] = field
super().__init__(f"{field}: {message}")

raise ValidationError("email", "invalid format")

Context managers (with statement):


with open("[Link]", "r") as f:
content = [Link]()
# file automatically closed

from contextlib import contextmanager


@contextmanager
def timer():
import time
start = [Link]()
yield
elapsed = [Link]() - start
print(f"Elapsed: {elapsed:.2f}s")

with timer():
expensive_operation()
8. File I/O

Reading and writing files is a fundamental programming task.

Reading files:
with open("[Link]", "r") as f:
content = [Link]() entire file as string

with open("[Link]", "r") as f:


lines = [Link]() list of lines

with open("[Link]", "r") as f:


for line in f: iterate line by line (memory-efficient)
print([Link]())

Writing files:
with open("[Link]", "w") as f: overwrite
[Link]("Hello, World!
")

with open("[Link]", "a") as f: append


[Link]("New entry
")

with open("[Link]", "w") as f:


lines = ["one
", "two
", "three
"]
[Link](lines)

Working with CSV:


import csv

with open("[Link]", "r") as f:


reader = [Link](f)
for row in reader:
print(row["name"], row["age"])

with open("[Link]", "w", newline="") as f:


writer = [Link](f, fieldnames=["name", "age"])
[Link]()
[Link]({"name": "Alice", "age": 30})

Working with JSON:


import json

data = {"name": "Alice", "scores": [95, 87, 92]}


json_str = [Link](data, indent=2)
with open("[Link]", "w") as f:
[Link](data, f, indent=2)

with open("[Link]", "r") as f:


loaded = [Link](f)

Path operations (pathlib):


from pathlib import Path
p = Path("/home/user/documents")
[Link](), p.is_dir(), p.is_file()
[Link](parents=True, exist_ok=True)
p / "subdir" / "[Link]" path joining
list([Link]("*.txt")) find files
9. Modules and Packages

Python's module system lets you organize code and reuse work from the community.

Importing:
import math
[Link](16)
[Link]

from math import sqrt, pi


sqrt(16)

from math import * import everything (avoid in large projects)

import numpy as np alias


[Link]([1, 2, 3])

Creating your own module:


# [Link]
def add(a, b):
return a + b

PI = 3.14159

# [Link]
import utils
print([Link](2, 3))
print([Link])

Packages (directories with __init__.py):


mypackage/
__init__.py
math_utils.py
string_utils.py

from mypackage import math_utils


from mypackage.string_utils import format_name

The __name__ == "__main__" guard:


# Only runs when file executed directly, not imported
if __name__ == "__main__":
main()

Useful standard library modules:


os operating system interface
sys system-specific parameters
re regular expressions
datetime dates and times
collections defaultdict, Counter, deque
itertools combinatorial iterators
functools higher-order functions
pathlib filesystem paths
json JSON encode/decode
csv CSV file reading/writing
sqlite3 embedded SQL database
urllib URL handling
http HTTP server and client
threading thread-based parallelism
subprocess spawn external processes
10. Virtual Environments and pip

Managing dependencies properly is essential for reproducible Python projects.

Why virtual environments?


Without them, all packages install globally. Different projects may need different
versions of the same library, causing conflicts. Virtual environments isolate each
project's dependencies.

Creating and activating:


python3 -m venv venv create in venv/ directory
source venv/bin/activate activate (Linux/Mac)
venv\Scripts\activate activate (Windows)
deactivate leave virtual environment

When active, your prompt changes to show (venv).


Python and pip now point to the virtual environment's copies.

Using pip:
pip install requests install latest version
pip install requests==2.28.0 specific version
pip install "requests>=2.25" minimum version
pip install -r [Link] install from file
pip list show installed packages
pip show requests package details
pip freeze > [Link] export current environment
pip uninstall requests remove package

[Link]:
requests==2.28.1
numpy>=1.24.0
pandas~=2.0.0 compatible release

Modern alternative -- [Link] (PEP 517/518):


[project]
name = "myproject"
version = "1.0.0"
dependencies = [
"requests>=2.28",
"click>=8.0",
]

Tools like Poetry and uv provide higher-level dependency management with lockfiles for
fully reproducible installs.

You might also like