mkdir lab08
cd lab08
idle3
# Function to sum list
def sum_list(numbers):
total = 0
for num in numbers:
total += num
return total
# Sample list
my_list = [2, 4, 6, 7, 5]
# Output result
print("Sum:", sum_list(my_list))
Expected Output: 24
# Function to get unique elements
def unique_list(lst):
return list(set(lst))
# Input list
input_list = [2, 2, 3, 4, 3, 5, 5, 6, 7, 3, 7]
# Get unique list
result = unique_list(input_list)
# Output
print("Original List:", input_list)
print("Unique List:", result)
Note: set removes duplicates.
# Function to remove two items
def remove_items(lst):
new_list = lst.copy()
if len(new_list) >= 2:
new_list.pop()
new_list.pop()
return new_list
# Create list interactively
user_list = input("Enter numbers separated by space: ").split()
user_list = [int(x) for x in user_list]
# Process list
modified_list = remove_items(user_list)
# Output
print("Original List:", user_list)
print("Modified List:", modified_list)
def check_even_odd(num):
if num % 2 == 0:
print(f"The value {num} is an even number")
else:
print(f"The value {num} is an odd number")
while True:
try:
num = int(input("Enter a number (111 to exit): "))
if num == 111:
print("Goodbye!")
break
check_even_odd(num)
except ValueError:
print("Invalid input! Please enter a number.")
Key Concept: Exception handling using try/except.
def find_max(a, b, c):
return max(a, b, c)
while True:
try:
a = int(input("Enter first number (555 to exit): "))
if a == 555:
print("Program terminated.")
break
b = int(input("Enter second number: "))
c = int(input("Enter third number: "))
print("Max value is:", find_max(a, b, c))
except ValueError:
print("Invalid input! Please enter numbers only.")
# Function to modify tuple
def modify_tuple(tpl, value):
# Convert tuple to list (tuples are immutable)
temp = list(tpl)
# Insert value at index 4
temp.insert(4, value)
# Append first 3 elements
temp.extend(tpl[:3])
return tuple(temp)
# Sample tuple
original_tuple = (2, 4, 6, 7, 5, 4, 9, 8)
# Modify tuple
new_tuple = modify_tuple(original_tuple, "var")
# Output
print("Original Tuple:", original_tuple)
print("Modified Tuple:", new_tuple)
Expected Output:
(2, 4, 6, 7, var, 5, 4, 9, 8, 2, 4, 6)
Key Concept:
insert() and extend() used for modification