Learn Python Basics using simple programs
1. Variables & Data Types
# 1. Area of a rectangle
length = 5
width = 3
area = length * width
print("Area:", area)
# 2. Celsius to Fahrenheit
celsius = 30
fahrenheit = (celsius * 9/5) + 32
print("Fahrenheit:", fahrenheit)
# 3. String concatenation
first = "Data"
second = "Science"
full = first + " " + second
print(full)
# 4. Type conversion
x = "100"
y = int(x)
print(y + 50)
# 5. Boolean check
is_valid = True
print("Is form valid?", is_valid)
# 6. Swap two numbers
a, b = 10, 20
a, b = b, a
print("a =", a, "b =", b)
# 7. Calculate simple interest
p, r, t = 1000, 5, 2
si = (p * r * t) / 100
print("Simple Interest:", si)
# 8. Input and type
name = input("Enter name: ")
age = int(input("Enter age: "))
print(f"Name: {name}, Age: {age}")
# 9. Percentage
total = 450
marks = 396
percentage = (marks / total) * 100
print("Percentage:", round(percentage, 2))
# 10. Constant value
PI = 3.1416
radius = 7
area = PI * radius**2
print("Circle Area:", area)
2. Lists, Tuples, Sets, Dictionaries
# 1. List of student names
students = ["Alice", "Bob", "Charlie"]
print(students)
# 2. Tuple of coordinates
point = (10, 20)
print("X:", point[0])
# 3. Set of unique numbers
nums = [1, 2, 2, 3, 4, 4]
unique = set(nums)
print(unique)
# 4. Dictionary of student scores
scores = {"Alice": 90, "Bob": 85}
print("Bob's score:", scores["Bob"])
# 5. Append to list
students.append("David")
print(students)
# 6. Remove duplicate cities
cities = ["Delhi", "Mumbai", "Delhi", "Pune"]
print(list(set(cities)))
# 7. Check item in list
if "Alice" in students:
print("Found Alice")
# 8. Update dictionary
scores["Charlie"] = 78
print(scores)
# 9. Iterate dictionary
for name, score in scores.items():
print(name, "->", score)
# 10. Count frequency using dictionary
text = "apple banana apple mango banana apple"
word_freq = {}
for word in text.split():
word_freq[word] = word_freq.get(word, 0) + 1
print(word_freq)
3. Loops & Conditionals
# 1. Even numbers from 1 to 10
for i in range(1, 11):
if i % 2 == 0:
print(i)
# 2. Sum of numbers till 100
total = 0
for i in range(1, 101):
total += i
print("Sum:", total)
# 3. Find factorial
n=5
fact = 1
for i in range(1, n+1):
fact *= i
print("Factorial:", fact)
# 4. Grade categorization
score = 82
if score >= 90:
print("A")
elif score >= 75:
print("B")
else:
print("C or below")
# 5. Print table
num = 5
for i in range(1, 11):
print(f"{num} x {i} = {num*i}")
# 6. Password attempts
attempts = 0
while attempts < 3:
pwd = input("Enter password: ")
if pwd == "admin":
print("Welcome!")
break
else:
print("Wrong!")
attempts += 1
# 7. Sum of even numbers in list
nums = [2, 7, 4, 9, 10]
even_sum = 0
for n in nums:
if n % 2 == 0:
even_sum += n
print("Sum:", even_sum)
# 8. Count vowels
text = "machine learning"
count = 0
for ch in text:
if ch in 'aeiou':
count += 1
print("Vowel count:", count)
# 9. Check prime
n = 29
is_prime = True
for i in range(2, n):
if n % i == 0:
is_prime = False
break
print("Is Prime?", is_prime)
# 10. Nested loop: pattern
for i in range(1, 6):
for j in range(i):
print("*", end="")
print()
4. Functions
# 1. Greet user
def greet(name):
print("Hello", name)
greet("Tanveer")
# 2. Add two numbers
def add(x, y):
return x + y
print(add(10, 5))
# 3. Factorial
def factorial(n):
if n == 0: return 1
return n * factorial(n-1)
print(factorial(5))
# 4. Check even
def is_even(num):
return num % 2 == 0
print(is_even(4))
# 5. Convert string to list of words
def to_words(sentence):
return sentence.split()
print(to_words("I love AI"))
# 6. Calculate average
def average(marks):
return sum(marks)/len(marks)
print(average([80, 90, 70]))
# 7. Calculator with operator
def calc(x, y, op):
if op == '+': return x + y
if op == '-': return x - y
if op == '*': return x * y
if op == '/': return x / y
return "Invalid op"
print(calc(10, 5, '*'))
# 8. Count vowels
def count_vowels(s):
return sum(1 for ch in s if ch in 'aeiou')
print(count_vowels("hello"))
# 9. Recursive sum
def recursive_sum(n):
return 0 if n == 0 else n + recursive_sum(n - 1)
print(recursive_sum(10))
# 10. Keyword arguments
def student(name, age, grade):
print(f"{name} is {age} years old, Grade: {grade}")
student(name="Uzma", age=16, grade='A')
5. File Handling (CSV/JSON)
# 1. Write to text file
with open("info.txt", "w") as file:
file.write("Hello World!")
# 2. Read from text file
with open("info.txt", "r") as file:
content = file.read()
print(content)
# 3. Append to file
with open("info.txt", "a") as file:
file.write("\nAppended line")
# 4. Count lines in file
with open("info.txt", "r") as file:
lines = file.readlines()
print("Line count:", len(lines))
# 5. Search word in file
word = "World"
with open("info.txt", "r") as file:
print("Found" if word in file.read() else "Not Found")
# 6. Read CSV with pandas
import pandas as pd
df = pd.read_csv("sample.csv")
print(df.head())
# 7. Write dictionary to JSON
import json
data = {"name": "Tanveer", "age": 45}
with open("data.json", "w") as file:
json.dump(data, file)
# 8. Read from JSON
with open("data.json", "r") as file:
info = json.load(file)
print(info)
# 9. CSV row counting
with open("sample.csv") as file:
print("Row count:", sum(1 for line in file))
# 10. Read large file in chunks
with open("big.txt") as file:
for i, line in enumerate(file):
if i >= 5: break
print(line.strip())
6. Libraries: NumPy, Pandas
import numpy as np
import pandas as pd
# 1. NumPy array creation
a = np.array([1, 2, 3])
print(a)
# 2. Reshape array
b = np.arange(6).reshape(2, 3)
print(b)
# 3. Array operations
print("Sum:", a.sum())
# 4. Mean and Std
print("Mean:", a.mean(), "Std:", a.std())
# 5. Create DataFrame
data = {"Name": ["A", "B"], "Marks": [85, 90]}
df = pd.DataFrame(data)
print(df)
# 6. Filter rows
print(df[df["Marks"] > 85])
# 7. Add column
df["Pass"] = df["Marks"] >= 40
print(df)
# 8. Drop column
df.drop("Pass", axis=1, inplace=True)
print(df)
# 9. Read Excel
# df_excel = pd.read_excel("data.xlsx") # needs openpyxl
# 10. GroupBy Example
grouped = df.groupby("Name").sum()
print(grouped)
import numpy as np
# 11. Create array of zeros
zeros = np.zeros((2, 3))
print("Zeros:\n", zeros)
# 12. Create array of ones
ones = np.ones((3, 3))
print("Ones:\n", ones)
# 13. Identity matrix
identity = np.eye(4)
print("Identity:\n", identity)
# 14. Random integers
rand_ints = np.random.randint(1, 100, size=(3, 3))
print("Random Integers:\n", rand_ints)
# 15. Element-wise addition
arr1 = np.array([1, 2, 3])
arr2 = np.array([4, 5, 6])
print("Add:", arr1 + arr2)
# 16. Array slicing
matrix = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(matrix[1:, 1:])
# 17. Flatten array
flat = matrix.flatten()
print("Flattened:", flat)
# 18. Transpose matrix
print("Transpose:\n", matrix.T)
# 19. Dot product
print("Dot:", np.dot(arr1, arr2))
# 20. Logical filtering
print("Greater than 2:", arr1[arr1 > 2])
import pandas as pd
# 21. Create DataFrame from list of dicts
data = [{"A": 1, "B": 2}, {"A": 3, "B": 4}]
df = pd.DataFrame(data)
print(df)
# 22. Rename columns
df.columns = ["Alpha", "Beta"]
print(df)
# 23. Change column data type
df["Alpha"] = df["Alpha"].astype(float)
print(df.dtypes)
# 24. Fill missing values
data = {"A": [1, None, 3]}
df = pd.DataFrame(data)
df.fillna(0, inplace=True)
print(df)
# 25. Drop rows with missing data
data = {"A": [1, None, 3]}
df = pd.DataFrame(data)
df = df.dropna()
print(df)
# 26. Concatenate two DataFrames
df1 = pd.DataFrame({"ID": [1, 2]})
df2 = pd.DataFrame({"Name": ["Ali", "Uzma"]})
print(pd.concat([df1, df2], axis=1))
# 27. Merge DataFrames
left = pd.DataFrame({"ID": [1, 2], "Name": ["A", "B"]})
right = pd.DataFrame({"ID": [1, 2], "Marks": [90, 95]})
print(pd.merge(left, right, on="ID"))
# 28. Group by and mean
df = pd.DataFrame({"Dept": ["CSE", "CSE", "ECE"], "Marks": [80, 90, 85]})
print(df.groupby("Dept").mean())
# 29. Apply function to column
df["Rounded"] = df["Marks"].apply(lambda x: round(x / 10) * 10)
print(df)
# 30. Export to Excel
df.to_excel("students.xlsx", index=False)
7. Matplotlib / Seaborn
import matplotlib.pyplot as plt
import seaborn as sns
# 1. Line chart
plt.plot([1, 2, 3], [2, 4, 1])
plt.title("Line Plot")
plt.show()
# 2. Bar chart
plt.bar(["A", "B", "C"], [5, 7, 3])
plt.title("Bar Chart")
plt.show()
# 3. Histogram
plt.hist([1, 2, 2, 3, 3, 3, 4])
plt.title("Histogram")
plt.show()
# 4. Scatter plot
plt.scatter([1, 2, 3], [4, 5, 6])
plt.title("Scatter Plot")
plt.show()
# 5. Pie chart
plt.pie([10, 20, 30], labels=["A", "B", "C"], autopct="%1.1f%%")
plt.title("Pie Chart")
plt.show()
# 6. Heatmap
data = np.random.rand(3, 3)
sns.heatmap(data, annot=True)
plt.title("Heatmap")
plt.show()
# 7. Boxplot
sns.boxplot(data=[10, 20, 15, 30, 25])
plt.title("Boxplot")
plt.show()
# 8. Countplot
sns.countplot(x=["A", "B", "A", "C", "B", "B"])
plt.title("Countplot")
plt.show()
# 9. Seaborn pairplot
iris = sns.load_dataset("iris")
sns.pairplot(iris, hue="species")
plt.show()
# 10. Save plot
plt.plot([1, 2], [3, 4])
plt.savefig("lineplot.png")
import matplotlib.pyplot as plt
# 11. Horizontal bar chart
labels = ["Python", "Java", "C++"]
scores = [90, 70, 60]
plt.barh(labels, scores)
plt.title("Horizontal Bar Chart")
plt.show()
# 12. Plot with grid
plt.plot([1, 2, 3], [2, 4, 6])
plt.grid(True)
plt.title("Line with Grid")
plt.show()
# 13. Multiple lines
x = [1, 2, 3]
plt.plot(x, [i**2 for i in x], label="x^2")
plt.plot(x, [i**3 for i in x], label="x^3")
plt.legend()
plt.title("Multiple Lines")
plt.show()
# 14. Line styles & markers
plt.plot([1, 2, 3], [3, 2, 1], linestyle="--", marker="o")
plt.title("Styled Line")
plt.show()
# 15. Subplots
plt.subplot(1, 2, 1)
plt.plot([1, 2, 3], [1, 4, 9])
plt.title("First Plot")
plt.subplot(1, 2, 2)
plt.plot([1, 2, 3], [9, 4, 1])
plt.title("Second Plot")
plt.tight_layout()
plt.show()
# 16. Bar color and width
plt.bar([1, 2, 3], [5, 6, 7], color='orange', width=0.5)
plt.title("Styled Bar")
plt.show()
# 17. Save figure as PDF
plt.plot([1, 2], [3, 4])
plt.savefig("figure.pdf")
# 18. Title and axis labels
plt.plot([1, 2], [3, 4])
plt.title("Line Plot")
plt.xlabel("X Axis")
plt.ylabel("Y Axis")
plt.show()
# 19. Changing figure size
plt.figure(figsize=(8, 4))
plt.plot([1, 2, 3], [2, 4, 6])
plt.title("Large Plot")
plt.show()
# 20. Color and transparency
plt.plot([1, 2, 3], [4, 5, 6], color='green', alpha=0.6)
plt.title("Color and Alpha")
plt.show()
8. Object-Oriented Programming (OOP)
# 1. Class and object
class Student:
def __init__(self, name):
self.name = name
def greet(self):
print("Hi", self.name)
s = Student("Uzma")
s.greet()
# 2. Circle class with area
class Circle:
def __init__(self, r):
self.radius = r
def area(self):
return 3.14 * self.radius**2
c = Circle(5)
print(c.area())
# 3. Inheritance
class Animal:
def speak(self): print("Animal")
class Dog(Animal):
def speak(self): print("Dog barks")
d = Dog()
d.speak()
# 4. Encapsulation
class Bank:
def __init__(self):
self.__balance = 0
def deposit(self, amt):
self.__balance += amt
def get_balance(self):
return self.__balance
b = Bank()
b.deposit(500)
print(b.get_balance())
# 5. Polymorphism
class Cat:
def sound(self): print("Meow")
class Cow:
def sound(self): print("Moo")
for animal in [Cat(), Cow()]:
animal.sound()
# 6. Static method
class Util:
@staticmethod
def square(x): return x*x
print(Util.square(5))
# 7. Class variable
class Book:
publisher = "Penguin"
def __init__(self, title):
self.title = title
print(Book.publisher)
# 8. __str__ method
class Car:
def __init__(self, brand): self.brand = brand
def __str__(self): return f"Car: {self.brand}"
c = Car("Toyota")
print(c)
# 9. Property decorator
class Temp:
def __init__(self, c): self._c = c
@property
def fahrenheit(self): return self._c * 9/5 + 32
t = Temp(37)
print(t.fahrenheit)
# 10. Operator Overloading
class Point:
def __init__(self, x, y): self.x = x; self.y = y
def __add__(self, other): return Point(self.x+other.x, self.y+other.y)
def __str__(self): return f"({self.x},{self.y})"
p1 = Point(1,2)
p2 = Point(3,4)
print(p1 + p2)
9. List Comprehensions & Lambda
# 1. Squares
squares = [x**2 for x in range(10)]
print(squares)
# 2. Even numbers
evens = [x for x in range(10) if x % 2 == 0]
print(evens)
# 3. Lambda add
add = lambda x, y: x + y
print(add(5, 3))
# 4. Map with lambda
nums = [1, 2, 3]
doubled = list(map(lambda x: x * 2, nums))
print(doubled)
# 5. Filter with lambda
odds = list(filter(lambda x: x % 2 != 0, range(10)))
print(odds)
# 6. Nested list comprehension
matrix = [[j for j in range(3)] for i in range(3)]
print(matrix)
# 7. Dictionary comprehension
data = ["a", "b", "c"]
index_map = {val: i for i, val in enumerate(data)}
print(index_map)
# 8. Set comprehension
nums = [1, 2, 2, 3, 3]
unique_squares = {x**2 for x in nums}
print(unique_squares)
# 9. String list to uppercase
names = ["ali", "uzma"]
print([n.upper() for n in names])
# 10. Zip with lambda
names = ["Ali", "Uzma"]
scores = [90, 95]
print(list(map(lambda x: f"{x[0]} scored {x[1]}", zip(names, scores))))
10. Basic Exception Handling
# 1. Divide by zero
try:
x = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
# 2. Value error
try:
val = int("abc")
except ValueError:
print("Invalid input")
# 3. File not found
try:
open("nofile.txt")
except FileNotFoundError:
print("File not found")
# 4. Multiple except blocks
try:
a = int("42")
b=1/0
except ValueError:
print("Value Error")
except ZeroDivisionError:
print("Zero Division")
# 5. Finally block
try:
x = 10
finally:
print("This always runs")
# 6. Raise custom error
try:
raise Exception("Something went wrong")
except Exception as e:
print(e)
# 7. Input validation
try:
age = int(input("Enter age: "))
except Exception as e:
print("Error:", e)
# 8. Index error
try:
lst = [1, 2]
print(lst[5])
except IndexError:
print("Index out of range")
# 9. Key error
try:
d = {"a": 1}
print(d["b"])
except KeyError:
print("Key not found")
# 10. Type error
try:
print("2" + 2)
except TypeError:
print("Cannot add str and int")