Introduction to Python Programming
Python is a beginner-friendly programming language used for web development, data analysis, automation, artificial intelligence, and more. Its simple, readable syntax makes it perfect for those new to programming. Think of Python as a tool to give clear instructions to a computer, like writing a recipe for your favorite dish.
This guide takes you from the basics (variables, loops) to advanced concepts (object-oriented programming, libraries). Each section includes definitions, syntax, examples, and hands-on exercises to help you learn by doing.
1. Getting Started: What is a Program?
A program is a set of instructions that tells a computer what to do, like displaying text or performing calculations. Python’s clear syntax makes writing these instructions easy, even for beginners.
Your First Python Program
Let’s write a simple program that displays “Hello, World!” using the print()
function.
print("Hello, World!")
Output: Hello, World!
2. Variables and Data Types
A variable is like a labeled box that stores data, such as numbers or text. Python automatically determines the data type (dynamic typing), so you don’t need to specify it.
Variable Naming Rules
- Names can include letters (a-z, A-Z), numbers (0-9), and underscores (_).
- Must start with a letter or underscore (not a number).
- Case-sensitive (
age
≠Age
). - Avoid Python keywords (e.g.,
if
,for
,print
).
Example
name = "Alice" # String
age = 25 # Integer
height = 5.6 # Float
is_student = True # Boolean
print(f"{name} is {age} years old, {height} feet tall, and is a student: {is_student}")
Output: Alice is 25 years old, 5.6 feet tall, and is a student: True
Data Types
Common Python data types include:
- Integer: Whole numbers (e.g.,
10
,-5
) - Float: Decimal numbers (e.g.,
3.14
) - String: Text (e.g.,
"Hello"
) - Boolean:
True
orFalse
- List: Ordered, mutable collection (e.g.,
[1, 2, 3]
) - Tuple: Ordered, immutable collection (e.g.,
(1, 2, 3)
) - Dictionary: Key-value pairs (e.g.,
{"name": "Alice", "age": 25}
)
Example with Lists and Dictionaries
fruits = ["apple", "banana", "orange"] # List
student = {"name": "Bob", "grade": 85} # Dictionary
print(fruits[0]) # First item
print(student["name"]) # Value for key
Output:
apple
Bob
3. Operators
Operators are symbols that perform operations on variables and values, like addition or comparison.
Arithmetic Operators
+
: Addition (e.g.,5 + 3 = 8
)-
: Subtraction (e.g.,5 - 3 = 2
)*
: Multiplication (e.g.,5 * 3 = 15
)/
: Division (e.g.,6 / 2 = 3.0
)//
: Floor division (e.g.,7 // 2 = 3
)%
: Modulus (e.g.,7 % 2 = 1
)**
: Exponentiation (e.g.,2 ** 3 = 8
)
Comparison Operators
==
: Equal to!=
: Not equal to>
: Greater than<
: Less than>=
: Greater than or equal to<=
: Less than or equal to
Logical Operators
and
: True if both conditions are trueor
: True if at least one condition is truenot
: Reverses the truth value
Example of Operators
a = 10
b = 3
print(a + b) # Addition
print(a > b) # Comparison
print(a > 5 and b < 5) # Logical
Output:
13
True
True
4. Input and Output
Python uses input()
to get user input and print()
to display output.
Example
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print(f"Hello, {name}! You are {age} years old.")
Sample Input: Alice
, 25
Output: Hello, Alice! You are 25 years old.
5. Conditional Statements
Conditional statements allow your program to make decisions using if
, elif
, and else
.
Syntax
if condition:
# Code if condition is True
elif another_condition:
# Code if another_condition is True
else:
# Code if no conditions are True
Example
age = int(input("Enter your age: "))
if age >= 18:
print("You are an adult.")
elif age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
Sample Input: 20
Output: You are an adult.
6. Loops
Loops repeat tasks. Python has for
loops (for sequences) and while
loops (for conditions).
For Loop
Iterates over a sequence (e.g., list, range).
for i in range(1, 6): # Prints 1 to 5
print(i)
Output:
1
2
3
4
5
While Loop
Repeats while a condition is true.
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
7. Functions
A function is a reusable block of code that performs a task, defined using def
.
Syntax
def function_name(parameters):
# Code block
return result # Optional
Example
def greet(name):
return f"Hello, {name}!"
message = greet("Alice")
print(message)
Output: Hello, Alice!
Default Parameters
def add(a, b=10):
return a + b
print(add(5)) # Uses default b=10
print(add(5, 20)) # Overrides default
Output:
15
25
8. Object-Oriented Programming (OOP)
OOP organizes code into objects, which combine data (attributes) and actions (methods). Think of objects as real-world entities, like a car with a color (attribute) and the ability to drive (method).
OOP Principles
Encapsulation
Encapsulation hides an object’s internal details and only exposes necessary parts. Use private attributes (with __
) to restrict access.
class BankAccount:
def __init__(self, owner, balance):
self.owner = owner
self.__balance = balance # Private attribute
def deposit(self, amount):
self.__balance += amount
return self.__balance
def get_balance(self):
return self.__balance
account = BankAccount("Alice", 1000)
print(account.get_balance()) # Access via method
account.deposit(500)
print(account.get_balance())
Output:
1000
1500
Inheritance
Inheritance allows a class to inherit attributes and methods from another class.
class Animal:
def __init__(self, name):
self.name = name
def eat(self):
return f"{self.name} is eating."
class Dog(Animal):
def bark(self):
return f"{self.name} says Woof!"
my_dog = Dog("Buddy")
print(my_dog.eat()) # Inherited
print(my_dog.bark()) # Dog-specific
Output:
Buddy is eating.
Buddy says Woof!
Polymorphism
Polymorphism allows different classes to be treated as instances of the same class through a shared method.
class Cat:
def speak(self):
return "Meow!"
class Dog:
def speak(self):
return "Woof!"
def animal_sound(animal):
print(animal.speak())
cat = Cat()
dog = Dog()
animal_sound(cat)
animal_sound(dog)
Output:
Meow!
Woof!
Abstraction
Abstraction hides complex details and shows only the essential features, often using abstract classes.
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius ** 2
circle = Circle(5)
print(circle.area())
Output: 78.5
Class Example
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says Woof!"
my_dog = Dog("Buddy", 3)
print(my_dog.name)
print(my_dog.bark())
Output:
Buddy
Buddy says Woof!
9. Python Libraries
Python libraries are pre-written code collections that extend Python’s capabilities. Here are some popular ones with examples.
NumPy (Numerical Computing)
Handles large arrays and mathematical operations.
import numpy as np
numbers = np.array([1, 2, 3, 4])
print(numbers * 2) # Multiply each element
Output: [2 4 6 8]
Pandas (Data Analysis)
Manages data in tables (DataFrames).
import pandas as pd
data = {"Name": ["Alice", "Bob"], "Age": [25, 30]}
df = pd.DataFrame(data)
print(df)
Output:
Name Age
0 Alice 25
1 Bob 30
Matplotlib (Data Visualization)
Creates charts and plots.
import matplotlib.pyplot as plt
x = [1, 2, 3]
y = [10, 20, 25]
plt.plot(x, y)
plt.savefig("plot.png") # Save instead of show
Saves a line plot as plot.png
.
Requests (HTTP Requests)
Fetches data from websites.
import requests
response = requests.get("https://api.github.com")
print(response.status_code) # Check if request succeeded
Output: 200
(success)
10. Roadmap to Advanced Python
Once you’ve mastered the basics, explore these advanced topics to become a proficient Python programmer:
File Handling
Read and write files for data storage.
with open("example.txt", "w") as file:
file.write("Hello, Python!")
with open("example.txt", "r") as file:
print(file.read())
Output: Hello, Python!
Web Development (Flask/Django)
Build websites using frameworks like Flask or Django.
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, Flask!"
if __name__ == "__main__":
app.run()
Runs a simple web server.
Data Science
Analyze data with libraries like Pandas, NumPy, and Scikit-learn.
import pandas as pd
data = pd.Series([1, 3, 5, 7])
print(data.mean()) # Calculate average
Output: 4.0
Automation
Automate tasks with libraries like PyAutoGUI.
import pyautogui
pyautogui.write("Hello, Automation!")
Types text automatically.
Learning Path: Start with file handling, then explore one domain (e.g., web development or data science). Practice by building projects like a to-do app, data dashboard, or automation script. Join communities (e.g., X posts with #Python) for support.
11. Try It Yourself
Try in Online Compiler
Python Notes by Code With Harry
Download Python Notes PDF View Python Notes PDFLearning Python by CFM Materials Physics Center
Download Python Detailed Notes PDF View Python Detailed Notes PDF