Chapter 1!

These are called cells. There are 2 types of cells: code and text. We can add more cells by clicking the + buttons above!

In a code cell you can type some code and then you execute the code by pressing Shift + Enter

In a text cell you can also format text! Sub text here!

Sub-Header

Sub-Sub-Header

2+2
4
2+2
4+4
8
print(2+2)
print(4+4)
4
8
print('hello world!')
hello world!
print('hello world',2+2,'this is python')
hello world 4 this is python
print('hello world',2+2,'this is python',sep='')
hello world4this is python
# everything to the right of a # is not run as code, this is called a comment!
2+2 # this is adding two plus two
4
# we can add strings together!
print('hello'+'world')
helloworld
print('hello ' + ' world')
hello  world
print('hello'+'world', sep = " ")
helloworld
# print('hello'+5)

A mobile store MobiWorld sells different mobile phones to customers. For each order that is placed, the store keeps a record of various attributes related to the mobile, like Price, Brand, RAM (GB), and Internal Storage (GB).

Let’s learn Python using the context of the store’s data.

1.1 Intro to Variables

First, we have to store our data to a variable that can be used to extract the stored information later. Let’s take an example of how we can do that in Python.

Q. Suppose the store sold an Apple iPhone (4GB, 128GB) for $900. Store this information in the variables price, brand, ram, and storage.

# store the price (in dollars) of the mobile in variable 'price'
price = 900
# print the value saved in the variable 'price'
print('The price of the mobile is $',price,sep='')
The price of the mobile is $900
#Also, you can add f'
print(f'The price of the mobile is ${price}')
The price of the mobile is $900
# store the brand name of the mobile in variable 'brand'.
brand = 'Apple' # Here we are storying a string
# print the value saved in the variable 'brand'
print('The brand of the mobile is',brand)
The brand of the mobile is Apple
# store the RAM (in GB) of the mobile in variable 'ram'.
ram = 4
# print the value saved in the variable 'ram'
print('The RAM of the mobile is', ram,'GB')
The RAM of the mobile is 4 GB
# store the internal storage (in GB) of the mobile in variable 'storage'.
storage = 128
# print the value saved in the variable 'Memory'
print('The internal storage of the mobile is', storage, 'GB')
The internal storage of the mobile is 128 GB

Q. Let’s say the store wants to save the information on the billing status of the above phone in a boolean variable. Write the code in Python to implement the same.

# a special type of variable stores just True/False values.  This is called a boolean variable.
# create a boolean variable 'is_billed' to save the billing information
is_billed = True #Note True is in blue. TRUE and False are special type of objects in Pyrtohn
print(is_billed)
True

The value that we store in a variable can be a number or a set of characters or a boolean variable (True/False). For example, a price is a number while the brand name is a set of characters which is also known as a string in python. Whenever we store a value in a variable, Python automatically assigns a data type to that variable based on the value. It also allows us to check the data type of the variable.

Q. Check the data type of the variables price, brand, ram, and storage

# check the data-type using the type function
type(price)
int
# check the data-type using the type function
type(brand)
str
# check the data-type using the type function
type(ram)
int
# check the data-type using the type function
type(storage)
int
# check the data-type using the type function
type(is_billed)
bool

Q. Let’s say a customer buys two Apple iPhones (4GB, 128GB) at a price of $900 each. What will be the total bill that the customer has to pay?

# calcuate the total bill and store it in variable 'bill'
bill = price + price
# the same result can be achieved by multiplication.
bill = price*2
print('The bill amount is $',bill,sep='')
The bill amount is $1800

Q. Let’s say the store provides a discount of $15 dollars on the Apple iPhone (4GB, 128GB) that costs $900. What will be the price of the iPhone after the discount?

# store the price (in dollars) of the mobile in variable 'price'
price = 900
# store the discount amount in variable 'discount'
discount = 15
# calculate the discounted price
price_after_discount = price - discount
print('The price of the iPhone after the discount is $',price_after_discount,sep='')
The price of the iPhone after the discount is $885

Q. Let’s say a customer buys two Apple iPhones (4GB, 128GB) and pays a total bill of $1800. Write the Python code to find the price of an Apple iPhone.

# store the bill (in dollars) of the two mobiles in variable 'bill'
bill = 1800
# calculate the price of one mobile
price = bill / 2
print('The price of an Apple iPhone is $',price,sep='')
The price of an Apple iPhone is $900.0

Q. Let’s say a customer buys x numbers of Apple iPhones (4GB, 128GB) for $900 each. The total bill that the customer pays is $3600. Write the Python code to find the value of x.

# store the bill (in dollars) of the mobile in variable 'bill'
bill = 3600
# store the price (in dollars) of the mobile in variable 'price'
price = 900
# calculate the number of iPhones that the customer buys
x = bill // price # The // rounds the value to the nearest integer, while / will make it a float
# double divided forces the answer to be an integer!
print('The customer buys', x, 'Apple iPhones')
The customer buys 4 Apple iPhones

Q. Suppose the store plans to provide a 4.5% discount on the Apple iPhone. What will be the discounted price of the mobile?

Type Conversion: The process of converting one data type to another data type is called type conversion.

In Python, we can perform two types of type conversion.

  1. Implicit Type Conversion - Here, Python automatically converts one data type to another in order to avoid data loss.

  2. Explicit Type Conversion - Here, the user can convert the data type of a variable to the required data type by using the in-built functions int(), float(), str(), etc.

# store the price (in dollars) of the mobile in variable 'price'
price = 900
# calculate the discount amount
discount = price * 0.045
# calculate the discounted price
discounted_price = price - discount
print('The discounted price of the iPhone is ' + str(discounted_price))
The discounted price of the iPhone is 859.5
type(discounted_price)
float

Now, let’s check the data type of the variables ‘discount’ and ‘price’

print('The data type of variable price is',type(price))
print('The data type of variable discount is',type(discount))
The data type of variable price is <class 'int'>
The data type of variable discount is <class 'float'>

As we can see, the data type of ‘discount’ is float as Python is implicitly converting the lower data type to a higher data type to avoid data loss.

Suppose we want to add the variables brand, ram, and storage.

Will the implicit conversion work?

Let’s try it!

# print(brand + ' ' + ram + 'GB')

As we can see from the output, the TypeError is being raised which indicates that Python is not able to use Implicit Conversion in such conditions.

But, we can do an explicit conversion for such cases.

type(brand)
str
type(ram)
int
# Let´s try this
print(brand, ram, "GB")
Apple 4 GB

Or using explicit type conversion

brand + ' ' + str(ram) + 'GB' #We can add string variables together!
'Apple 4GB'
#a="Hi"
#b=int(a)
#type(b)

1.2 Data Structures

MobiWorld store has provided a snapshot of the details of mobile phones sold by them.

Brand RAM (in GB) Memory (in GB) Price (in dollars)
Apple 4 128 900
Samsung 12 128 899
LG 8 64 600
Apple 8 128 1000

We know how to create a variable to store the brand name.

Brand = 'Apple'
print(Brand)
Apple

List

Let’s create a variable that will store all the brand names given in the above table. This can be achieved using the ‘list’ data struture in Python.

Lists are used to store the data items inside square brackets [] where each data item is separated by a comma (,)

# create a list
brand_list = ['Apple', 'Samsung', 'LG', 'Apple']
brand_list
['Apple', 'Samsung', 'LG', 'Apple']
# check the type of the variable 'brand_list'
type(brand_list)
list

Let’s create lists for other attributes as well.

ram_list = [4, 12, 8, 8]
storage_list = [128, 128, 64, 128]
price_list = [900, 899, 600, 1000]
# let's print the lists we created
print('RAM List:', ram_list)
print('Storage List:', storage_list)
print('Price List:', price_list)
RAM List: [4, 12, 8, 8]
Storage List: [128, 128, 64, 128]
Price List: [900, 899, 600, 1000]

Now, we have created lists for all attributes with the provided data. There are various operations that can be performed on lists to extract information from the data. Let’s understand a few important methods by answering some questions.

Q. How many records are stored in the list brand_list?

  • len() is an in-built function in Python that provides the count of elements inside a list. In-built functions are functions that are already defined in the Python framework to perform a task.
len(brand_list)
4
print(brand_list)
['Apple', 'Samsung', 'LG', 'Apple']

We have 4 records

Q. Find the minimum and maximum price among the mobile phones sold by the store.

  • min() and max() are in-built functions in Python that calculates the minimum and maximum values among the items in a list (or some other data types).
# minimum price
min_price = min(price_list)
print('The minimum price is $' + str(min_price))
# maximum price
max_price = max(price_list)
print('The maximum price is $' + str(max_price))
The minimum price is $600
The maximum price is $1000
  • The minimum and maximum prices are $600 and $1000 respectively.

As a list may contain a large number of items in it, there should be a way to access the item that we want. This is achieved by indexing the list to access the required item.

Q. Print the third item in the list ram_list.

  • Indexing in list is done by specifying the index inside square brackets. In python, indexing starts with 0. That is, the first item has the index 0, the second has the index 1 and so on.
# indexing to get the third item in ram_list
print(ram_list[2])
8
ram_list[2]
8

Q. Print the first three items from the list price_list.

  • We can also select a range of indices to access more than 1 item. This can be done by using a colon (:) between the start and stop index
# first three items in price_list
print(price_list[0:3])
[900, 899, 600]

Notice that in such an indexing, the output includes the item at the start index (index 0) but excludes the item at the stop index (index 3). The index [0:3] has included the items at indices 0, 1 and 2

print(price_list)
[900, 899, 600, 1000]

Q. Print the last item in the list brand_list.

  • The last item can also be accessed using its index. But, if the list is too large, counting the index for the last item may not be the best way. Here’s how the last item can be accessed for any list.
# last item in brand_list
print(brand_list[-1])
Apple
print(brand_list)
['Apple', 'Samsung', 'LG', 'Apple']

The Store finds out that for the last record in the data, the brand name provided was not correct.

Q. Remove the last element from the list brand_list.

  • pop() is a list method that removes the item at the given index and returns the removed item . If the index is not specified, by default, it removes the last element. To confirm we can check the list again.
brand_list.pop()
'Apple'
brand_list
['Apple', 'Samsung', 'LG']

As we can see the last element got removed. Now, the Store informs that the correct brand name should be “Motorola’.

Q. Insert ‘Motorola’ to the list brand_list

  • The append() method adds a single item to an existing list.
brand_list.append('Motorola')
brand_list
['Apple', 'Samsung', 'LG', 'Motorola']
brand_list[3] = 'Apple'
print(brand_list)
['Apple', 'Samsung', 'LG', 'Apple']
brand_list[3] = 'Motorola'
brand_list
['Apple', 'Samsung', 'LG', 'Motorola']

We have succesfully corrected the list now.

Tuple

Now that you have learned about lists, you know that data can be modified and altered in a list, making it a mutable data structure. Sometimes, you might want to store data which should not be altered, for example storage. The storage in a mobile phone is in terms of powers of 2, that is, 32 GB, 64 GB, 128 GB, etc. You do not want to alter the number 32 and change it to 30.

Q. Store the storage specifications 32/64/128/256 as an immutable variable.

storage = (32,64,128,256)
print(storage)
(32, 64, 128, 256)
type(storage)
tuple
  • The above data structure structure is called a tuple. A tuple in Python is similar to a list. The difference between the two is that unlike lists we cannot change the elements of a tuple once it is assigned. While list are defined using [ ], tuples are definded using ( ).

Indexing in tuple is similar to indexing in lists.

Q. Print the second item in the tuple storage

print(storage[1])
64

Let’s try changing the second item to 60 and see if it works.

# try changing an item in a tuple
# storage[1]=60
X = (20,23,-50,5.6,98)
print(X[2:-1])
(-50, 5.6)

As can be seen from the TypeError, items cannot be altered in a tuple.

Dictionary

Lists are great for storing data for a single attribute. But, we might want to add more information about the items in a variable. Suppose the store wants to store the attributes brand, ram, storage, and price in a single variable.

Q. Store the attributes of an Apple iPhone (4GB, 128GB) of price of $800 in a single variable.

# creating a dictionary
attributes = {
    'Brand':'Apple',
    'RAM (in GB)':4,
    'Storage (in GB)':128,
    'Price (in $)':800
    }
print(attributes)
{'Brand': 'Apple', 'RAM (in GB)': 4, 'Storage (in GB)': 128, 'Price (in $)': 800}
type(attributes)
dict
  • The above data structure is called a dictionary. Dictionaries are used to store data values in key:value pairs. Dictionaries are written with curly brackets {}, and have keys and values. Keys must be unique.

Q. Extract the price from the dictionary attributes.

# extract information from dictionary
print(attributes['Price (in $)'])
800
attributes['Price (in $)']
800
  • For the above pair, ‘Price (in $)’ is the key and 800 is the value.

Dictionary items are ordered, changeable, and does not allow duplicates.

Q. Change the price in attributes to 900

attributes['Price (in $)'] = 900
print(attributes)
{'Brand': 'Apple', 'RAM (in GB)': 4, 'Storage (in GB)': 128, 'Price (in $)': 900}

Now, that you have learned how to create a dictionary, let’s store data for multiple mobile phones in it. The values in a dictionary can also be a list to store information for more than one product.

Q. Create a dictionary products for storing the attributes of 4 different mobile phones.

# creating a dictionary for storing data.
products = {
    'Brand':brand_list,
    'RAM (in GB)':ram_list,
    'Storage (in GB)':storage_list,
    'Price (in $)':price_list
    }
print(products)
{'Brand': ['Apple', 'Samsung', 'LG', 'Motorola'], 'RAM (in GB)': [4, 12, 8, 8], 'Storage (in GB)': [128, 128, 64, 128], 'Price (in $)': [900, 899, 600, 1000]}

Using a dictionary, we have stored a lot of information in a single variable.

Q. Extract the keys and values from the dictionary products

  • keys() and values() are methods of a dictionary to extract the lists of dictionary keys and dictionary values respectively.
# keys of a dictionary
keys = products.keys()
print('The keys of the dictionary are :\n',keys)
# values of a dictionary
values = products.values()
print('The values of the dictionary are :\n', values)
The keys of the dictionary are :
 dict_keys(['Brand', 'RAM (in GB)', 'Storage (in GB)', 'Price (in $)'])
The values of the dictionary are :
 dict_values([['Apple', 'Samsung', 'LG', 'Motorola'], [4, 12, 8, 8], [128, 128, 64, 128], [900, 899, 600, 1000]])
products['RAM (in GB)'][1]
12
products['RAM (in GB)']
[4, 12, 8, 8]
dictionary={1:"USA", 2:"India", 3:"China"}
dictionary.update({3:"Japan"})
print(dictionary)
{1: 'USA', 2: 'India', 3: 'Japan'}
dictionary={1:"USA", 2:"India", 3:"China"}
dictionary.pop(2)
print(dictionary)
{1: 'USA', 3: 'China'}

1.3 Conditional Statements

Suppose a customer is planning to buy a mobile phone but has a limited budget. Thus, his decision to buy is based on the condition that the price comes under his budget. Let’s say his budget is $600.

Q. Write a code in Python that prints whether the customer can buy the iPhone or not based on his budget.

Sometimes we want to execute a block of code based on a particular condition. In these types of situations, we write conditional statements.

The if-else statement in Python can be used for decision-making. The general syntax of an if-else statement is:

if (test expression):
    Body of if
else:
    Body of else

Python is a tabbed based language, so we need to be VERY careful about tabs!!!

print(price)
900

The input function prompts the user to give a value.

# define the budget price
budget = int(input('Enter your budget(in dollars): '))

# if-else statement
if price <= budget:
  print('Congrats! You can buy the Iphone')
else:
  print('Sorry! The mobile price is more than your budget')
Enter your budget(in dollars): 1000
Congrats! You can buy the Iphone

If there are multiple conditions, we may use another conditional statement called if-elif-else statement. The general syntax of the if-elif-else statement is:

if (test expression):
    Body of if
elif (test expression):
    Body of elif
else:
    Body of else

Q. Suppose the price of the 32 GB, 64 GB, and 128 GB iPhones are $600, $700, and $900 respectively. Write a conditional statement to print the price based on the internal storage of the phone.

Memory = int(input('Enter the memory: '))

if Memory == 32:
  print('The price of the phone is $600')
elif Memory == 64:
  print('The price of the phone is $700')
elif Memory ==128:
  print('The price of the phone is $900')
else:
  print('Please enter a valid memory requirement')
Enter the memory: 32
The price of the phone is $600
a = b = "TRUE"
if (a == b):
  print("Hello")
else:
  print("Well done")
Hello

1.4 Looping Statements

Suppose the store wants to check the price of the Apple iPhone (4GB, 128GB) after providing 5%, 10%, 15%, and 20% discounts respectively. Instead of calculating the discounted prices multiple times, looping statements can be used to achieve this.

Q. Write a code in Python that prints the discounted price for each of the above-mentioned discounts.

Before jumping into the concept of looping, let’s have a look at the range() function in Python.

The range() method returns an immutable sequence of numbers between the given start integer to the stop integer.

print(range(6))
range(0, 6)
print(list(range(6)))
[0, 1, 2, 3, 4, 5]
print(list(range(2,6)))
[2, 3, 4, 5]
print(list(range(6, 14, 2)))
[6, 8, 10, 12]

Loops are used in Python to iterate over a sequence.

The syntax of the ‘for loop’ is:

for iterator_var in sequence:
    statements(s)
# store the price (in dollars) of the mobile in variable 'Price'.
price = 900
# start the for loop
for i in range(5, 21, 5):
  # calculate the discount amount
  discount = price * (i / 100)
  # calculate the discounted price
  discounted_price = price - discount
  # print the discounted price
  print('The price after providing ', i, ' percent discount is $', discounted_price,sep='')
The price after providing 5 percent discount is $855.0
The price after providing 10 percent discount is $810.0
The price after providing 15 percent discount is $765.0
The price after providing 20 percent discount is $720.0

We can also use the while loop to iterate over a sequence. The syntax of the ‘while loop’ is:

while condition:
    statements(s)

Let’s try to solve the above question using ‘while’ loops.

# store the price (in dollars) of the mobile in variable 'Price'.
Price = 900
# set the value of i to 5
i = 5
# start the while loop
while i <= 20:
  # calculate the discount amount
  discount = Price * (i / 100)
  # calculate the discounted price
  discounted_price = Price - discount
  # print the discounted price
  print('The price after providing ',i, ' percent discount is $', discounted_price,sep='')
  # increase the value of i by 5
  i += 5
The price after providing 5 percent discount is $855.0
The price after providing 10 percent discount is $810.0
The price after providing 15 percent discount is $765.0
The price after providing 20 percent discount is $720.0
i
25

This is interesting. Look at the indented characteristics of the following for-loops:



sum = 0
for number in range(1,5):
    sum = sum + number
    print(sum)
1
3
6
10
sum = 0
for number in range(1,5):
    sum = sum + number
print(sum)
10

while x: This is the start of a while loop. The condition x in the while loop checks whether the list x is empty or not. As long as there are elements in the list, the loop will continue to execute.



x = [1, 2, 3, 4, 5]
while x:
  print(x.pop(0))
1
2
3
4
5

1.5 List Comprehensions

MobiWorld has decided to provide an instant discount of 5% on all their products during the upcoming sale. We want to check the discounted prices of the products.

We already have the price_list with us. Let’s use it to get the discounted prices.

One way of creating a discounted price list is by looping over the elements of price_list, subtracting the discount from the price, and adding it one at a time to a new list discounted_price_list.

print(price_list)
type(price_list)
[900, 899, 600, 1000]
list
discounted_price_list=[]

for x in price_list:
  discounted_price = x - (x*(5/100))
  discounted_price_list.append(discounted_price)

print(discounted_price_list)
[855.0, 854.05, 570.0, 950.0]

An equivalent way of obtaining the same result is by using list comprehensions.

  • List comprehension is a type of control structure for creating a list from an existing iterable (like tuples, strings, arrays, lists, etc).
  • They offer a shorter and more appealing syntax and are often faster than explicit for loops in creating a list from an existing iterable.
discounted_price_list = [x - (x*(5/100)) for x in price_list]
print(discounted_price_list)
[855.0, 854.05, 570.0, 950.0]

Let’s breakdown the syntax of the above list comprehension. There are three parts: 1. [ ]: The outer square brackets tells that we are creating a list 2. x-(x*(5/100): The expression to evaluate or the computation to perform 3. for x in price_list: The iterable from which elements (x) will be fetched

Customers often want to check whether any of the discounted prices during the sale are within their budget.

Let’s help the store display the same based on the budget mentioned by the customer by comparing the discounted price with the budget for each of the four mobile phone prices.

# asking for customer's budget
budget = int(input('Enter your budget(in dollars): '))

# creating a list of Yes/No based on budget and discounted prices
within_budget = ['Yes' if x <= budget else 'No' for x in discounted_price_list]
print(within_budget)
Enter your budget(in dollars): 600
['No', 'No', 'Yes', 'No']

To get more clarity on the way the list comprehension syntax is formulated, we can expand the list comprehension to the usual for and if statements and think of this in a reversed way.

within_budget = []

for x in discounted_price_list:
  if x <= budget:
    within_budget.append('Yes')
  else:
    within_budget.append('No')

print(within_budget)
['No', 'No', 'Yes', 'No']


week_list = [ "Week" + str(i) for i in range(5)]
print(week_list)
['Week0', 'Week1', 'Week2', 'Week3', 'Week4']

1.6 Functions in Python

What is a Function in Python?

In Python, a function is a block of instructions that performs a specific task.

We have already seen a few functions in python. min and max were functions that found the minimum and maximum numbers in a list!

In Python, we can also define our own functions! We don’t have to rely on the ones that are already there.

Functions break the program into modular chunks which can be reused later. Functions are used to make the program more organized and manageable.

Syntax of a function

Functions that users define themselves to a particular task are referred to as user-defined functions.

def function_name(parameters):
    '''explain what a function does'''
    statement(s)

Let’s say the store wants to market the Apple iPhone by displaying its attributes to each customer.

Q. Write a function in Python that displays the attributes of the Apple iPhone.

# write the function
def display_iphone_attributes():
    """
    This function displays
    the stored attributes of
    the Apple iPhone
    """
    # store the price (in dollars) of the mobile in variable 'price'
    price = 900
    # store the RAM (in GB) of the mobile in variable 'ram'.
    ram = 4
    # store the internal storage (in GB) of the mobile in variable 'storage'.
    storage = 128
    # display the details
    print('The Apple iPhone has ', ram, ' GB RAM and ', storage, ' GB internal storage and it costs $', price, sep='')

How to call a function in python?

Once the function is defined, we can simply call the function by writing the function name with appropriate parameters. The function definition must always be written before the function call. Else, we will get an error.

# call the function
display_iphone_attributes()
The Apple iPhone has 4 GB RAM and 128 GB internal storage and it costs $900

How to write a Python function with arguments?

In Python, you can also define a function that takes a variable number of arguments. Let’s try an example!

Q. Write a function in Python that displays the attributes of a phone.

# write the function
def display_phone_attributes(brand, price, ram, storage):
    """
    This function displays
    the stored attributes of
    any phone
    """
    # display the details
    print('The ', brand, ' phone has ', ram, ' GB RAM and ', storage,' GB internal storage and it costs $',price,sep='')
# call the function
display_phone_attributes('samsung', 899, 12, 128)
The samsung phone has 12 GB RAM and 128 GB internal storage and it costs $899

Since we have called the function with the appropriate number of arguments, it runs smoothly without any error. The interpreter will show an error message in case we call it with a different number of arguments.

Let’s try calling the function with 3 arguments.

# call the function with 3 arguments
display_phone_attributes('samsung', 899, 12)
TypeError: ignored

What is a return statement?

The return statement is used to exit a function and also returns the output.

Q. Write a function in Python that takes the discount percentage as input and returns the discounted price of an Apple iPhone.

# write the function
def dis_price(discount):
    """
    This function takes the discount
    percentage as input and
    returns the discounted price of Apple iPhone
    """
    # store the price (in dollars) of the mobile in variable 'price'
    price = 900
    # calculate the price after discount
    discounted_price = price - price * (discount / 100)
    # return the discounted price
    return discounted_price
# call the function with discount = 10%
dp = dis_price(10)
dp
810.0

In Python, lambda function are functions a different way to define a function

  • User-defined functions are defined using the def keyword, whereas lambda functions are defined using the lambda keyword.
  • We generally use them when we require an anonymous function for a small task
  • We cannot use a return statement with lambda functions.

Let’s try to get the discounted price using lambda function.

# lambda functions
dis_price_lambda = lambda discount : 900 - ( 900 * (discount / 100) )
# call the function with discount = 10%
dis_price_lambda(10)
810.0

Interesting feature. It can print the string two times:



def say(message, times):
    print(message*times, sep='')
say("How are you", 2)
How are youHow are you
mul = lambda a,b: return a*b
mul(5,6)
SyntaxError: ignored

We cannot use a return statement with lambda functions.



(lambda x: (x+2)*5/2)(4)
15.0

Note that we can give the argument value (4) in the definiton of the function itself

1.7 *args and **kwargs

A customer has placed an order for 5 mobile phones with MobiWorld. The store wants to generate the total amount for the order.

We can define a function with 5 arguments (one each for the price of the mobile phone ordered) to compute the total amount.

def total_amount(price1, price2, price3, price4, price5):
    """
    This function takes the price of five phones ordered
    and returns the total order amount.
    """
    # computing the total order amount
    total = price1 + price2 + price3 + price4 + price5

    # return the total amount
    return total
print('Total order amount:', total_amount(700, 599, 650, 900, 820))
Total order amount: 3669

This works as we have a small number of items in the order placed. What if the customer decides to add 5 more phones to his order? It will become tedious to keep adding an argument to the function for each new addition.

  • In some cases, we might not even want any constraints on the number of arguments for the function.

Python allows us flexibility in terms of the number of arguments passed to a function by using *args.

def total_amount(*args):
    """
    This function takes the prices of phones ordered
    and returns the total order amount.
    """
    total = 0
    # computing the total order amount
    for arg in args:
        total += arg

    # return the total amount
    return total

Let’s compute the total amount for 5 phones.

print('Total order amount:', total_amount(700, 599, 650, 900, 820))
Total order amount: 3669

Now, let’s compute the total amount for 10 phones.

print('Total order amount:', total_amount(700, 599, 650, 900, 820, 630, 520, 799, 999, 840))
Total order amount: 7457

We can also use any other text in place of args.

def total_amount(*prices):
    """
    This function takes the prices of phones ordered
    and returns the total order amount.
    """
    total = 0
    # computing the total order amount
    for price in prices:
        total += price

    # return the total amount
    return total
print('Total order amount:', total_amount(700, 599, 650, 900, 820, 630, 520, 799, 999, 840))
Total order amount: 7457

Till now, the arguments we have passed to our functions have been declared by names only, like brand, ram, price1. These types of arguments are called positional arguments.

Another type of argument in Python is called keyword argument, which is declared using both a name and a default value.

Let us consider the festive season sale, where the store is offering a discount of 5% on all its products. Outside the sale period, there will be no discount for the products.

Let’s create a new function to compute the total discounted price for an order of one or more phones placed by a customer.

def total_discounted_amount(*prices, discount=0.0):
    """
    This function takes the prices of phones ordered
    and the discount percentage
    and returns the total discounted order amount.
    """
    total = 0
    # computing the total order amount
    for price in prices:
        total += price

    total_discounted_price = total - discount*total

    # return the total amount
    return total_discounted_price
print('Total discounted order amount:', total_discounted_amount(700, 599, 650, 900, 820, 630, 520, 799, 999, 840))
Total discounted order amount: 7457.0

The discount percentage during the festive season sale will be 5%, which we can specify by setting the keyword argument discount to 0.05.

print('Total discounted order amount (during festive season):', total_discounted_amount(700, 599, 650, 900, 820, 630, 520, 799, 999, 840, discount=0.05))
Total discounted order amount (during festive season): 7084.15

Note: In Python, keyword arguments should be declared after the positional arguments.

def total_discounted_amount(discount=0.0, *prices):
    """
    This function takes the prices of phones ordered
    and the discount percentage
    and returns the total discounted order amount.
    """
    total = 0
    # computing the total order amount
    for price in prices:
        total += price

    total_discounted_price = total - discount*total

    # return the total amount
    return total_discounted_price
print('Total discounted order amount (during festive season):', total_discounted_amount(discount=0.05, 700, 599, 650, 900, 820, 630, 520, 799, 999, 840))
SyntaxError: ignored

If we assign a value to a positional argument, it becomes a keyword argument. Since it is followed by positional arguments, we get a SyntaxError.

Just like *args helped us remove the constraint on the number of positional arguments, **kwargs helps us remove the constraint on the number of keyword arguments.

The **kwargs argument passed while calling the function must be a mapping, such as a dictionary.

MobiWorld has decided to offer a $5 cashback on all the products on top of the 5% discount for the last day of the festive season sale. Let’s create a function to compute the customer’s net spend.

def customer_net_spend(*prices, discount=0.0, **kwargs):
    """
    This function takes the prices of phones ordered,
    the discount percentage, and any other cost additions/subtractions,
    and returns the customer's net spend on the order.
    """
    total = 0
    # computing the total order amount
    for price in prices:
        total += price

    total_discounted_price = total - discount*total

    net_spend = total_discounted_price - kwargs['cashback']

    # return the total amount
    return net_spend

Importan: Note that the **kwargs arguments passed while calling the function must be a mappuing

additionals = {'cashback': 5}
print('Customer net spend (during last day of festive season):', customer_net_spend(700, 599, 650, discount=0.05, **additionals))
Customer net spend (during last day of festive season): 1846.55

MobiWorld plans to introduce a reward-point system based on the total order amount. Reward points will be given as per the following scheme:

  • Total Amount >= 2000: 100 Reward Points
  • Total Amount >= 5000: 200 Reward Points
  • Total Amount >= 10000: 300 Reward Points

Let’s define a function that will return the total amount, net spend, and rewards points earned for the order.

def order_summary(*prices, **additionals):
    """
    This function takes the prices of phones ordered
    and any other cost additions/subtractions,
    and returns the total amount, net spend,
    and rewards points earned for the order.
    """
    total = 0
    # computing the total order amount
    for price in prices:
        total += price

    net_spend = total - additionals['discount']*total - additionals['cashback']

    if total >= 10000:
        reward_points = 300
    elif total >= 5000:
        reward_points = 200
    elif total >= 2000:
        reward_points = 100
    else:
        reward_points = 0

    # return the total amount
    return total, net_spend, reward_points

Python will return multiple outputs as a tuple.

additionals = {'discount':0.05, 'cashback': 5}
ta, ns, rp = order_summary(700, 599, 750, **additionals)
print('Customer Order Summary:\n', '\nTotal Amount:', ta, '\nTotal Discounted Amount:', ns, '\nReward Points Earned:', rp)
Customer Order Summary:
 
Total Amount: 2049 
Total Discounted Amount: 1941.55 
Reward Points Earned: 100

Note the += and *= operations in the following examples

def total_addition(*numbers):
    addition = 0
    for number in numbers:
        addition += number
    return addition

total_addition(1,2,3)
6
def fun(*int):
    result = 1
    for x in int:
        result *= x
    return result

fun(1,2,3,4,5)
120