Python Fundamentals: Essential Code Examples and Concepts

Unit 2: Basic Python Operations and Control Flow

1. Check if a Number is Even or Odd

n = int(input("Enter a number: "))
print("Even" if n % 2 == 0 else "Odd")

2. Determine if a Number is Positive, Negative, or Zero

n = float(input("Enter a number: "))
if n > 0:
    print("Positive")
elif n < 0:
    print("Negative")
else:
    print("Zero")

3. Generate Fibonacci Series of Length ‘n’

n = int(input("Enter the length: "))
a, b = 0, 1
for _ in range(n):
    print(a, end=" ")
    a, b = b, a + b

4. Generate a Multiplication Table

n = int(input("Enter a number: "))
for i in range(1, 11):
    print(f"{n} x {i} = {n * i}")

Unit 3: Functions, Strings, and Prime Numbers

1. Lambda Function for Checking Even or Odd

check = lambda x: "even" if x % 2 == 0 else "odd"
print(check(int(input("Enter a number: "))))

2. Concatenate Two Strings

s1 = input("Enter first string: ")
s2 = input("Enter second string: ")
print("Concatenated:", s1 + s2)

3. Check if a String Starts with a Specified Character

s = input("Enter string: ")
ch = input("Enter starting character: ")
print(s.startswith(ch))

4. Find the Length of a String

s = input("Enter string: ")
print("Length:", len(s))

5. Display String Characters and Initialize Count Using a Loop

s = input("Enter string: ")
count = 0
for c in s:
    print(c, end=" ")

6. Count Characters and Words in a String

s = input("Enter string: ")
print("Characters:", len(s))
print("Words:", len(s.split()))

7. Check if a Number is Prime

n = int(input("Enter number: "))
if n > 1 and all(n % i != 0 for i in range(2, int(n**0.5)+1)):
    print("Prime")
else:
    print("Not Prime")

Unit 4: File Handling and OS Operations

1. OS Operations: Display, Create, and Remove Directory

import os
print("Current Directory:", os.getcwd())
os.mkdir("my_dir")
print("Directory created.")
os.rmdir("my_dir")
print("Directory removed.")

2. Read the First 10 Characters from a File

with open("file.txt", "r") as f:
    print(f.read(10))

3. Print File Object Details (Name, Mode, Closed Status)

with open("file.txt", "r") as f:
    print("Name:", f.name)
    print("Mode:", f.mode)
    print("Closed:", f.closed)
print("Closed outside:", f.closed)

4. Count Vowels and Consonants in a Text File

vowels = 'aeiouAEIOU'
vowel_count = consonant_count = 0

with open("file.txt", "r") as f:
    text = f.read()
    for ch in text:
        if ch.isalpha():
            if ch in vowels:
                vowel_count += 1
            else:
                consonant_count += 1

print("Vowels:", vowel_count)
print("Consonants:", consonant_count)

Unit 5: Object-Oriented Programming (OOP) Concepts

1. Calculate Area of Square and Rectangle Using a Class

class Area:
    def square(self, side):
        return side * side
    
    def rectangle(self, l, b):
        return l * b

a = Area()
print("Square Area:", a.square(4))
print("Rectangle Area:", a.rectangle(4, 5))

2. Define a Class ‘Car’ with Attributes and Display Method

class Car:
    def __init__(self, name, cost):
        self.name = name
        self.cost = cost
    
    def display(self):
        print(f"Name: {self.name}, Cost: {self.cost}")

car1 = Car("BMW", 5000000)
car2 = Car("Toyota", 2000000)
car1.display()
car2.display()

3. Calculate Area of a Triangle Using a Class

class Triangle:
    def __init__(self, base, height):
        self.base = base
        self.height = height
    
    def area(self):
        return 0.5 * self.base * self.height

t = Triangle(10, 5)
print("Area:", t.area())

4. Student Class: Store Exam Number and Marks List

class Student:
    def __init__(self, exam_no, marks):
        self.exam_no = exam_no
        self.marks = marks
    
    def display(self):
        print(f"Exam No: {self.exam_no}, Marks: {self.marks}")

s = Student(101, [85, 78, 92, 88])
s.display()

5. Employee Class Definition and Instance Creation

class Employee:
    def __init__(self, name, emp_id, salary):
        self.name = name
        self.emp_id = emp_id
        self.salary = salary
    
    def display(self):
        print(f"Name: {self.name}, ID: {self.emp_id}, Salary: {self.salary}")

e1 = Employee("Sarthak", "E101", 50000)
e2 = Employee("Gaurav", "E102", 55000)
e1.display()
e2.display()