0% found this document useful (0 votes)
2 views

Document 1

The document contains a series of programming assignments focused on basic Python functionalities, including checking number signs, character types, month days, file operations, and encapsulation. It provides code examples for each task, demonstrating input handling, condition checking, and file management. Additionally, it includes short notes on array methods and mathematical functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Document 1

The document contains a series of programming assignments focused on basic Python functionalities, including checking number signs, character types, month days, file operations, and encapsulation. It provides code examples for each task, demonstrating input handling, condition checking, and file management. Additionally, it includes short notes on array methods and mathematical functions.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 9

ASSIGNMENT – 3

Prince Saini
CSE (AL & ML)
3rd Year

1. Check if a number is +ve, -ve, or 0


# Input from user

num = float(input("Enter a number: "))

# Checking conditions

if num > 0:

print("The number is Positive.")

elif num < 0:

print("The number is Negative.")

else:

print("The number is Zero.")


2. Check if an input is an alphabet, digit, or special character
# Input from user

char = input("Enter a character: ")

# Checking conditions

if char.isalpha():

print("It is an alphabet.")

elif char.isdigit():

print("It is a digit.")

else:

print("It is a special character.")


3. Check if a character is uppercase or lowercase
# Input from user

char = input("Enter a character: ")

# Checking conditions

if char.isupper():

print("It is an uppercase letter.")

elif char.islower():

print("It is a lowercase letter.")

else:

print("Invalid input!")

4. Input month number and print number of days in that month


# Input from user

month = int(input("Enter month number (1-12): "))

# Dictionary for month-days mapping

month_days = {

1: 31, 2: 28, 3: 31, 4: 30, 5: 31, 6: 30,

7: 31, 8: 31, 9: 30, 10: 31, 11: 30, 12: 31

# Checking for leap year in February

if month == 2:

year = int(input("Enter year: "))

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):

print("February has 29 days.")

else:

print("February has 28 days.")

elif 1 <= month <= 12:

print(f"Month {month} has {month_days[month]} days.")

else:

print("Invalid month number.")

5. File Operations: Menu for WRITE, READ, INSERT, DELETE


def write_file():
with open("data.txt", "w") as file:

content = input("Enter content to write: ")

file.write(content)

print("Data written successfully.")

def read_file():

try:

with open("data.txt", "r") as file:

print("File Content:\n", file.read())

except FileNotFoundError:

print("File not found.")

def insert_file():

with open("data.txt", "a") as file:

content = input("Enter content to append: ")

file.write("\n" + content)

print("Data inserted successfully.")

def delete_file():

import os

if os.path.exists("data.txt"):

os.remove("data.txt")

print("File deleted successfully.")

else:

print("File not found.")

while True:

print("\nMenu: 1. WRITE 2. READ 3. INSERT 4. DELETE 5. EXIT")


choice = int(input("Enter choice: "))

if choice == 1:

write_file()

elif choice == 2:

read_file()

elif choice == 3:

insert_file()

elif choice == 4:

delete_file()

elif choice == 5:

break

else:

print("Invalid choice! Try again.")

6. Encapsulation in Python
Encapsulation is the concept of wrapping data and methods in a class and restricting access
to some of them.
class BankAccount:

def __init__(self, account_holder, balance):

self.account_holder = account_holder # Public attribute

self.__balance = balance # Private attribute

def deposit(self, amount):

if amount > 0:

self.__balance += amount

print(f"{amount} deposited. New balance: {self.__balance}")

else:

print("Invalid amount.")

def withdraw(self, amount):

if 0 < amount <= self.__balance:

self.__balance -= amount

print(f"{amount} withdrawn. Remaining balance: {self.__balance}")

else:

print("Insufficient balance or invalid amount.")

def get_balance(self):

return self.__balance # Access private attribute using method

account = BankAccount("John", 1000)

account.deposit(500)

account.withdraw(300)

print("Balance:", account.get_balance()) # Access private variable safely


7. Short Notes
a) Pop vs Remove in Array
Feature pop() remove()

Removes Element at specified index (default last) First occurrence of specified value

Returns Removed element None

Example arr.pop(2) arr.remove(5)

Error Handling IndexError if out of range ValueError if not found

b) Sqrt vs Abs Function

Function Purpose Example

sqrt(x) Returns square root of x math.sqrt(9) → 3.0

abs(x) Returns absolute value of x abs(-5) → 5

c) Sub vs Split in Regular Expressions

Function Purpose Example

sub() Replaces pattern in string re.sub(r'\d+', '#', 'a12b34') → 'a#b#'

split() Splits string based on pattern re.split(r'\s+', 'hello world') → ['hello', 'world']

You might also like