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
[Link]("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 [Link]():
print(name, "->", score)
# 10. Count frequency using dictionary
text = "apple banana apple mango banana apple"
word_freq = {}
for word in [Link]():
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 [Link]()
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("[Link]", "w") as file:
[Link]("Hello World!")
# 2. Read from text file
with open("[Link]", "r") as file:
content = [Link]()
print(content)
# 3. Append to file
with open("[Link]", "a") as file:
[Link]("\nAppended line")
# 4. Count lines in file
with open("[Link]", "r") as file:
lines = [Link]()
print("Line count:", len(lines))
# 5. Search word in file
word = "World"
with open("[Link]", "r") as file:
print("Found" if word in [Link]() else "Not Found")
# 6. Read CSV with pandas
import pandas as pd
df = pd.read_csv("[Link]")
print([Link]())
# 7. Write dictionary to JSON
import json
data = {"name": "Tanveer", "age": 45}
with open("[Link]", "w") as file:
[Link](data, file)
# 8. Read from JSON
with open("[Link]", "r") as file:
info = [Link](file)
print(info)
# 9. CSV row counting
with open("[Link]") as file:
print("Row count:", sum(1 for line in file))
# 10. Read large file in chunks
with open("[Link]") as file:
for i, line in enumerate(file):
if i >= 5: break
print([Link]())
6. Libraries: NumPy, Pandas
import numpy as np
import pandas as pd
# 1. NumPy array creation
a = [Link]([1, 2, 3])
print(a)
# 2. Reshape array
b = [Link](6).reshape(2, 3)
print(b)
# 3. Array operations
print("Sum:", [Link]())
# 4. Mean and Std
print("Mean:", [Link](), "Std:", [Link]())
# 5. Create DataFrame
data = {"Name": ["A", "B"], "Marks": [85, 90]}
df = [Link](data)
print(df)
# 6. Filter rows
print(df[df["Marks"] > 85])
# 7. Add column
df["Pass"] = df["Marks"] >= 40
print(df)
# 8. Drop column
[Link]("Pass", axis=1, inplace=True)
print(df)
# 9. Read Excel
# df_excel = pd.read_excel("[Link]") # needs openpyxl
# 10. GroupBy Example
grouped = [Link]("Name").sum()
print(grouped)
import numpy as np
# 11. Create array of zeros
zeros = [Link]((2, 3))
print("Zeros:\n", zeros)
# 12. Create array of ones
ones = [Link]((3, 3))
print("Ones:\n", ones)
# 13. Identity matrix
identity = [Link](4)
print("Identity:\n", identity)
# 14. Random integers
rand_ints = [Link](1, 100, size=(3, 3))
print("Random Integers:\n", rand_ints)
# 15. Element-wise addition
arr1 = [Link]([1, 2, 3])
arr2 = [Link]([4, 5, 6])
print("Add:", arr1 + arr2)
# 16. Array slicing
matrix = [Link]([[1,2,3],[4,5,6],[7,8,9]])
print(matrix[1:, 1:])
# 17. Flatten array
flat = [Link]()
print("Flattened:", flat)
# 18. Transpose matrix
print("Transpose:\n", matrix.T)
# 19. Dot product
print("Dot:", [Link](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 = [Link](data)
print(df)
# 22. Rename columns
[Link] = ["Alpha", "Beta"]
print(df)
# 23. Change column data type
df["Alpha"] = df["Alpha"].astype(float)
print([Link])
# 24. Fill missing values
data = {"A": [1, None, 3]}
df = [Link](data)
[Link](0, inplace=True)
print(df)
# 25. Drop rows with missing data
data = {"A": [1, None, 3]}
df = [Link](data)
df = [Link]()
print(df)
# 26. Concatenate two DataFrames
df1 = [Link]({"ID": [1, 2]})
df2 = [Link]({"Name": ["Ali", "Uzma"]})
print([Link]([df1, df2], axis=1))
# 27. Merge DataFrames
left = [Link]({"ID": [1, 2], "Name": ["A", "B"]})
right = [Link]({"ID": [1, 2], "Marks": [90, 95]})
print([Link](left, right, on="ID"))
# 28. Group by and mean
df = [Link]({"Dept": ["CSE", "CSE", "ECE"], "Marks": [80, 90, 85]})
print([Link]("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("[Link]", index=False)
7. Matplotlib / Seaborn
import [Link] as plt
import seaborn as sns
# 1. Line chart
[Link]([1, 2, 3], [2, 4, 1])
[Link]("Line Plot")
[Link]()
# 2. Bar chart
[Link](["A", "B", "C"], [5, 7, 3])
[Link]("Bar Chart")
[Link]()
# 3. Histogram
[Link]([1, 2, 2, 3, 3, 3, 4])
[Link]("Histogram")
[Link]()
# 4. Scatter plot
[Link]([1, 2, 3], [4, 5, 6])
[Link]("Scatter Plot")
[Link]()
# 5. Pie chart
[Link]([10, 20, 30], labels=["A", "B", "C"], autopct="%1.1f%%")
[Link]("Pie Chart")
[Link]()
# 6. Heatmap
data = [Link](3, 3)
[Link](data, annot=True)
[Link]("Heatmap")
[Link]()
# 7. Boxplot
[Link](data=[10, 20, 15, 30, 25])
[Link]("Boxplot")
[Link]()
# 8. Countplot
[Link](x=["A", "B", "A", "C", "B", "B"])
[Link]("Countplot")
[Link]()
# 9. Seaborn pairplot
iris = sns.load_dataset("iris")
[Link](iris, hue="species")
[Link]()
# 10. Save plot
[Link]([1, 2], [3, 4])
[Link]("[Link]")
import [Link] as plt
# 11. Horizontal bar chart
labels = ["Python", "Java", "C++"]
scores = [90, 70, 60]
[Link](labels, scores)
[Link]("Horizontal Bar Chart")
[Link]()
# 12. Plot with grid
[Link]([1, 2, 3], [2, 4, 6])
[Link](True)
[Link]("Line with Grid")
[Link]()
# 13. Multiple lines
x = [1, 2, 3]
[Link](x, [i**2 for i in x], label="x^2")
[Link](x, [i**3 for i in x], label="x^3")
[Link]()
[Link]("Multiple Lines")
[Link]()
# 14. Line styles & markers
[Link]([1, 2, 3], [3, 2, 1], linestyle="--", marker="o")
[Link]("Styled Line")
[Link]()
# 15. Subplots
[Link](1, 2, 1)
[Link]([1, 2, 3], [1, 4, 9])
[Link]("First Plot")
[Link](1, 2, 2)
[Link]([1, 2, 3], [9, 4, 1])
[Link]("Second Plot")
plt.tight_layout()
[Link]()
# 16. Bar color and width
[Link]([1, 2, 3], [5, 6, 7], color='orange', width=0.5)
[Link]("Styled Bar")
[Link]()
# 17. Save figure as PDF
[Link]([1, 2], [3, 4])
[Link]("[Link]")
# 18. Title and axis labels
[Link]([1, 2], [3, 4])
[Link]("Line Plot")
[Link]("X Axis")
[Link]("Y Axis")
[Link]()
# 19. Changing figure size
[Link](figsize=(8, 4))
[Link]([1, 2, 3], [2, 4, 6])
[Link]("Large Plot")
[Link]()
# 20. Color and transparency
[Link]([1, 2, 3], [4, 5, 6], color='green', alpha=0.6)
[Link]("Color and Alpha")
[Link]()
8. Object-Oriented Programming (OOP)
# 1. Class and object
class Student:
def __init__(self, name):
[Link] = name
def greet(self):
print("Hi", [Link])
s = Student("Uzma")
[Link]()
# 2. Circle class with area
class Circle:
def __init__(self, r):
[Link] = r
def area(self):
return 3.14 * [Link]**2
c = Circle(5)
print([Link]())
# 3. Inheritance
class Animal:
def speak(self): print("Animal")
class Dog(Animal):
def speak(self): print("Dog barks")
d = Dog()
[Link]()
# 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()
[Link](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()]:
[Link]()
# 6. Static method
class Util:
@staticmethod
def square(x): return x*x
print([Link](5))
# 7. Class variable
class Book:
publisher = "Penguin"
def __init__(self, title):
[Link] = title
print([Link])
# 8. __str__ method
class Car:
def __init__(self, brand): [Link] = brand
def __str__(self): return f"Car: {[Link]}"
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([Link])
# 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([[Link]() 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("[Link]")
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")