Introduction To Python Programming Language
Introduction To Python Programming Language
Introduction To Python Programming Language
A general-purpose programming language is a language that can be used to develop software for
a wide range of application domains.
• Python is a GPL that can be used to write desktop software, web applications, data
science, ML, etc.
• In contrast to general-purpose programming languages, we also have domain-specific
programming languages, such as SQL.
• DSLs are used within a specific area, such as SQL, which can only be used for querying
relational databases and nothing else.
• Python is a programming language that places special importance on code readability and
is one of the most readable programming languages.
• Code readability is important because if code is readable, more people will be able to use
it and it will be easier to maintain.
• Another reason why code readability is important is that as a programmer, you will spend
most of your time reading, understanding, reusing, and modifying existing source code.
• Indentation makes code more readable, but in programming languages like C, C++, and
Java, indentation is only used for code readability and formatting.
• In Python, indentation is part of the syntax and is used to indicate a block of code.
• For example, in Java, we use curly braces to represent a block of code, whereas in
Python, we use indentation, i.e., spaces to indicate a block of code.
In programming languages like C, when you declare a variable, you also set the type for that
variable, and the type of that variable cannot be changed during execution.
• In Python, you do not have to declare the type while creating a variable.
• Due to dynamic typing, a variable can have a different type at different times during
execution.
• In dynamic typing, the type of variable is decided at runtime.
• In Python, we do not have to worry about freeing up or reclaiming allocated and unused
memory because it is garbage collected.
• Garbage collection automatically reclaims memory that was allocated by the program but
is no longer in use.
• As programmers, we do not have to manually deallocate memory.
Performing mathematical operations in Python:
1. 100+20
1. 200-40
1. 45*67
1. 4*6*(28+5)
1. 200/2
1. 200//2
Always ensure that you do not divide any number by zero in your program, as it will result in an
error.
When you multiply a float value with an integer value, the result is always in float:
1. 12.0 * 4
However, if we write:
1. 12*4
An exponent refers to how many times a number is multiplied by itself. For example, 5 is
multiplied by itself 3 times i.e. 5 x 5 x 5, then we can say it is 5 raised to 3. We also call it 5 to
the power 3 or 5 raised to 3. Here, 3 is the exponent and 5 is the base.
We can calculate exponents in Python using the "**" operator. For instance:
1. 5**3
1. 2**4
We can also use exponents to calculate the square root of a number, for instance:
1. 64**(1/2)
When we divide two numbers in Python, we only get the quotient. However, in division, we have
a remainder as well. For example, if we say:
1. 21/4
We should get 1 as a remainder. Hence, to specifically get a remainder, we use the modulus
operator "%".
The modulus operator "%" divides the two numbers and gives us the remainder instead of the
quotient. The modulus operator is specifically useful when we need to check if a number is odd
or even. If any number % 2 gives zero as the remainder, the number is odd. If it gives 1 as the
remainder, the number is even. The modulus operator can also be used with floating-point
values.
Example:
1. 456.34%2
Strings in Python:
To create and print a string:
1. print('Hello world')
While using the Python interactive console, you don't have to use the print statement to print the
string.
You could directly enclose anything inside of single or double quotes and that would be printed.
For example:
1. 'hello world'
Hit enter and you will get "hello world" printed. The same could be done using double quotes as
well.
This error occurs because Python thinks that the single quote which we use in the sentence is not
a part of the sentence but instead is a part of the syntax.
Python thinks that the string starts at ' and ends at '.
Hence, to tell Python that ' is a part of a string, we use something called an escape character
which is \ backslash.
To specify that we want to escape a character, we add a backslash before it. In this case, we want
to escape the ' in the sentence and hence we add a \ before it.
Another way to print the above sentence is by using double quotes instead of single ones.
Now here, as we have used double quotes, the single quote is automatically escaped as Python
does not treat it as a part of syntax. It believes that the string starts when we start " and ends
when we add another " and everything in between is a string.
The same could be done with single quotes as well. If we use single quotes to represent a string,
we could use double quotes inside a string. For example:
1. 'This is the "only" way to go'
But instead of the above, if you use double quotes for creating strings as well as inside of a string
as well, in that case, we will get an issue. Let's try doing that:
1. input()
However, when we execute the input() function, we may not be sure what the program expects
us to do or what value should be entered. Therefore, we can pass a string argument to the input()
function to prompt the user for input.
We can also save this input as a variable for later use in our program, but we will cover that topic
later when we learn about variables.
String operations:
For example:
1. 'Hello there'
1. '8'
To check the actual type of a value, you can use the type() function:
1. type(8)
2. type('8')
1. "10" + "10"
1. 10+10
Python treats them as integer values and performs addition instead of concatenation.
You can also concatenate a string and a number by making the number a string:
But if you try to concatenate a string with an integer, you will get an error:
1. "Hello" + 5
1. "Hello " * 4
1. a = 200
We have created a variable named "a" and assigned the value 200 to it. The "=" sign is called a
variable assignment.
When we create a variable and assign it a value, we are essentially storing the value into a
memory location.
To print the value of "a", we can use the print() function:
1. print(a)
1. b = 20
However, if you close the window and try accessing the value of "a" and "b", you won't be able
to do so. When we close the interpreter, the value stored in the variable gets deleted.
1. a = 100
2. print(a)
3. a = 200
4. print(a)
Not just numbers, but you can also store other data types in a variable as well:
Strings:
1. name = "John"
2. type(name)
Floats:
1. a = 3.2
2. type(a)
Booleans:
1. b = True
2. type(b)
Naming Python variables:
You can use long or short variable names in Python, but it is advisable to write readable variable
names so that we can understand what is stored in them. For example, when writing a program to
calculate the area of a circle, it is better to name a variable "radius" rather than just "r" to save the
radius value.
In Python, variables can be of any length and can consist of uppercase letters, lowercase letters,
digits, and underscores. However, the first character of a variable cannot be a number. Let's take
a couple of examples:
Another restriction on variable names is that we cannot use Python keywords as variable names.
Keywords are part of the Python programming language itself. For example,
the print() function is a keyword. Let's try using "print" as a variable:
1. print = 20
This will result in an error.
It is a data structure in Python that allows you to store multiple items in one place.
A variable allows you to store a single item, such as a single name. However, if you need to store
multiple names, you need to use lists.
A list is an alternative to arrays in Python. In Java and C, we have arrays, but in Python, we have
lists.
To print an individual element inside a list, every item in the list has an index position. The first
element has an index position of 0.
1. print(people[0])
1. print(people[1])
1. print(numbers[0])
Lists are ordered, which means that a list is not just a collection of items; the items are in a
specific order, and their order does matter.
1. a = [1, 2]
1. b = [2, 1]
1. print(a == b)
In Python, negative list indexing refers to accessing elements of a list using negative integers as
the index.
When you use a negative index, Python starts counting from the end of the list. So, the last
element in the list has an index of -1, the second-to-last has an index of -2, and so on.
Here, my_list[-1] would give the value 50 , my_list[-2] would give the value 40 , and
so on.
Negative indexing can be useful when you want to access the last few elements of a list, but you
don't know the exact length of the list.
List slicing:
1. a[m:n]
In the following example, we have a list of fruits and we are slicing the list to extract certain
portions:
1. # -ve index -6 -5 -4 -3 -2 -1
2. fruits = ['apple', 'mango', 'peach', 'orange', 'watermelon', 'grape']
3. # index 0 1 2 3 4 5
4.
5. # list slicing
6. print(fruits[0:3]) # prints ['apple', 'mango', 'peach']
7. print(fruits[1:3]) # prints ['mango', 'peach']
Here, the first slice fruits[0:3] returns a sublist of fruits starting from index 0 up to but not
including index 3. So it includes the elements at indices 0, 1, and 2 which are 'apple', 'mango',
and 'peach' respectively.
Similarly, the second slice fruits[1:3] returns a sublist starting from index 1 up to but not
including index 3. So it includes the elements at indices 1 and 2 which are 'mango' and 'peach'
respectively.
1. a[-m:-n] returns list items from index -m to -n but does not include n
List functions:
1. print(len(fruits))
1. fruits.insert(index,"Element to be inserted")
2. fruits.insert(1,"Pineapple")
Appending an element to the end of a list:
1. fruits.append('Hello')
1. fruits.extend(['guava', 'apricot'])
1. fruits.remove('apple')
1. fruits.pop()
2. print(fruits)
1. print(fruits.index('apple'))
Tuples:
Like lists, tuples are also collections of items or objects.
However, the difference between tuples and lists is that tuples are immutable.
Once the items in the tuple are defined, we cannot change them.
1. # Creating a tuple
2. fruits = ('apple', 'orange', 'mango', 'pineapple')
3. # Printing a tuple
4. print(fruits)
5. # Immutability of a tuple
6. fruits[1] = 'peach'
7. print(fruits)
8. # Indexing
9. print(fruits[1])
10. # Slicing
11. print(fruits[1:3])
12. # Negative indexing
13. print(fruits[-1])
Program execution is fast with tuples. As tuples are immutable, they should be used when we
don't want the data to be changed.
Dictionaries:
We can store data inside a dictionary that we can later use in our program.
We can take the example of a dictionary in the real world, which is a big book that contains the
meanings of words.
If you want to find the meaning of the word "garden", you would look up that word and you will
be able to find its meaning. Hence we can say that a dictionary contains a pair, i.e., a word and
its meaning.
In Python, a dictionary is similar. Instead of the meaning and word, we have keys and values.
Let's create a dictionary.
Dictionaries are mutable, and we can change the value of a certain key. Let's try changing the
age.
1. people["Rob"] = 90
2. print(people["Rob"])
We can have anything as a key-value pair in a dictionary. For example, we can have an integer as
a key and a string as a value, which is exactly opposite to what we have currently. However, we
cannot have the same key-value in a single dictionary.
Another way to create a dictionary is by using the dict() function. The argument to
the dict() function should be a key-value pair.
1. del people["John"]
2. print(people)
Sets:
Similarly, a set in Python is a collection of elements where each element is unique and duplicates
are not allowed.
When creating a set, if duplicates are present, the set will automatically remove them:
1. numbers = {1,2,3,4,1,4}
2. print(numbers) # Output: {1, 2, 3, 4}
The same holds true for strings:
1. names = {'John','Rob','Mike','John'}
2. print(names) # Output: {'Rob', 'John', 'Mike'}
To create an empty set, we cannot use empty curly braces ( {} ) as it creates an empty dictionary.
We need to use the set() function:
1. s = set()
1. s = {"John",2,4.5,True}
2. print(s) # Output: {2, 4.5, True, 'John'}
Set operations:
However, there are different operations that can be performed on sets, which are similar to those
of mathematical sets.
These operations include finding union, intersection, difference, and symmetric difference.
Union:
When you perform the union of two sets, you get all the elements of set a and all the elements of
set b, but with no duplicate entries.
1. seta = {1, 2, 3, 4, 5}
2. setb = {4, 5, 6, 7, 8}
3.
4. # union
5. print(seta | setb)
6. # the above could also be written as
7. print(seta.union(setb))
Intersection:
The intersection of two sets includes only those values which are common between the two sets.
1. seta = {1, 2, 3, 4, 5}
2. setb = {4, 5, 6, 7, 8}
3.
4. # intersection
5. print(seta & setb)
6. # the above code could also be written as
7. print(seta.intersection(setb))
Difference operation:
The difference operation takes the elements of set a and removes all the elements which are
present in set b.
It removes the values from set a which are common to both set a and set b.
1. # difference
2. print(seta - setb)
3. # the above code could also be written as
4. print(seta.difference(setb))
Symmetric difference:
The symmetric difference returns only those elements that are either in set a or in set b but not
both.
1. print(seta ^ setb)
2. # this could also be written as
3. print(seta.symmetric_difference(setb))
1. seta.remove(1)
2. print(seta)
This works the same as remove, but does not raise an exception if the element is not present in
the set.
1. seta.discard(10)
2. print(seta)
Pop:
1. a = seta.pop()
2. print(a)
Clear:
1. seta.clear()
2. print(seta)
Please note that this search is case-sensitive, so it will not work if you search for a product using
capital letters. Here's an example:
Example:
In the above example, the search for "Laptop" (with a capital 'L') returns False because the list
contains "laptop" (with a lowercase 'l').
We then use the append & remove methods to add and remove accepted values from the list
respectively:
To add items at a specific position, we make use of the index of the list along with the insert
method.
The insert method of a list allows us to insert an item at a specific index position in a list.
To add a new item to a Python dictionary, we simply add a new value at a specific key for that
dictionary.
To update an item inside a Python dictionary, we use it's key and simply add a new value for the
specified key.
1. products = {
2. 'phone': 100,
3. 'tablet': 200,
4. 'computer': 300,
5. 'laptop': 400,
6. 'journal': 40
7. }
8.
9. # Print all the items inside the dictionary
10. print(products)
11.
12. # Search for the price of a product
13. product = input("Enter the product to get the price: ")
14. print(f"The price of {product} is ${products[product]}")
15.
16. # Add a product along with its price
17. new_product = input("Enter the product you want to add: ")
18. new_product_price = input(f"Enter the price for {new_product}: ")
19. products[new_product] = new_product_price
20.
21. # Show the entire dictionary
22. print(f"Product successfully added. Here is the list of products: {products}")
23.
24. # Delete a product
25. deleted_product = input("Enter the product you want to delete: ")
26. del products[deleted_product]
27. print(f"Product successfully deleted. Here is the list of products:
{products}")
28.
29. # Change the price of a product
30. price_change_product = input("Enter the product to change the price: ")
31. price_change = input(f"Enter the new price for {price_change_product}: ")
32. products[price_change_product] = price_change
33. print(f"Price successfully changed. Here is the list of product:{products}”)
Section Notes
If statement:
In this example, the condition that determined the decision was whether it was raining
or not.
Python allows for the same type of decision-making through the use of If statements.
For instance, a program can be written to determine whether a person is an adult or not
based on their age. The code can be explained line-by-line as follows:
1. age = input('Enter your age') # Prompts the user to enter their age
2. age = int(age) # Converts the input to an integer
3.
4. if age>=18: # If the age is greater than or equal to 18, execute the next
line
5. print('You are an adult') # Prints the message "You are an adult"
6. else: # If the age is less than 18, execute the next line
7. print('You are not an adult') # Prints the message "You are not an adult"
In the above code, the lines of code within the if statement and the else statement are
indented to show that they are a part of those blocks.
This is how Python knows which lines of code are to be executed based on which
condition is met.
Indentation is typically four spaces or one tab, and consistency in indentation is
essential for proper execution of the code.
Range in Python:
For instance, to create a list of numbers from 1 to 10, we can use the range function
instead of typing out all the numbers individually.
Using the range function, we can create a sequence of numbers in the following way:
1. numbers = list(range(10))
This will create a list of numbers from 0 to 9, i.e., a total of 10 numbers. However, if we
want to create a range from 1 to 10, we can pass two parameters to the range function,
start, and stop:
1. numbers = list(range(1,11))
This will create a list of numbers from 1 to 10. Similarly, to create a list of 100 numbers,
we can use the following code:
1. numbers = list(range(1,101))
The range function takes two parameters, start and stop, and creates a sequence of
numbers from start to stop-1.
Additionally, we can add an optional third parameter called step, which specifies the
number of steps we need to skip in the range.
For example, instead of printing all the numbers from 1 to 100 in sequence like 1, 2, 3,
we could print digits like 1, 4, 7, which means we want a gap of 3 after every number.
We can do this by specifying the step parameter as follows:
1. range(1,101,3)
This will create a sequence of numbers with a gap of 3 after every number.
For loop in Python:
A for loop in Python allows you to execute a snippet of code multiple number of times.
The for loop then iterates over each value in this sequence. For each iteration, the loop
assigns the current value from the sequence to the variable x . The code block inside
the loop, which is indented, is then executed.
In this example, the code block simply prints the value of x using
the print() function. Therefore, during each iteration of the loop, the value of x will be
printed.
When you run this code, it will output the numbers from 1 to 9, each on a separate line
A for loop can also be used to iterate through a list of items as well.
Here is a simple example of using a for loop to iterate through a list of fruits:
First, we have a list called fruits that contains several string elements, namely 'apple',
'mango', 'banana', and 'orange'.
The for loop iterates over each element in the fruits list. For each iteration, the loop
assigns the current element to the variable x . The code block inside the loop, which is
indented, is then executed.
In this example, the code block simply prints the value of x using
the print() function. Therefore, during each iteration of the loop, the current fruit
name will be printed.
When you run this code, it will output each fruit name on a separate line.
A for loop can also be used to iterate through a dictionary as well just as we iterate
through a list.
The dictionary people is defined with key-value pairs representing names and ages of
individuals.
The first for loop iterates over the dictionary people . During each iteration, the loop
assigns the current key to the variable x . The code block inside the loop prints the value
of x , which represents the current key. This loop allows you to access and work with the
keys of the dictionary.
The second for loop also iterates over the dictionary people . Similarly, during each
iteration, the loop assigns the current key to the variable x . However, this time the code
block inside the loop prints the value associated with the current key. By
using people[x] , we can access the value corresponding to the key x in
the people dictionary.
While loop:
A while loop in Python is a control flow statement that allows you to repeatedly
execute a block of code as long as a specified condition remains true. It has the
following general syntax:
1. while condition:
2. # Code block to be executed repeatedly
It's important to ensure that the code inside the while loop eventually modifies the
condition; otherwise, the loop will continue indefinitely, resulting in an infinite loop.
1. counter = 0
2.
3. while counter <= 10:
4. print(counter)
5. counter = counter + 1
1. The variable counter is initialized with a value of 0. This variable will be used to
keep track of the current count.
2. The while loop begins with the condition counter <= 10 . This condition
specifies that the loop should continue executing as long as the value
of counter is less than or equal to 10.
3. Inside the loop, the current value of counter is printed using
the print() function.
4. After printing the value of counter , the variable is incremented by 1 using the
statement counter = counter + 1 (or the equivalent counter += 1 ).
5. The program then goes back to the beginning of the while loop and checks the
condition again. If the condition counter <= 10 is still true, the loop continues
to the next iteration. If the condition is false (i.e., counter becomes greater than
10), the loop terminates, and the program continues executing the statements
after the loop.
6. This process repeats until the condition counter <= 10 becomes false,
resulting in a total of 11 iterations.
Break:
1. while condition:
2. # code block
3. if condition:
4. break
5. # more code
In the above example, the break statement is placed within an if statement. When the
specified condition evaluates to True , the break statement is executed, and the loop
is terminated even if the original condition of the while loop is still satisfied.
1. counter = 0
2.
3. while counter <= 10:
4. counter = counter + 1
5. if counter == 5:
6. break
7. print(counter)
8.
9. print('Line after break')
In the given code, we have a while loop that runs as long as the counter variable is
less than or equal to 10. The loop increments the counter by 1 in each iteration using
the line counter = counter + 1 .
Inside the loop, there is an if statement that checks if the counter is equal to 5. If the
condition evaluates to True , the break statement is executed. This causes the loop to
be immediately terminated, even though the original condition ( counter <= 10 ) might
still be satisfied.
When the counter is equal to 5, the break statement is triggered, and the loop is
exited. After the loop, the line print('Line after break') is executed. This line
will be executed regardless of the break statement because the break statement only
stops the loop's execution, not the execution of the entire program.
In summary, the code prints the values of counter from 1 to 4 (inclusive) and then
breaks out of the loop when counter reaches 5. After the loop, the line print('Line
after break') is executed.
Continue:
A continue statement will immediately terminate a loop and the execution starts again
from top of the loop, the conditional expression is re-evaluated and it is determined if
loop will be executed again or not.
1. counter = 0
2.
3. while counter <= 10:
4. counter = counter + 1
5. if counter == 5:
6. continue
7. print(counter)
8.
9. print('Line after continue')
We have a while loop that runs as long as the value of counter is less than or equal to
10. The initial value of counter is 0.
Within the loop, counter is incremented by 1 using the line counter = counter +
1 . This means that with each iteration of the loop, the value of counter increases by 1.
Inside the loop, there is an if statement that checks if the value of counter is equal to
5. If it is, the continue statement is encountered. When continue is executed, it
skips the rest of the code within the loop for that iteration and moves on to the next
iteration. In this case, when counter is 5, the print(counter) statement is skipped,
and the loop proceeds to the next iteration.
The line print(counter) inside the loop is responsible for printing the current value
of counter for each iteration. However, when counter is 5, it is skipped due to
the continue statement.
Once the loop completes, the line print('Line after continue') is executed.
This line is not part of the loop and will be printed after the loop has finished running.
To accept multiple inputs from a user, we can make use of a for loop.
In the code below we accept items to be added to the cart and save them in a list called
cart.
However, with this for loop we are limited by asking the user the number of items they
want to add hence making our code less dynamic
1. cart = []
2.
3. # Accept the number of items the user wants
4. n = int(input("Enter the number of items: "))
5.
6. # Loop to add items to the cart
7. for x in range(n):
8. item = input("Enter item to add to the cart: ")
9. cart.append(item)
10. print(cart)
11.
12. # This code accepts only one item at a time based on the given input.
In this code, we start by initializing an empty list cart to store the items.
Then, we ask the user to enter the number of items they want to add to the cart using
the input function and store it in the variable n .
Next, we use a for loop to iterate n times. In each iteration, we prompt the user to
enter an item to add to the cart using the input function and store it in the
variable item . The item is then appended to the cart list using the append method.
After adding an item to the cart, we print the current contents of the cart by printing
the cart list.
Note: The code as provided only allows the user to enter one item at a time, and it
repeats the process n times based on the user's input.
Let’s say I do not want to set a limit on the no of items I can add.
In this case we can use a while loop which infinitely accepts products till we tell the
program to stop.
1. pythonCopy code
2. cart = []
3.
4. while True:
5. choice = input('Do you want to add an item to the cart? ')
6. if choice == "yes":
7. item = input("Enter the item you want to add: ")
8. cart.append(item)
9. print(f'Current cart contents are: {cart}')
10. else:
11. break
12.
13. print(f"Thank you, your final cart contents are: {cart}")
If the user chooses not to add an item (enters "no"), the loop breaks, and the code
continues executing after the loop.
1. products = [
2. {"name": "Smartphone", "price": 500, "description": "A handheld device
used for communication and browsing the internet."},
3. {"name": "Laptop", "price": 1000, "description": "A portable computer that
is easy to carry around."},
4. {"name": "Headphones", "price": 50, "description": "A pair of earphones
worn over the head to listen to music."},
5. {"name": "Smartwatch", "price": 300, "description": "A wearable device
used for fitness tracking and receiving notifications."},
6. {"name": "Bluetooth speaker", "price": 100, "description": "A portable
speaker that connects wirelessly to devices using Bluetooth technology."}
7. ]
8. cart = []
9.
10. while True:
11. choice = input('Do you want to continue shopping? ')
12.
13. if choice == "y":
14. print('Here is a list of products and their prices')
15. for index, product in enumerate(products):
16. print(f"{index}: {product['name']} : {product['description']} :
${product['price']}")
17. product_id = int(input("Enter the id of the product you want to add to
the cart"))
18.
19. # Check if the product is already present in the cart
20. if products[product_id] in cart:
21. # If present, increase the quantity of the product
22. products[product_id]["quantity"] += 1
23. else:
24. # If not present, add the product to the cart with a quantity of 1
25. products[product_id]["quantity"] = 1
26. cart.append(products[product_id])
27.
28. # Code to display the current cart contents, including the name,
description, price, and quantity
29. total = 0
30. print('Here are the contents in your cart')
31. for product in cart:
32. print(f"{product['name']} : {product['description']} :
${product['price']} : QTY:{product['quantity']}")
33. total += product['price'] * product['quantity']
34. print(f"Cart total is: ${total}")
35. else:
36. break
37.
38. print(f"Thank you, your final cart contents are {cart}")
In this code, we start by defining a list called products which contains dictionaries
representing different products. Each product dictionary has the keys "name", "price",
and "description" with corresponding values.
The code enters a while loop that continues indefinitely until the user chooses to stop
shopping by entering something other than "y" when prompted. Inside the loop, it
displays the list of products and their prices using a for loop and
the enumerate() function to get both the index and the product.
The user is then prompted to enter the ID of the product they want to add to the cart. If
the selected product is already present in the cart, its quantity is increased by 1.
Otherwise, the product is added to the cart with a quantity of 1.
After updating the cart, the code displays the current contents of the cart by iterating
through the cart list and printing the product's name, description, price, and quantity. It
also calculates the total price of the items in the cart.
Once the user chooses to stop shopping, the loop breaks, and the final contents of the
cart are printed.
Functions in Python:
It can be created to avoid repeating code and to make the program more efficient.
To create a function in Python, we need to define it first. The syntax for defining a
function is as follows:
1. def function_name():
2. # code to be executed
The def keyword is used to define the function, followed by the name of the function
and a pair of parentheses.
Any arguments that the function takes can be specified within these parentheses.
1. def hello():
2. print('Hello')
3. print('Hi')
4. print('Tom')
To execute the function, we simply call it by its name followed by a pair of parentheses.
For example, we can call the hello function twice:
1. hello()
2. hello()
When we run the code, it will print the output of the hello function twice, which is:
1. Hello
2. Hi
3. Tom
4. Hello
5. Hi
6. Tom
1. def add():
2. a = 10
3. b = 20
4. print(a + b)
5.
6. add()
This works, but the problem is that every time we call the add() function, it performs
the addition of 10 and 20.
However, we want our function to be dynamic, i.e., it should perform the addition of any
two numbers we want, just like the print() function.
To make a function accept arguments, we have to change its definition. Let's modify the
function definition for add() so that instead of having variables a and b inside the
function, we make them parameters:
Now calling the add() function gives an error because the function call now expects
two arguments.
Let's pass values to the function call and see the result:
Note: In the above code, a and b are parameters, and 10 and 20 are arguments.
In the above code, what happens is that the value 10 gets assigned to a , and 20 gets
assigned to b .
1. pythonCopy code
2. def add(a, b):
3. print(a)
4. print(b)
5. print(a + b)
6.
7. add(10, 20)
1. add(10, 20)
2. add(20, 40)
3. add(34, 23)
Positional arguments:
In positional arguments, the position of arguments matters, and you must know the
position of the parameters so that you could pass them accurately.
But let’s say you don't want to be bothered by the position of the argument.
Let’s take an example to understand this. Let’s create a function that calculates the
speed.
1. def speed(distance,time):
2. s = distance/time
3. return s
As we are using positional arguments, we always have to remember that while calling a
function, we need to pass the arguments in the proper order.
If we pass arguments in the wrong order, the function returns a wrong result. For
instance:
1. avgspeed = speed(100,2)
2. print(avgspeed)
3.
4. avgspeed = speed(2,100)
5. print(avgspeed)
However, we can call the same function using keyword arguments, which do not require
the order of arguments to be the same as the parameter order in the function definition.
For example:
1. avgspeed = speed(time=2,distance=100)
2. print(avgspeed)
Now in the above code, even if we pass arguments in the wrong order, we do not have
to worry about the result being wrong.
Default parameters:
While defining a function, we can add parameters to it. However, we can also pass the
values to these parameters inside the function definition itself, which is called passing
default parameters.
Even if we don’t pass the value of PI in the function call, it still works fine:
1. circle_area = area(10)
You can also override the value of the default parameter by passing your own value.
Let’s pass pi as 3.15:
Now the value of 3.14, which is the default parameter, gets overridden by the value
which we pass in the function call.
The "add" function above prints a value, but suppose we want to access that value
instead of printing it. In this case, we need to modify the function definition to return the
value using the "return" keyword:
1. def add(a, b):
2. c = a + b
3. return c
4.
5. result = add(10, 20)
6. print(result)
This is a common practice in real-world function design, where functions often return a
value that can be used in other parts of the program.
Till this point we have learned how to return a single value from a function.
Here is how:
We cannot just pass a single integer or a string to a function, we can also pass some
complex data structure like a list to a function.
1. def sum(numbers):
2. total = 0
3. for number in numbers:
4. total = total + number
5. return total
6.
7. result = sum([1,2,3,4,5])
8. print(result)
Remove duplicates from a list:
Using a combination of a loop, "in" and append, we can remove duplicate values from a
list.
1. def remove_duplicates(numbers):
2. # create a new list which does not contain duplicates
3. new_list =[]
4. for number in numbers:
5. if number not in new_list:
6. new_list.append(number)
7. return new_list
8.
9. list = [1,2,3,4,3,4,5,2,1,7,8,9]
10. result = remove_duplicates(list)
11. print(result)
Take the list, pass it to the set it will remove the duplicate elements.
1. def remove_duplicates(lst):
2. return list(set(lst))
Global variables:
• Global variables are defined outside of any function or block and can be
accessed throughout the program.
• They have global scope, meaning they can be accessed by any part of the
program, including functions and blocks.
• Global variables are typically defined at the top level of the program.
• To define a global variable, you simply assign a value to a variable outside of any
function or block.
• Global variables can be accessed and modified by any part of the program
unless they are shadowed by a local variable with the same name inside a
function.
Local variables:
• Local variables are defined within a function or block and can only be accessed
within that specific function or block.
• They have local scope, meaning they are limited in visibility to the block in which
they are defined.
• Local variables are typically defined inside functions, loops, or conditional
statements.
• To define a local variable, you assign a value to a variable inside a function or
block.
• Local variables can only be accessed and modified within the function or block in
which they are defined. They are not visible outside of their scope.
1. def add():
2. count = 20
3. print(count)
4.
5. print(count)
This wont work because the variable count is local variable and it cannot be accessed
outside the variable.
1. count = 10
2.
3. def increment():
4. print(count)
5.
6.
7. increment()
A global variable is accessible everywhere outside as well as inside the function as well.
But now let’s try incrementing the value of count inside the function.
1. count = 10
2.
3. def increment():
4. count = count + 1
5. print(count)
6.
7.
8. increment()
This gives an error and the error log says, local variable cannot be referenced before
assignment.
This does not work because Python thinks that the variable declared inside the function
is a local variable.
To access global variable inside a function, we need to tell python that “count” is a
global variable.
1. count = 10
2.
3. def increment():
4. global count
5. count = count + 1
6. print(count)
7.
8.
9. increment()
A palindrome is a string which when reversed gives the exact same output.
The code below explain step by step how a string could be checked for being a
palindrome.
To check the first letters and last letters of a string, we first loop through the string in a
forward manner and then also loop though it in reverse and compare the letters if they
match.
To loop in a reverse manner, we simply use the length of the string and subtract 1 from
it every time the loop executes.
1. word = "panasonic"
2. # treat a string like a list
3. print(word[0])
4.
5. # get the length of string
6. l = len(word)
7.
8. # loop through all the items from the start
9. print('Printing the string straight')
10. for i in range(l):
11. print(word[i])
12.
13. # loop through the items in reverse
14. print('Printing the string in reverse')
15. for i in range(l):
16. print(word[l-i-1])
17.
18. #comparing and returning if palindrome
19. palindrome_flag = True
20. for i in range(l):
21. if word[i] != word[l-i-1]:
22. palindrome_flag = False
23. break
24. else:
25. palindrome_flag = True
26.
27. if palindrome_flag:
28. print("The string is a palindrome")
29. else:
30. print('The string is not a palindrome')
31.
32.
33. #converting the above code into a function
34. def check_palindrome(word):
35. #get the length of the string
36. l = len(word)
37. for i in range(l):
38. if word[i] != word[l-i-1]:
39. return False
40. return True
41.
42. # call the above function
43. print(check_palindrome("racecar"))
EMI calculator:
Recursion:
1. def hello():
2. print('Hello')
3. hello()
4.
5.
6. hello()
1. 4! = 4x3x2x1
2. 2! = 2x1
3. 100! = 100x99x98......
Python code to calculate factorial:
1. def factorial(number):
2. if number ==1:
3. return 1
4. else:
5. return number * factorial(number-1)
6.
7. print(factorial(4))
8.
9. #how the iterations work
10. #factorial(4) => return 4 * factorial(3)
11. #factorial(3) => return 3 * factorial(2)
12. #factorial(2) => return 2 * factorial(1)
13. #factorial(1) => return 1
In some cases we don’t know the number of arguments we need to pass to a function.
Example:
Hence to create a function that can accept variable number of arguments we use
variable length arguments.
1. def add(*args):
2. sum = 0
3. for n in args:
4. sum = sum+n
5. print(sum)
6.
7. add()
8. add(10)
9. add(20, 30)
10. add(40, 50, 60)
A variable length keyword arguments let’s you pass any number or arguments along
with a keyword rather than the position.
1. def product(**kwargs):
2. for key, value in kwargs.items():
3. print(key+":"+value)
4.
5. product(name='iphone', price="700")
6. product(name='iPad', price="400", description="This is an ipad")
Decorators in Python:
In simple words, decorators are a function that take another function and extends its
behaviour without altering the code.
1. def chocolate():
2. print('chocolate')
3. chocolate()
Now let’s say I want to add a wrapper to the chocolate which prints wrapper and
wrapper before and after chocolate.
1. def chocolate():
2. print('chocolate')
3.
4. # this decorator function accepts function as argument
5.
6. def decorator(func):
7. # inside the decorator function we have another function
8. def wrapper():
9. print('Wrapper up side')
10. # now here I call the func
11. func()
12. print('Wrapper down side')
13. # now the decorator needs to return this wrapper
14. return wrapper
15.
16. # now to call the functions, i first call the decorator and then pass
chocolate inside it
17. # then assign the function back to the previous main function i.e chocolate
18. # finally call the chocolate function
19. chocolate = decorator(chocolate)
20. chocolate()
As you can see now the behaviour of the chocolate function is modified.
Hence we can say that decorators simply wrap the function to modify its behaviour.
Another way of using decorator:
In the above code after defining two functions we had to write the last 2 lines to use the
decorator.
1. def decorator(func):
2. # inside the decorator function we have another function
3. def wrapper():
4. print('Wrapper up side')
5. # now here I call the func
6. func()
7. print('Wrapper down side')
8. # now the decorator needs to return this wrapper
9. return wrapper
10.
11. @decorator
12. def chocolate():
13. print('chocolate')
14.
15. chocolate()
Reusing decorators:
The decorator we used for wrapping can also be used for another function as well.
1. @decorator
2. def cake():
3. print('cake')
4.
5. cake()
Let’s try adding some argument to the cake function and see if it works.
1. @decorator
2. def cake(name):
3. print('cake'+name)
4.
5. cake("apple")
This will give us an error, because the wrapper which calls the function does not accept
any arguments.
Hence we need to make the func() inside the wrapper accept arguments as well.
1. def decorator(func):
2. def wrapper(name):
3. print('Wrapper up side')
4. func(name)
5. print('Wrapper down side')
6. return wrapper
However when we now try to use the same decorator with chocolate it wont work
because we have not passed in name there.
1. chocolate()
To avoid this, we pass variable length arguments and variable length keyword
arguments to the function instead of simply passing it name.
1. def decorator(func):
2. def wrapper(*args, **kwargs):
3. print('Wrapper up side')
4. func(*args, **kwargs)
5. print('Wrapper down side')
6. return wrapper
7.
8. @decorator
9. def chocolate():
10. print('chocolate')
11.
12. @decorator
13. def cake(name):
14. print('cake'+name)
15.
16. chocolate()
17. cake("Mango")
Let’s assume we have a function that calculates the total amount of shopping.
On top of it, we want another function that calculates a 50% summer discount on the
total value.
Create a function called total that calculates the total price:
1. def total(price):
2. # Let's assume there was some code here which calculated the total amount
3. return price
1. def summer_discount_decorator(func):
2. def wrapper(price):
3. # take the value inside the total and return
4. func(price)
5. return func(price/2)
6. return wrapper
Entire code:
1. def summer_discount_decorator(func):
2. def wrapper(price):
3. # take the value inside the total and return
4. func(price)
5. return func(price/2)
6. return wrapper
7.
8. @summer_discount_decorator
9. def total(price):
10. # Let's assume there was some code here which calculated the total amount
11. return price
12.
13. print(total(20))