Functions and Lists
Functions
def greet(name):
return f"Hello, {name}!"
print(greet("Alice")) # "Hello, Alice!"
def add_numbers(a, b=0):
return a + b
print(add_numbers(5, 3)) # 8
print(add_numbers(5)) # 5
List Methods
fruits = ["apple", "banana"]
fruits.append("cherry") # add to end
fruits.insert(1, "mango") # insert at index 1
fruits.remove("banana") # remove item
fruits.sort() # sort alphabetically
fruits.pop() # remove and return last item
len(fruits) # length of listExample
# Shopping List App
shopping = []
# Add items
shopping.append("Rice")
shopping.append("Beans")
shopping.append("Oil")
shopping.append("Tomatoes")
shopping.append("Onions")
print("Shopping List:")
for i, item in enumerate(shopping, 1):
print(f" {i}. {item}")
# Remove an item
shopping.remove("Oil")
print(f"
After removing Oil: {shopping}")
# Function to find most expensive
def most_expensive(prices):
items = list(prices.keys())
costs = list(prices.values())
max_idx = costs.index(max(costs))
return items[max_idx]
prices = {"Rice": 1500, "Beans": 800, "Tomatoes": 500}
print(f"Most expensive: {most_expensive(prices)}")
Exercises
Exercise 1. Write a double Function
Medium
Write a function double(x) that returns x multiplied by 2.
Use exactly: def double(x): and return x * 2
Use exactly: def double(x): and return x * 2
# your code here
Expected Output
double(4) == 8