#List Methods
list_a =[]
for i in range(1, 4):
->>
list_a = [1, 2, 3]
list_b = [4, 5, 6]
list_a.extend(list_b)
print(list_a)
->>
list_a = [1, 2, 3]
list_a.insert(1,4)
print(list_a)
->>
list_a = [1, 2, 3]
list_a.pop()
print(list_a)
->>
list_a = [1, 3, 2, 3]
list_a.remove(3)
print(list_a)
->>
list_a = [1, 2, 3]
list_a.clear()
print(list_a)
->>
list_a = [1, 3, 2, 3]
index =list_a.index(3)
print(index)
->>
list_a = [1, 2, 3]
count = list_a.count(2)
print(count)
->>
list_a = [1, 3, 2]
list_a.sort()
print(list_a)
->>
list_a = [1, 3, 2]
sorted(list_a)
print(list_a)
->>
ML = {
"title": "Workshop",
"location": "Hyderabad",
"Complted_on": 1964
}
[Link]()
print(ML)
->>
dict_a = {
'name': 'Harsha',
'age': 22
}
print(dict_a.get('name'))
->>
dict_a = {
'name': 'Harsha',
'age': 22
}
print(dict_a.get('city'))
->>
dict_a = {
'name': 'Harsha',
'age': 22
}
result = 'name' in dict_a
print(result)
->>
ML = {
"title": "Workshop",
"location": "Hyderabad",
"Complted_on": 1964
}
x = [Link]()
print(x)
->>
x = ('key1', 'key2', 'key3')
y = 0
thisdict = [Link](x, y)
print(thisdict)
->>
ML = {
"title": "Workshop",
"location": "Hyderabad",
"Complted_on": 1964
}
x = [Link]("model")
print(x)
->>
ML = {
"title": "Workshop",
"location": "Hyderabad",
"Complted_on": 1964
}
x = [Link]()
print(x)
->>
ML = {
"title": "Workshop",
"location": "Hyderabad",
"Complted_on": 1964
}
ML = [Link]()
print(x)
->>
ML = {
"title": "Workshop",
"location": "Hyderabad",
"Complted_on": 1964
}
[Link]("location")
print(ML)
->>
ML = {
"title": "Workshop",
"location": "Hyderabad",
"Complted_on": 1964
}
[Link]()
print(ML)
->>
ML = {
"title": "Workshop",
"location": "Hyderabad",
"Complted_on": 1964
}
[Link]({"location": "Bangalore"})
print(ML)
->>
ML = {
"title": "Workshop",
"location": "Hyderabad",
"Complted_on": 1964
}
x = [Link]()
print(x)
->>
Ls = list(map(int, input("Enter the elements separated by space: ").split()))
total_sum = sum(Ls)
if total_sum % 2 != 0:
print("Cannot divide the list into two sublists with equal sums")
else:
target = total_sum // 2
sublist1 = []
sublist2 = []
current_sum = 0
for num in Ls:
if current_sum + num <= target:
[Link](num)
current_sum += num
else:
[Link](num)
print(f"L1 = {sublist1} => {sum(sublist1)}")
print(f"L2 = {sublist2} => {sum(sublist2)}")
->>
z = int(input("Enter number of values: "))
new_1 = []
print("Enter the values:")
for _ in range(z):
value = int(input())
new_1.append(value)
print("Input List:", new_1)
# Split into sublists
sublists = []
current_sublist = [new_1[0]]
for i in range(1, z):
if new_1[i] >= new_1[i - 1]:
current_sublist.append(new_1[i])
else:
[Link](current_sublist)
current_sublist = [new_1[i]]
[Link](current_sublist)
index = 1
for sublist in sublists:
print(f"list_{index} = {sublist}")
index += 1
->>
import random
# Data dictionary
data = {
"John Doe": {
"email": "[Link]@[Link]",
"age": 30,
"city": "New York",
"hobbies": ["Reading", "Traveling", "Swimming"],
"job": {
"title": "Software Engineer",
"company": "Tech Solutions Inc.",
"years_experience": 8
},
"address": {"street": "123 Elm St", "zip_code": "10001", "state": "NY"},
"contact_info": {
"phone": "123-456-7890",
"linkedIn": "[Link]/in/johndoe"
}
},
"Jane Smith": {
"email": "[Link]@[Link]",
"age": 25,
"city": "Los Angeles",
"hobbies": ["Cooking", "Dancing", "Photography"],
"job": {
"title": "Graphic Designer",
"company": "Creative Studio",
"years_experience": 5
},
"address": {"street": "456 Maple Ave", "zip_code": "90001", "state": "CA"},
"contact_info": {
"phone": "987-654-3210",
"linkedIn": "[Link]/in/janesmith"
}
}
}
for name, details in [Link]():
print(f"Random details for {name}:")
for key in details:
for details in
value = details[key]
if type(value) == dict:
random_key = [Link](list([Link]()))
print(f" {[Link]()} - {random_key.capitalize()}:
{value[random_key]}")
elif type(value) == list:
random_item = [Link](value)
print(f" {[Link]()}: {random_item}")
else:
print(f" {[Link]()}: {value}")
print()
->>
# Word-wise reverse
def word_wise_reverse(s):
return " ".join([Link]()[::-1])
#2-char interchange
def two_char_interchange(s):
words = [Link](" ")
result = []
for word in words:
transformed_word = ""
for i in range(1, len(word), 2):
# Reverse pairs of characters
transformed_word += word[i] + word[i - 1]
if len(word) % 2 != 0:
# Add the last character if the length is odd
transformed_word += word[-1]
[Link](transformed_word)
return " ".join(result)
user_string = input("Enter a string: ")
print("Word-wise Reversed:", word_wise_reverse(user_string))
print("Two-Character Interchanged:", two_char_interchange(user_string))
->>
def get_user_input():
num_lists = int(input("Enter the number of lists: "))
lists = []
for i in range(num_lists):
size = int(input(f"Enter the number of elements for list {i + 1}: "))
print(f"Enter elements for list {i + 1}:")
lst = [int(input()) for _ in range(size)]
[Link](lst)
return lists
def calculate(*lists):
if len(lists) == 1:
print("Single List:", lists[0])
else:
# Concatenate all lists
combined_list = sum(lists, [])
print("Combined List:", combined_list)
# If there are lists
if len(lists):
print("Maximum element:", max(combined_list))
print("Minimum element:", min(combined_list))
# If there are two or more lists
if len(lists) >= 2:
print("Sum of all elements:", sum(combined_list))
# For any number of lists
square_list = list(map(lambda x: x ** 2, combined_list))
odd_numbers = list(filter(lambda x: x % 2 != 0, combined_list))
print("Squares of elements:", square_list)
print("Odd numbers:", odd_numbers)
lists = get_user_input()
calculate(*lists)
->>
import os
def process_file(filename, file_location):
file_path = [Link](file_location, filename)
lines = int(input("Enter the number of lines: "))
with open(file_path, 'w') as file:
for i in range(lines):
[Link](input(f"Line {i+1}: ") + '\n')
# Read the file contents
with open(file_path, 'r') as file:
data = [Link]()
lines = [Link]()
line_count = 0
for line in lines:
if [Link]():
line_count += 1
# Count the total number of words
word_count = 0
for line in lines:
words = [Link]()
word_count += len(words)
# Count the total number of characters (including spaces)
chars_with_space = len(data)
# Count the total number of characters
chars_without_space = 0
for char in data:
if char not in (" ", "\n"):
chars_without_space += 1
print("\n=== File Data ===\n", data)
print(f"Lines: {line_count}, Words: {word_count}, Chars (with spaces):
{chars_with_space}, Chars (no spaces): {chars_without_space}")
process_file(input("Filename: "), input("File location: "))
->>
num_lines = int(input("Enter the number of lines: "))
with open("[Link]", "w") as demo_file:
for i in range(num_lines):
line = input(f"Enter line {i + 1}: ")
demo_file.write(line + "\n")
# Read and display content from [Link]
with open("[Link]", "r") as demo_file:
demo_content = demo_file.read()
print("\nContent of [Link]:")
print(demo_content)
# Write content from [Link] to [Link]
with open("[Link]", "w") as dummy_file:
dummy_file.write(demo_content)
# Read and reverse lines from [Link]
with open("[Link]", "r") as dummy_file:
dummy_lines = dummy_file.readlines()
reversed_lines = dummy_lines[::-1]
replaced_content = "".join(dummy_lines).replace("Hello", "Hi!")
print("".join(reversed_lines)) #reversed
print("\nContent after replacing 'Hello' with 'Hi!':")
print(replaced_content)
->>
def write_data(n):
student_info = []
student_marks = []
for i in range(n):
roll_no = input(f"Enter roll number for student {i + 1}: ")
name = input(f"Enter name for student {i + 1}: ")
marks = list(map(int, input(name).split()))
student_info.append(f"{roll_no}-{name}")
student_marks.append(f"{roll_no}-{'-'.join(map(str, marks))}")
# Write to [Link]
with open("[Link]", "w") as info_file:
info_file.write("\n".join(student_info))
# Write to [Link]
with open("[Link]", "w") as marks_file:
marks_file.write("\n".join(student_marks))
def calculate_and_grade():
"""Calculate averages, determine grades, and store data in grade-specific
files."""
grades = {"A": [], "B": [], "C": []}
# Read student info
with open("[Link]", "r") as info_file:
student_info = {[Link]("-")[0]: [Link]("-")[1].strip() for line in
info_file.readlines()}
# Read student marks
with open("[Link]", "r") as marks_file:
student_marks = marks_file.readlines()
# Calculate averages and determine grades
for line in student_marks:
parts = [Link]().split("-")
roll_no, marks = parts[0], list(map(int, parts[1:]))
average = sum(marks) / len(marks)
# Assign grade based on average
if 80 <= average <= 100:
grades["A"].append(f"{roll_no}-{student_info[roll_no]}-{average:.2f}")
elif 60 <= average < 80:
grades["B"].append(f"{roll_no}-{student_info[roll_no]}-{average:.2f}")
elif 40 <= average < 60:
grades["C"].append(f"{roll_no}-{student_info[roll_no]}-{average:.2f}")
# Sort by average in descending order and write to files
for grade, students in [Link]():
students_sorted = sorted(students, key=lambda x: float([Link]("-")[-1]),
reverse=True)
with open(f"{grade}[Link]", "w") as grade_file:
grade_file.write("\n".join(students_sorted))
# Example usage
n = int(input("Enter the number of students: "))
write_data(n)
calculate_and_grade()
print("Data processed and grades assigned!")
->>
#Exceptiojn handling
import re
class SignUp:
def __init__(self, fn, ln, un, pwd):
[Link] = fn
[Link] = ln
[Link] = un
[Link] = self.validate_password(pwd)
def validate_password(password):
while True:
if (len(password) < 8 or len(password) > 16):
print("Password must be between 8 and 16 characters.")
elif not [Link]("[a-z]", password):
print("Password must contain at least one lowercase letter.")
elif not [Link]("[A-Z]", password):
print("Password must contain at least one uppercase letter.")
elif not [Link]("[0-9]", password):
print("Password must contain at least one digit.")
elif not [Link]("[!@#$%^&*(),.?\":{}|<>]", password):
print("Password must contain at least one special character.")
else:
return password
# If validation fails, user to re-enter password
password = input("Enter a valid password: ")
class SignIn:
def __init__(self, un, pwd):
[Link] = un
[Link] = pwd
def loginCheck(self, signup_obj):
if [Link] == signup_obj.un and [Link] == signup_obj.pwd:
print(f"Welcome, {signup_obj.fn} {signup_obj.ln}!")
else:
raise Exception("Invalid username or password. Please try again.")
if __name__ == "__main__":
print("Sign Up")
first_name = input("Enter first name: ")
last_name = input("Enter last name: ")
username = input("Enter username: ")
password = input("Enter password: ")
# Create SignUp object
user = SignUp(first_name, last_name, username, password)
print("\nSign In")
signin_username = input("Enter username: ")
signin_password = input("Enter password: ")
# Create SignIn object
signin = SignIn(signin_username, signin_password)
# Check login
try:
[Link](user)
except Exception as e:
print(e)
->>
#Inheritance
class BankInfo:
def __init__(self, fn, ln, gender, address):
[Link] = fn
[Link] = ln
[Link] = gender
[Link] = address
class BankAccount:
def __init__(self, acno, amount, bank_info):
[Link] = acno
[Link] = amount
self.bank_info = bank_info
class Saving:
min_amount = 10000
rate = 0.06 # 6% as a decimal
def calculate_interest(amount, months):
return amount * [Link] * (months / 12)
class Current:
min_amount = 5000
rate = 0 # No interest
def calculate_interest(amount, months):
return 0
def validate_amount(account_type, amount):
min_amount = Saving.min_amount if account_type == "Saving" else
Current.min_amount
for _ in range(3): # User gets 3 attempts
if amount >= min_amount:
return True
else:
print(f"Amount must be at least {min_amount}. You have {_ + 1}/3
attempts left.")
amount = float(input("Enter a valid amount: "))
raise Exception("Invalid amount after 3 attempts. Account creation failed.")
# Main
if __name__ == "__main__":
# Input for BankInfo
print("Enter Bank Info:")
first_name = input("Enter first name: ")
last_name = input("Enter last name: ")
gender = input("Enter gender (M/F): ")
address = input("Enter address: ")
# Create BankInfo object
bank_info = BankInfo(first_name, last_name, gender, address)
# Input for BankAccount
print("\nEnter Bank Account Info:")
account_number = input("Enter account number: ")
initial_amount = float(input("Enter initial amount: "))
# Select Account Type
print("\nSelect Account Type:")
account_type = input("Enter 'Saving' or 'Current': ").capitalize()
if account_type not in ["Saving", "Current"]:
raise Exception("Invalid account type. Please select either 'Saving' or
'Current'.")
# Validate Initial Amount
try:
validate_amount(account_type, initial_amount)
except Exception as e:
print(e)
exit()
# Create BankAccount object
bank_account = BankAccount(account_number, initial_amount, bank_info)
# Input months
months = int(input("\nEnter the number of months to calculate interest: "))
# Calculate interest
if account_type == "Saving":
interest = Saving.calculate_interest(initial_amount, months)
else:
interest = Current.calculate_interest(initial_amount, months)
# Display Account Info and Interest
print("\nAccount Summary:")
print(f"Name: {bank_info.fn} {bank_info.ln}")
print(f"Gender: {bank_info.gender}")
print(f"Address: {bank_info.address}")
print(f"Account Number: {bank_account.acno}")
print(f"Account Type: {account_type}")
print(f"Initial Amount: {initial_amount}")
print(f"Interest Earned: {interest:.2f}")
print(f"Total Balance After {months} Months: {initial_amount + interest:.2f}")
->>
#Polymorphism
class Bank:
def __init__(self, max_transactions, max_amount):
self.__max_transactions = max_transactions
self.__max_amount = max_amount
self.__remaining_transactions = max_transactions
self.__remaining_amount = max_amount
def withdraw(self, amount):
"""Withdraw method to be overridden by subclasses"""
raise NotImplementedError("This method should be implemented by
subclasses")
def get_remaining_transactions(self):
return self.__remaining_transactions
def get_remaining_amount(self):
return self.__remaining_amount
def update_limits(self, amount):
self.__remaining_transactions -= 1
self.__remaining_amount -= amount
def validate_transaction(self, amount):
if self.__remaining_transactions <= 0:
raise Exception("Max transaction limit exceeded.")
if amount > self.__remaining_amount:
raise Exception("Max amount limit exceeded.")
class HDFCBank(Bank):
def __init__(self):
super().__init__(max_transactions=3, max_amount=20000)
def withdraw(self, amount):
self.validate_transaction(amount)
self.update_limits(amount)
print(f"Transaction successful in HDFC Bank. Amount withdrawn: {amount}")
class AXISBank(Bank):
def __init__(self):
super().__init__(max_transactions=5, max_amount=30000)
def withdraw(self, amount):
self.validate_transaction(amount)
self.update_limits(amount)
print(f"Transaction successful in AXIS Bank. Amount withdrawn: {amount}")
def main():
print("Welcome to ATM!")
bank_choice = input("Enter bank name (HDFC/AXIS): ").strip().upper()
if bank_choice == "HDFC":
bank = HDFCBank()
elif bank_choice == "AXIS":
bank = AXISBank()
else:
print("Invalid bank choice!")
return
while True:
try:
amount = float(input("Enter amount to withdraw: "))
[Link](amount)
print(f"Remaining transactions: {bank.get_remaining_transactions()}")
print(f"Remaining withdrawal limit: {bank.get_remaining_amount()}")
except Exception as e:
print(f"Transaction failed: {e}")
break
next_transaction = input("Do you want to make another transaction?
(yes/no): ").strip().lower()
if next_transaction != "yes":
print("Thank you for using our ATM!")
break
if __name__ == "__main__":
main()
->>