# In this example we'll have a look at basic Python functionality including
# lists, list comprehension and functions
list = [1, 2, 3, 4] # we create a list containing the numbers from 1 to 4
# We would like to multiply all the values in the list by a constant and create
# a new list
# For this, we define a function to multiply all values in list by a constant n
def multiply_by_n(list, n):
new_list = []
for number in list: # iterate over all elements in list
new_list.append(number * n) # add number multiplied with n to new_list
return new_list
multiplied_by_three = multiply_by_n(list, 3)
# We can use .format() to format strings: We just pass the values we want inserted
# at the placeholders {} to the function
print('{} multiplied by three is {}'.format(list, multiplied_by_three))
# A way better way to do this sort of operation is list comprehension:
another_multiplied_by_three = [number * 3 for number in list]
print('{} multiplied by three is {}'.format(list, another_multiplied_by_three))
# Imagine we run an online store offering fruit. We would like to define the
# prices for the fruit in our stock and create a function for calculating the
# total price for all items in the shopping cart
# For creating the list of prices, we can use a Python dictionary.
# In a dictionary, each entry consists of a key and a value. For our purposes,
# we'll use the name of the fruit as key and the price as value
price_list = {'apple': 3, 'grapes': 1.5, 'pineapple': 2, 'banana': 2.4}
# We can access elements in the dictionary like this:
apple_price = price_list['apple']
print(apple_price)
# We put the items we want to buy in a list
shopping_cart = ['apple', 'banana', 'grapes']
def calculate_total(products, prices):
# We can use list comprehension to get the price for each of the products
# in our shopping cart
product_prices = [prices[product] for product in products]
total = sum(product_prices)
return total
print('The total is {}'.format(calculate_total(shopping_cart, price_list)))