Beginner's Guide to Python Programming
Beginner's Guide to Python Programming
GUIDE
FOR
BEGINNERS
A Complete
Python Guide
Table of Contents
1. Introduction to Python
1.1 Whatis Python?
1.2 History and Evolution of Python
1.3 Features and Advantages of Python
1.4 Real-World Applications of Python
1.5 Installing Python and Setting Up the Environment
2. Python Basics
2.1 PythonSyntax andIndentation Rules
2.2 Variables and Constants
2.3 Data Types in Python
Numeric Types: int, float, complex
Text Type: str
Sequence Types: list, tuple, range
Set Type: set, frozenset
Mapping Type: dict
2.4 Type Casting and Type Checking
Python Notes 1
2.5 Taking User Input (input() function)
2.6 Printing Output (print() function, f-strings, format method)
2.7 Comments in Python Single-line and Multi-line)
|
= , += , -= , *=, etc.)
3.5 Assignment Operators i s n(ot)
3..67 MIdeemntbitey rOshpiepr Oatpoersra (tios,r s (in , noti n)
3
• if-elif-else Statement
4.2 Looping in Python
• for Loop
• while Loop
4.3 Nested Loops
4.4 Loop Control Statements
• break Statement
• continue Statement
• pass Statement
Python Notes 2
5. Data Structures in Python
5.1 Lists
Creating Lists
Adding and Removing Elements (append(), extend() , inser t() , remove() , pop() )
Sorting and Reversing Lists
5.2 Tuples
Tuple Characteristics Immutable)
Tuple Methods
5.3 Sets
Set Properties Unordered, Unique Elements)
5.4 Dictionaries
Key-Value Pair Structure Adding,
Dictionary Methods
6. Functions
6.1DefiningandCalling Functions
Python Notes 3
6.2 Function Arguments
Positional Arguments
Default Arguments
Keyword Arguments
7. Modules
7.1 Understanding Modules in Python
7.2 Importing Modules (import, from ... import, as)
7.3 Creating and Using Custom Modules
7.4 Standard Library Modules (math, random, datetimeo,s , etc.)
8. File Handling
8.1 Opening and Closing Files (open(), close() )
8.2 Reading and Writing Files (read(), wr ite() , wr itelines() )
9. Exception Handling
9.1 Understanding Errors in Python
Python Notes 4
9.2 Using try and except Blocks
9.3 Handling Multiple Exceptions
9.4 The finally Block
9.5 Raising Custom Exceptions ( raise keyword)
Python Notes 5
BeautifulSoup Parsing HTML
11.5 Automation
Selenium Automating Browsers)
Handling Forms
1. Introduction to Python
Python Notes 6
1.1 What is Python?
Pythoni s a high-level, interpreted, and general-purpose programming
language known for its simplicity, readability, and versatility. It was created
by Guido van Rossum and first released in 1991. Python supports multiple
programming paradigms, including procedural, object-oriented, and
functional programming.
Python Notes 7
🔹 Key Features:
✔ Easy to Read and Write: Uses indentation instead of braces {}.
✔ Extensive Standard Library: Includes built-in modules for OS, networking,
math, etc.
✔ Automatic Memory Management: Uses garbage collection.
✔ Interpreted Language: No need for compilation like C/C.
✔ High-level Language: Allows focusing on logic rather than low-level
details.
🔹 Advantages of Python:
✅ Beginner-friendly: Simple syntax, easy to learn.
✅ Large Community Support: Active developers and open-source
contr ibutions.
✅ Versatile: Used in web development, AI, data science, automation, and
more.
Python Notes 8
1.5 Installing Python and Setting Up the
Environment
🔹 [Link]:
Windows: Download from [Link].
Fedora).
🔹 2. Verify Installation:
Run:
python --version
or
python3 --version
Python Notes 9
python
Example:
python my_script.py
Example ([Link]):
Run it:
print("Welcome to Python!")
python [Link]
Python Notes 10
Loop Repeats the process
🔹 Example:
>>> a 10
>>> b 20
>>> a + b
30
🔹 Expected Output:
Hello, World!
Python Basics
Python Notes 11
2. Python Basics
2.1PythonSyntaxandIndentation Rules
🔹 Best Practices:
Use 4 spaces for indentation PEP 8 standard).
Python Notes 12
No need to declare types explicitly (dynamic typing).
Example:
name = "Python"
age 30
pi 3.14
print(name, age, pi)
num1 10 # int
num2 3.14 # float
num3 3 4j # complex
print(type(num1), type(num2), type(num3))
Python Notes 13
text = "Hello, Python!"
pr int(t ype(tex t))
Python Notes 14
my_dict = {"name": "Python", "year" 1991
pr int(my_dict["name"])
Python Notes 15
age = int(input("Enter your age: "))
print("Next year, you will be", age 1
Python Notes 16
🔹 Single-line comments (#)
# This is a comment
print("Hello, World!") # This is an inline comment
+ Addition 53 8
- Subtraction 10 4 6
Python Notes 17
/ Division (floating-point) 7/2 3.5
**
Exponentiation (power) 2 ** 3 8
🔹 Examples:
a, b 10, 3 print(a + b) #
13 print(a - b) # 7 print(a *
b) # 30 print(a / b) #
3.3333 print(a % b) # 1
print(a // b) # 3 print(a **
b) # 1000 10^3
== Equal to 5 5 True
🔹 Examples:
Python Notes 18
x, y 10, 20
print(x == y) # False
print(x ! y) # True
print(x
# False> y)
print(x
# True < y)
print(x >= y) # False
print(x <= y) # True
🔹 Examples:
a, b True, False
print(a and b) # False
print(a or b) # True
print(not a) # False
` ` OR `5
^ XOR 5 ^ 3 → 0101 ^ 0011 0110 6
Python Notes 19
~ NOT Inverts bits) 5 6
🔹 Examples:
x, y 5, 3
print(x & y) # 1 AND
print(x | y) # 7 OR
print(x ^ y) # 6 XOR
print(~x) # 6 NOT
print(x 1 # 10 Left shift)
print(x 1 # 2 Right shift)
= x5 x5
+= x 3 x=x3
-= x 3 x=x3
*= x * 3 x=x*3
/= x / 3 x=x/3
% x % 3 x=x%3
//= x // 3 x = x // 3
**= x ** 3 x = x ** 3
🔹 Examples:
x 10
x 5 # x = x 5 15
Python Notes 20
x * 2 # x = x * 2 30
pr int(x)
🔹 Examples:
a = 1, 2, 3
b=a
c = 1, 2, 3
🔹 Examples:
numbers = 1, 2, 3, 4
print(2 in numbers) # True
print(5 not in numbers) # True
Python Notes 21
3.8 Operator Precedence and Associativity
Operatorprecedencedeterminestheorderinwhichoperationsare
per formed.
* Exponentiation
^ Bitwise XOR
| Bitwise OR
🔹 Examples:
print(2 3 4 # 14 * has higher precedence than +)
print((2 3 * 4 # 20 Parentheses change precedence)
Python Notes 22
Control flow statements determine the execution order of statements in a
program. They allow decision-making and looping, enabling programs to
respond dynamically to different conditions.
🔹 if Statement
Syntax:
if condition:
# Code to execute when the condition is True
Example:
age 20
if age 18
print("You are eligible to vote.")
Output:
🔹 if-else Statement
Syntax:
if condition:
# Code when condition is True
Python Notes 23
else:
# Code when condition is False
Example:
num 5
if num % 2 0
print("Even number")
else:
print("Odd number")
Output:
Odd number
🔹 if-elif-else Statement
It runs the first block that evaluates to True. If none are True , else executes.
Syntax:
if condition1
# Executes if condition1 is True
elif condition2
# Executes if condition1 is False and condition2 is True
else:
# Executes if both conditions are False
Example:
marks 85
if marks 90
print("Grade: A")
Python Notes 24
elif marks 75
print("Grade: B")
elif marks 50
print("Grade: C")
else:
print("Fail")
Output:
Grade: B
🔹 for Loop
The loop automatically stops when it reaches the end of the sequence.
Syntax:
Example:
Output:
1
2
3
Python Notes 25
4
5
Output:
apple
banana
cher r y
🔹 while Loop
Syntax:
while condition:
# Code to execute while condition is True
Example:
count 1
while count 5
print(count)
count 1
Output:
Python Notes 26
1
2
3
4
5
while True:
print("This will run forever!") # Avoid this unless intentional
The inner loop executes completely for each iteration of the outer loop.
Example:
Output:
i=1, j=1
i=1, j=2
i=1, j=3
i=2, j=1
i=2, j=2
i=2, j=3
Python Notes 27
🔹 break Statement
Example:
Output:
1
2
3
🔹 continue Statement
Skips the rest of the loopʼs code for the current iteration but continues
with the next iteration.
Example:
Output:
1
2
4
5
Python Notes 28
🔹 pass Statement
Example:
Output:
0
1
2
3
4
5.1 Lists
Definition
Python Notes 29
A list is an ordered, mutable (changeable) collection of items. Lists allow
duplicate elements and can store different data types in a single list.
Creating Lists
empty_list = []
numbers = 1, 2, 3, 4, 5
mixed_list = ["Python", 3.14, True, 42
nested_list = 1, 2, 3, 4
Accessing Elements
List Methods
Method Descr iption Example
Python Notes 30
5.2 Tuples
Definition
At upleis anordered and immutable collection. Once a tuple is created, its
elements cannot be modified.
Creating Tuples
empty_tuple = ()
single_element_tuple = 42,) # Comma required
numbers = 10, 20, 30, 40
Accessing Elements
Tuple Methods
Method Descr iption Counts Example
count(x) occurrences of x Returns [Link](2)
tuple() tuple(lst)
5.3 Sets
Python Notes 31
Definition
Asetisanunordered collection of unique elements.
Creating Sets
empty_set = set()
my_set = 1, 2, 3, 4, 5
Set Methods
Method Descr iption Example
5.4 Dictionaries
Definition
Adictionaryisa key-value data structure that allows fast lookups.
Creating Dictionaries
Python Notes 32
Dictionary Methods
Method Descr iption Example
5.5 Strings
Definition
Astringisanimmutable sequence of characters.
String Methods
Method Descr iption Example
upper() Converts to uppercase "hello".upper()
Python Notes 33
star tswith(x) Checks if string starts with x "hello".startswith("h")
Functions
6. Functions in Python
A function is a block of reusable code designed to perform a specific task.
Functions improve code reusability, modularity, and readability.
def greet():
print("Hello, welcome to Python!")
result = add(5, 3)
print(result) # Output: 8
1. Positional Arguments
Python Notes 34
The most common type of argument.
full_name("Nihar", "Dodagatta")
# Output: Full Name: Nihar Dodagatta
2. Default Arguments
Used when a function has a default value for a parameter.
def greet(name="Guest"):
print(f"Hello, {name}!")
3. Keyword Arguments
Arguments are passed using parameter names.
Python Notes 35
Allows passing multiple positional arguments as a tuple.
def sum_numbers(*numbers):
total = sum(numbers)
print(f"Sum: {total}")
sum_numbers(1, 2, 3, 4, 5
# Output: Sum: 15
def display_info(**info):
for key, value in [Link]():
print(f"{key}: {value}")
def square(num):
return num * num
result = square(6)
print(result) # Output: 36
Python Notes 36
A function can return multiple values as a tuple.
x 10 # Global variable
def my_function():
x 5 # Local variable
print("Inside function:", x)
my_function()
print("Outside function:", x)
# Output:
# Inside function: 5
# Outside function: 10
Python Notes 37
x 10
def modify():
global x
x 20
modify()
print(x) # Output: 20
def factorial(n):
if n 0
return 1
return n * factorial(n 1
pr int(factor ial(5))
# Output: 120
def fibonacci(n):
if n 0
return 0
elif n 1
return 1
else:
return fibonacci(n 1 fibonacci(n 2
Python Notes 38
pr int(fibonacci(6))
# Output: 8
Syntax
square = lambda x: x * x
print(square(5)) # Output: 25
add = lambda a, b: a + b
print(add(3, 4)) # Output: 7
1. map() Function
Applies a function to all elements in an iterable.
2. filter() Function
Python Notes 39
Filters elements based on a condition.
Modules
7. Modules in Python
A module in Python is a file containing Python code (functions, classes, and
variables) that can be imported and reused in other programs. Modules help in
organizing code into separate files, improving readability and maintainability.
A module file has a .py extension.
Python Notes 40
Organized Structure Breaks large programs into smaller, manageable
files.
Namespace Management Helps prevent variable and function name
conflicts.
1. Using import
The import statement is used to import a module.
import math
3. Using as (Alias)
You can give a module or function an alias using as .
import math as m
Python Notes 41
This imports all functions and variables from a module.
# [Link]
def greet(name):
return f"Hello, {name}!"
import mymodule
Python Notes 42
import math
import random
import datetime
now = [Link]()
print(now) # Output: 20250219 123456.789123
import os
Python Notes 43
5. time Module (Time-Related Functions)
import time
import sys
import json
parsed_data = [Link](json_data)
print(parsed_data["name"]) # Output: Nihar
import csv
Python Notes 44
[Link](["Name", "Age"])
[Link](["Nihar", 25
import re
pattern = r"\\d+"
text = "There are 15 cats and 3 dogs."
import [Link]
response = [Link]("<[Link]
print([Link]) # Output: 200
Example: [Link]
Save the following code in scr [Link] :
import sys
print("Arguments:", [Link])
Python Notes 45
python [Link] hello world
Output:
pip list
Installing a Module
Uninstalling a Module
import requests
response = [Link]("<[Link]
print([Link]()) # Output: JSON response from GitHub API
File Handling
Python Notes 46
8. File Handling in Python
Pythonprovidesbuilt-in functions andmodules towork with files. Using file
handling, we can read, write, and modify files stored on disk.
Syntax:
Opening a File
Closing a File
Always close a file after performing operations to free system resources.
[Link]()
Python Notes 47
Reading a File ( read() , readline() , readlines() )
Python Notes 48
Appends data without deleting existing content.
Mode Descr iption Read (default) Error if file doesnʼt exist Write Creates
r file if not exists, overwrites existing content Append Adds new data,
w doesnʼt delete existing content Read and Write Raises error if file
a doesnʼt exist Read and Write Creates file if not exists, overwrites
r+ existing content Read and Append Creates file if not exists Read in
w+
Binary mode Write in Binary mode Append in Binary mode
a+
rb
wb
ab
Python Notes 49
CSV Comma-Separated Values) files store tabular data in plain text.
import csv
import csv
import csv
Python Notes 50
reader = [Link](file)
forrow in reader:
print(row["Name"], row["Age"], row["City"])
import json
data = {
"name": "Nihar",
"age" 25,
"city": "Hyderabad"
}
import json
Python Notes 51
import json
import json
Exception Handling
Syntax Errors Occur when the Python interpreter cannot understand the
code.
Python Notes 52
# Missing colon in 'if' statement SyntaxError)
if True
print("Hello")
KeyError
Raised when a dictionary key is not found
Raised when attempting to open a non-existent file
FileNotFoundError
Basic Example
try:
result 10 / 0 # Code that may raise an error
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
Output:
Python Notes 53
Error: Cannot divide by zero!
try:
num = int(input("Enter a number: ")) # May raise ValueError
result 10 / num # May raise ZeroDivisionError
except ZeroDivisionError:
print("Error: Cannot divide by zero!")
except ValueError:
print("Error: Invalid input! Please enter a valid integer.")
try:
num = int(input("Enter a number: "))
result 10 / num
except ZeroDivisionError, ValueError) as e:
print("An error occurred:", e)
Python Notes 54
try:
file = open("[Link]", "r")
content = [Link]()
except FileNotFoundError:
print("Error: File not found!")
finally:
print("Closing file...")
[Link]() # Ensuring the file is closed
class NegativeNumberError(Exception):
"""Custom exception for negative numbers"""
pass
Python Notes 55
if num 0
raise NegativeNumberError("Negative numbers are not allowed!")
class Car:
brand = "Toyota"
Python Notes 56
class Car:
def __init__(self, brand, model):
[Link] = brand # Instance variable
[Link] = model # Instance variable
# Creating objects
car1 Car("Toyota", "Corolla")
car2 Car("Honda", "Civic")
Class Variables
Shared among all instances of the class.
class Employee:
company = "TechCorp" # Class variable
Python Notes 57
emp2 Employee("Bob", 60000
class Animal:
def speak(self):
print("Animal makes a sound")
Python Notes 58
dog Dog()
[Link]() # Output: Dog barks
class Parent:
def show(self):
print("This is the parent class")
class Child(Parent):
def show(self):
print("This is the child class")
obj Child()
[Link]() # Output: This is the child class
Polymorphism
Allows different objects to be treated as instances of the same class
through method overriding or duck typing.
Example: Polymorphism
class Bird:
def fly(self):
print("Birds can fly")
class Penguin(Bird):
def fly(self):
Python Notes 59
print("Penguins cannot fly")
def flying_test(bird):
[Link]()
sparrow Bird()
penguin Penguin()
Example: Encapsulation
class BankAccount:
def __init__(self, balance):
self.__balance = balance # Private variable
def get_balance(self):
return self.__balance
account BankAccount(1000)
[Link](500)
print(account.get_balance()) # Output: 1500
Python Notes 60
# Accessing private variable directly raises an error
# print(account.__balance) # AttributeError
Abstraction
Hides complex details from the user using abstract classes.
class Dog(Animal):
def sound(self):
return "Bark"
class Cat(Animal):
def sound(self):
return "Meow"
dog Dog()
cat Cat()
Python Notes 61
Common Magic Methods
Method Descr iption
__eq__(self, other)
Defines behavior for obj1 obj2
class Book:
def __init__(self, title, pages):
[Link] = title
[Link] = pages
def __str__(self):
return f"Book: {[Link]}, Pages: {[Link]}"
def __len__(self):
return [Link]
Python Notes 62
11.1 Data Analysis Libraries
NumPy (Numerical Python)
import numpy as np
# Creating an array
arr = [Link]([1, 2, 3, 4, 5
print(arr) # Output: 1 2 3 4 5
# Reshaping an array
arr2D [Link](1, 5)
print(arr2D # Output: 1 2 3 4 5
import pandas as pd
# Creating a DataFrame
data = {'Name': ['Alice', 'Bob', 'Charlie'], 'Age': 25, 30, 35
Python Notes 63
df = [Link](data)
# Selecting a column
pr int(df['Name'])
x = 1, 2, 3, 4, 5
y = 10, 20, 25, 30, 40
[Link](x, y, marker='o') pl
[Link]("X-axis")
[Link]("Y-axis")
[Link]("Line Plot Example")
[Link]()
Python Notes 64
Supports heatmaps, pair plots, violin plots, and more.
# Creating a heatmap
[Link](data, annot=True, cmap="coolwarm")
[Link]()
Python Notes 65
# Predicting a new value
print([Link]([[6]])) # Output: 12.]
import requests
response = [Link]("<[Link]
print([Link]) # Prints the HTML content of the page
11.5 Automation
Selenium(Automating Browsers)
Python Notes 66
Automates browser actions such as clicking buttons, filling forms, and
navigating pages.
# Open Google
[Link]("<[Link]
import sqlite3
Python Notes 67
# Creating a table
[Link]("CREATE TABLE IF NOT EXISTS users (id INTEGER PRIMA
RY KEY, name TEXT"
# Inserting data
[Link]("INSERT INTO users (name) VALUES 'Alice')")
[Link]()
# Retrieving data
[Link]("SELECT * FROM users")
print([Link]()) # Output: 1, 'Alice')]
[Link]()
import [Link]
conn = [Link](
host="localhost",
user="root",
password="password",
database="testdb"
)
cursor = [Link]()
# Creating a table
[Link]("CREATE TABLE IF NOT EXISTS users (id INT AUTO_INCRE
MENT PRIMARY KEY, name VARCHAR100"
Python Notes 68
# Inserting data
[Link]("INSERT INTO users (name) VALUES 'Alice')")
[Link]()
# Retrieving data
[Link]("SELECT * FROM users")
pr int([Link]())
[Link]()
[Link]
Python Notes 69
{
"id" 1,
"name": "Alice",
"email": "alice@[Link]"
}
import requests
import requests
url = "[Link]
Python Notes 70
# Data to send
data = {
"title": "New Post",
"body": "This is a sample post",
"userId" 1
}
import json
import json
Python Notes 71
json_output = [Link](python_dict, indent=4
pr int( json_output)
import requests
api_key = "your_api_key_here"
city = "London"
url = f"[Link]
={api_ key}"
response = [Link](url)
weather_data = [Link]()
import requests
username = "octocat"
url = f"[Link]
Python Notes 72
response = [Link](url)
data = [Link]()
Installing Flask
app Flask(__name__)
# Sample data
users = [
{"id" 1, "name": "Alice"},
{"id" 2, "name": "Bob"}
]
@[Link]("/users", methods=["GET"])
def get_users():
return jsonify(users)
@[Link]("/users/<int:user_id>", methods=["GET"])
def get_user(user_id):
user = next((u for u in users if u["id"] == user_id), None)
if user:
return jsonify(user)
Python Notes 73
return jsonify({"error": "User not found"}), 404
if __name__ == "__main__":
[Link](debug=True)
Installing Flask
To install Flask, use:
app Flask(__name__)
@[Link]("/")
def home():
Python Notes 74
return "Hello, Flask!"
if __name__ == "__main__":
[Link](debug=True)
app Flask(__name__)
@[Link]("/")
def home():
return "Welcome to the Home Page"
@[Link]("/about")
def about():
return "This is the About Page"
if __name__ == "__main__":
[Link](debug=True)
Dynamic Routes
Dynamic routes allow passing parameters in URLs.
Python Notes 75
@[Link]("/user/<name>")
def user(name):
return f"Hello, {name}!"
app Flask(__name__)
if __name__ == "__main__":
[Link](debug=True)
Python Notes 76
Accepts user input and returns a personalized greeting.
Python Notes 77