Answer for 2nd Assignment
Answer for Question 1:
1. Creating Strings:
a. # Example strings
b. A = "ABCDEFGHIJ" # Length 10
c. B = "ABCDE" # Length 5
2. String Operations:
a. C = A + B # Result: "ABCDEFGHIJABCDE"
3. Slicing:
a. first_three_A = A[:3] # Result: "ABC"
b. first_two_B = B[:2] # Result: "AB"
4. Comparison:
a. are_equal = (A == B) # Result: False
5. Filling with characters:
a. A = "A" * 10 # Result: "AAAAAAAAAA"
b. B = "B" * 5 # Result: "BBBBB"
Answer for Question 2a:
string_a = "hello world"
upper_case_a = string_a.upper()
print(upper_case_a) # Outputs: HELLO WORLD
Answer for Question 2b:
# Function to display the menu and get user choice
def display_menu():
print("Select an operation:")
print("1. Add (x + y)")
print("2. Subtract (x - y)")
print("3. Multiply (x * y)")
print("4. Divide (x / y)")
print("5. Power (x^y or y^x)")
choice = int(input("Enter your choice (1-5): "))
return choice
# Function to perform the selected operation
def perform_operation(x, y, choice):
if choice == 1:
result = x + y
operation = "Addition"
elif choice == 2:
result = x - y
operation = "Subtraction"
elif choice == 3:
result = x * y
operation = "Multiplication"
elif choice == 4:
if y != 0:
result = x / y
operation = "Division"
else:
return "Error: Division by zero is not allowed."
elif choice == 5:
power_choice = int(input("Choose power operation:\n1. x^y\n2. y^x\nEnter your choice (1-2): "))
if power_choice == 1:
result = x ** y
operation = "Power (x^y)"
elif power_choice == 2:
result = y ** x
operation = "Power (y^x)"
else:
return "Error: Invalid power choice."
else:
return "Error: Invalid choice."
return f"{operation} Result: {result}"
# Main function to execute the script
def main():
try:
x = int(input("Enter the first number (x): "))
y = int(input("Enter the second number (y): "))
choice = display_menu()
result = perform_operation(x, y, choice)
print(result)
except ValueError:
print("Error: Please enter valid integers.")
# Run the main function
if __name__ == "__main__":
main()
Answer for Question 3:
# Step 1: Create a tuple of size 6
a = (1, 2, 3, 4, 5, 6)
# Step 2: Convert the tuple to a list
b = list(a)
# Step 3: Insert a member at the second position (index 1)
b.insert(1, 'new_member')
# Output the result
print(b)
Answer for Question 4:
# Function to generate a dictionary based on user input
def generate_dictionary():
# Initialize an empty dictionary
my_dict = {}
# Ask the user for the number of entries they want to create
num_entries = int(input("How many key-value pairs do you want to add to the dictionary? "))
# Loop to get key-value pairs from the user
for i in range(num_entries):
# Get a number for the key
while True:
try:
key = int(input(f"Enter key {i + 1} (a number): "))
break # Exit loop if input is valid
except ValueError:
print("Invalid input. Please enter a valid number for the key.")
# Get a string for the value
value = input(f"Enter value {i + 1} (a string): ")
# Add the key-value pair to the dictionary
my_dict[key] = value
# Print the generated dictionary
print("\nGenerated Dictionary:")
print(my_dict)
# Call the function to execute the script
generate_dictionary()
Answer for Question 4:
def count_letters_and_digits(sentence):
letters_count = 0
digits_count = 0
for char in sentence:
if char.isalpha(): # Check if the character is a letter
letters_count += 1
elif char.isdigit(): # Check if the character is a digit
digits_count += 1
return letters_count, digits_count
# Main function to run the script
def main():
user_input = input("Please enter a sentence: ")
letters, digits = count_letters_and_digits(user_input)
print(f"Number of letters: {letters}")
print(f"Number of digits: {digits}")
# Run the script
if __name__ == "__main__":
main()
Answer for Question 5:
def count_letters_and_digits(sentence):
letter_count = 0
digit_count = 0
for char in sentence:
if char.isalpha(): # Check if the character is a letter
letter_count += 1
elif char.isdigit(): # Check if the character is a digit
digit_count += 1
return letter_count, digit_count
def main():
# Accept a sentence from the user
user_input = input("Please enter a sentence: ")
# Calculate the number of letters and digits
letters, digits = count_letters_and_digits(user_input)
# Display the results
print(f"Number of letters: {letters}")
print(f"Number of digits: {digits}")
if __name__ == "__main__":
main()
Answer for Question 6:
def create_username():
attempts = 3
while attempts > 0:
username = input("Please create a username (5-10 characters): ")
if 5 <= len(username) <= 10:
print(f"Username '{username}' created successfully!")
return username
else:
attempts -= 1
print(f"Invalid username. You have {attempts} attempt(s) left.")
print("Session Terminated")
return None
# Run the function
create_username()
Answer for Question 7:
import string
def is_valid_password(password):
# Strip any leading or trailing whitespace
new_password = password.strip()
# Check length
if not (6 <= len(new_password) <= 15):
return False
# Initialize flags for character types
has_upper = False
has_lower = False
has_digit = False
has_special = False
# Define special characters
special_characters = {'@', '#', '&', '%', '$'}
# Check for spaces
if ' ' in new_password:
return False
# Iterate through each character in the password
for char in new_password:
if char.isupper():
has_upper = True
elif char.islower():
has_lower = True
elif char.isdigit():
has_digit = True
elif char in special_characters:
has_special = True
# Return True only if all conditions are satisfied
return has_upper and has_lower and has_digit and has_special
# Example usage:
passwords_to_test = ["Password1@", "passW1@", "Pass1$", "P@ssword", "P@ss 1", "Short1@",
"VeryLongPassword123$"]
for pwd in passwords_to_test:
print(f"'{pwd}' is valid: {is_valid_password(pwd)}")
Answer for Question 8:
1. Using for loop:
# Example list
my_list = [10, 20, 30, 40, 50, 60]
# Printing elements at even positions using a for loop
print("Elements at even positions:")
for i in range(0, len(my_list), 2): # Start from index 0 and step by 2
print(my_list[i], end=' ')
2. Using for while loop:
# Example list
my_list = [10, 20, 30, 40, 50, 60]
# Printing elements at even positions using a while loop
print("\nElements at even positions:")
i=0
while i < len(my_list):
print(my_list[i], end=' ')
i += 2 # Increment by 2 to get the next even index