Introduction To Python Programming Language

Download as pdf or txt
Download as pdf or txt
You are on page 1of 49

Introduction to Python programming language:

• Python is a high-level, interpreted, general-purpose programming language.


• Its design emphasises code readability through the use of significant indentation.
• Python is dynamically typed and garbage-collected.
• A high-level programming language is one that abstracts the details of the computer.
• When writing a program using any programming language, all code written is converted
into machine code, which is binary 0s and 1s.
• However, for programmers, writing a program using machine code is extremely difficult
since a computer's processor can only process machine code.
• Programmers who used to code in machine code did not use 0s and 1s.
• Instead, they wrote code in a more readable format, such as decimal, octal, or
hexadecimal.
• This code was then translated into an internal format by a program called a loader.
• Back in the early days, programming a computer using machine code was quite difficult.
• To reduce this difficulty, assembly language was introduced, which provided one
abstraction level on top of machine code.
• Unlike binary code, assembly code had some human-readable symbols, numerics, strings,
etc.
• In assembly code, we had to directly work with hardware features of the processor, i.e.,
its registers.
• Writing code in assembly language was still difficult, so another layer of abstraction was
added on top of it.
• A more human-readable language, like the C programming language, was introduced to
make coding easier.

What is a general purpose 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.

Emphasises code readability


Code readability refers to how easy it is for a human to read and comprehend code.

• 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.

Uses significant indentation

Indentation refers to having space at the beginning of a line of 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.

Python is dynamically typed

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.

Python is garbage collected

Garbage collection is a process of automatic memory management.

• 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:

To add two numbers:

1. 100+20

To subtract two numbers:

1. 200-40

To multiply two numbers:

1. 45*67

To perform complex mathematical operations:

1. 4*6*(28+5)

There are two ways to divide numbers in Python:

1. 200/2

Using a single slash will give a float value:

A float is a value that has a decimal point.

To obtain an integer value instead of a float, use "//" instead of "/":

1. 200//2

This is called floor division.

Dividing a number by zero will result in a divide by zero error:


1. 345/0

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:

For example, if we write:

1. 12.0 * 4

This will give us 36.0 instead of 36.

However, if we write:

1. 12*4

It will give us an integer value.

Complex mathematical operations:

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.

Examples of Exponent in Python:

We can calculate exponents in Python using the "**" operator. For instance:

To calculate 5 to the power of 3, we write:

1. 5**3

To calculate 2 to the power of 4, we write:

1. 2**4
We can also use exponents to calculate the square root of a number, for instance:

1. 64**(1/2)

Finding Remainder in Division:

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:

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')

When we enclose anything in single or double quotes, it becomes a string in Python.

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.

Let's try printing a sentence like "He's a good guy".

When we try doing that, we get an error.

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.

1. 'He\'s a good guy'

This tells Python that ' is not a part of syntax.

Another way to print the above sentence is by using double quotes instead of single ones.

1. "He's a good guy"

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. "This is the "only" way to go"

We need to fix this by using the backslash escape character.

"This is the \"only\" way to go"

Accepting user input:

In some programs, it is necessary to accept input data.

Python provides a function called input() to accomplish this.

Let's try using this function.

1. input()

This will prompt us to enter something.

Let's enter some input.

If we enter our name, the output will be the entered value.

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.

For example, we could use:

1. input('Enter your name')

After entering the name, it will be displayed.

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:

When you enclose anything in single or double quotes, it becomes a string.

For example:

1. 'Hello there'

Even a number or an integer becomes a string if it's enclosed in quotes:

1. '8'

To check the actual type of a value, you can use the type() function:

1. type(8)
2. type('8')

String operations include concatenation using the + operator:

1. "Hello" + " world"

You can also include spaces inside of the quotes:

1. "Hello " + "World"

You can concatenate two numbers as a string:

1. "10" + "10"

If you try to add two numbers without quotes:

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:

1. "Hello " + "5"

But if you try to concatenate a string with an integer, you will get an error:

1. "Hello" + 5

To multiply a string with a number, you can use the * operator:

1. "Hello " * 4

This will output "Hello Hello Hello Hello " .

However, you cannot multiply a string with another string.

Data types in Python:


When we write a program, we need to work with data. This data needs to be stored somewhere,
and hence, to store this data, we use variables.

Let's create a variable and assign it a value:

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)

Let's create another variable "b":

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.

The value of a variable can be changed at any instance:

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:

1. radius = 10. # Allowed


2. ra20dius= 20 # Allowed
3. 10radius = 30. # Not allowed
4. 1radius=20. # Not allowed
5. _radius=10. # Allowed
6. circle_radius = 10 # Allowed

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.

A list is used to store a list of items.

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.

Let's create a list of people:

1. people = ['John', 'Rob', 'Mike']

To print out this list, use:


1. print(people)

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.

Let's try printing the first element:

1. print(people[0])

To print the second member's name:

1. print(people[1])

Now let's create a list of numbers:

1. numbers = [10, 20, 30, 40, 50]

To print elements using an index, use:

1. print(numbers[0])

In the next lecture, we will perform some operations on the list.

A list can have different types of data:

1. Movies = ['Spiderman', 'Batman', 1, 2, 4.5, 'Hello']

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.

For example, the two lists:

1. a = [1, 2]
1. b = [2, 1]

are not the same.

To check if the two lists are equal, use:

1. print(a == b)

You will get the result as false.

Negative list indexing:

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.

For example, consider the following list:

1. my_list = [10, 20, 30, 40, 50]

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:

List slicing is a way to extract a portion of a list in Python.

1. a[m:n]

Returns a sublist of a starting from index m up to but not including index 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.

List slicing using negative indexing:

1. a[-m:-n] returns list items from index -m to -n but does not include n

List functions:

Calculating the number of items in a list

1. print(len(fruits))

Inserting elements into a list:

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')

To add the contents of one list into another, we use extend:

1. fruits.extend(['guava', 'apricot'])

Now the fruits will be added as individual items.

To remove an object from a list:

1. fruits.remove('apple')

To remove the last item in the list using pop:

1. fruits.pop()
2. print(fruits)

Finding the index of an item in a list:

1. print(fruits.index('apple'))

Getting the maximum values in a list:

scores = [1, 2, 3, 4, 5, 6, 90, 30] print(max(scores))

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.

Let's create a tuple and explain every code line by line:

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])

Advantages of using a tuple:

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:

Dictionaries are a data structure provided by Python, just like lists.

We can store data inside a dictionary that we can later use in our program.

Let's understand what dictionaries are in Python.

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.

Suppose you want to save the age of multiple people.

1. people = {"John": 32, "Rob": 40, "Tim": 20}


2. # Here John is the key, and 32 is the value.
3. # Elements of a list are accessed with index,
4. # elements of a dictionary are accessed with a key.
5. # Find the age of Rob, find a value depending on a key.
6. print(people["Rob"])

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.

1. ids = {1: "John", 2: "Rob", 3: "Matt"}


2. print(ids[2])

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. # We pass values as keyword arguments to the dict function.


2. # We have not learned about keyword arguments, but we will discuss them when
we learn about functions.
3. people = dict(
4. john=32,
5. rob=45,
6. tim=20
7. )
8. print(people["john"])

We can add a new value to a dictionary.


1. people = {"John": 32, "Rob": 40, "Tim": 20}
2. people["Mike"] = 34
3. print(people)

We can delete an entry using a key.

1. del people["John"]
2. print(people)

Sets:

A mathematical set is nothing but a collection of unique elements.

Similarly, a set in Python is a collection of elements where each element is unique and duplicates
are not allowed.

Sets in Python are unordered.

There are two ways to create a set in Python:

1. Using the set() function:


a. #creating a set
b. numbers = set([1,2,3,4,5,6])
c. print(numbers)
2. Using curly braces:
a. numbers = {1,2,3,4,5}
b. print(numbers)

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()

A set can contain elements of different data types:

1. s = {"John",2,4.5,True}
2. print(s) # Output: {2, 4.5, True, 'John'}

Note that the order of elements is not retained in a set.

Set operations:

Sets cannot be sliced or indexed as they are not ordered.

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))

Adding & removing elements of a set:

Adding elements to a set:


1. seta.add(10)
2. print(seta)

Removing elements from a set:

1. seta.remove(1)
2. print(seta)

Discarding elements from a set:

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:

This removes and returns a randomly chosen element from a set.

1. a = seta.pop()
2. print(a)

Clear:

This removes all the elements from a set.

1. seta.clear()
2. print(seta)

Searching for items in a list:

1. products = ['phone', 'tablet', 'computer', 'laptop', 'journal']


2. item = input("Enter the product to search: ")
3. print("Is the product in the list?", item in products)

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:

1. Enter the product to search: Laptop


2. Is the product in the list? False

In the above example, the search for "Laptop" (with a capital 'L') returns False because the list
contains "laptop" (with a lowercase 'l').

Adding and removing items form a list:

We first accept input from the user to add or remove items.

We then use the append & remove methods to add and remove accepted values from the list
respectively:

1. # Initial list of products


2. products = ['phone', 'tablet', 'computer', 'laptop', 'journal']
3.
4. # Displaying the initial list of products
5. print(f"The current list of items is: {products}")
6.
7. # Removing products
8. remove_item = input("Enter the product to remove: ")
9. products.remove(remove_item)
10.
11. # Displaying the list after removing the product
12. print(f"The current list of items is: {products}")
13.
14. # Adding products
15. add_item = input("Enter the product to add: ")
16. products.append(add_item)
17.
18. # Displaying the list after adding the product
19. print(f"The current list of items is: {products}")

Adding items at a specific position in a list:

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.

1. # Initial list of products


2. products = ['phone', 'tablet', 'computer', 'laptop', 'journal']
3.
4. # Displaying the initial list of products
5. print(f"The current list of items is: {products}")
6.
7. # Adding products
8. add_item = input("Enter the product to add: ")
9.
10. # Accepting the product after which you want to place the current product
11. add_after = input(f"After which product do you want to place {add_item}? ")
12. index = products.index(add_after)
13. products.insert(index + 1, add_item)
14.
15. # Displaying the list after adding products
16. print(f"The current list of items is: {products}")

Adding, deleting and editing items of a dictionary:

To add a new item to a Python dictionary, we simply add a new value at a specific key for that
dictionary.

To delete an item from a dictionary we use "del".

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:

An If statement is used to make a decision based on a specific condition.

This allows for logical decisions to be made based on certain criteria.

For instance, if it is raining outside, you won't go shopping. Conversely, if it is not


raining, you will go outside.

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"

Indentation in Python is used to define blocks of code.

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:

Range is an essential concept in Python used to create a sequence of numbers.

It enables us to create a list of numbers from a given range.

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.

Here is a simple example of a for loop:

1. for x in range(1, 10):


2. print(x)

The range() function in Python generates a sequence of numbers based on the


specified start, stop, and step values. In this case, range(1, 10) will generate a
sequence of numbers starting from 1 and ending at 9 (up to, but not including 10).

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

Iterating through a list of items:

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:

1. fruits = ['apple', 'mango', 'banana', 'orange']


2.
3. for x in fruits:
4. print(x)

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.

Iterating through a list of dictionary:

A for loop can also be used to iterate through a dictionary as well just as we iterate
through a list.

Here is an example of iterating through a dictionary using a for loop:

1. people = {"John": 32, "Rob": 40, "Tim": 20}


2.
3. # To get access to keys
4. for x in people:
5. print(x)
6.
7. # To get access to values
8. for x in people:
9. print(people[x])

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

1. The condition is a boolean expression that determines whether the loop


should continue executing or not. It is evaluated before each iteration of the loop.
If the condition is True , the code block inside the loop is executed. If the
condition is False , the loop is exited, and the program continues executing from
the next statement after the loop.
2. The code block indented below the while statement is the body of the loop. It
contains the statements that will be executed repeatedly as long as the condition
remains true. This block of code should perform some operations or tasks that
will eventually modify the condition, allowing the loop to terminate.
3. After executing the code block, the program goes back to the beginning of
the while loop and checks the condition again. If the condition is still True , the
code block is executed again. This process continues until the condition
becomes False .

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.

Example of a while 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:

In Python, the break statement is used to terminate the execution of a loop


prematurely. When break is encountered within a loop (such as for or while ), the
loop is immediately exited, and the program continues to execute from the next
statement after the loop.

The break statement is often used in combination with conditional statements to


control the loop termination based on certain conditions. Here's the general syntax of
the break statement:

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.

Here is an example of a break statement:

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.

Example of a continue statement:

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.

Adding items to the cart(list) using a for loop:

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.

Finally, the loop ends, and the program finishes executing.

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.

Adding items to the cart using while loop:

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}")

In this code, we initialize an empty list cart to store the items.

If the user chooses not to add an item (enters "no"), the loop breaks, and the code
continues executing after the loop.

Adding items to cart from a given product list:


Instead of accepting a simple string value as a product, we now present users with a list
of products.

We create a list of products where each product is defined in terms of a Python


dictionary.

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.

We initialise an empty list called cart to store the selected products.

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:

A function in Python is a block of code that performs a specific task.

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.

The colon : is used to indicate the start of the function block.


The code to be executed inside the function must be indented. It is best practice to use
four spaces for indentation.

For example, let's define a function called hello :

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

Passing arguments to function:

let's say we want to create a function that adds two numbers:

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:

1. def add(a, b):


2. print(a + b)
3.
4. add()

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:

1. def add(a, b):


2. print(a + b)
3.
4. add(10, 20)

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 .

You can even verify that by printing them:

1. pythonCopy code
2. def add(a, b):
3. print(a)
4. print(b)
5. print(a + b)
6.
7. add(10, 20)

This is why they are called positional arguments.

Let's call this function multiple times with different values:

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.

Let’s take an example:

1. def area(pi, radius):


2. a = pi * radius * radius
3. return a
4.
5. circle_area = area(3.14, 10)
6. print(circle_area)

Now let's make the pi argument a default argument:

1. def area(radius, pi=3.14):

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:

1. circle_area = area(10, 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.

Making a function return a value:

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.

Returning multiple values from a function.

Till this point we have learned how to return a single value from a function.

However, we can also make a function return multiple values as well.

Here is how:

1. # returning multiple values from a function


2.
3. def circle(r):
4. area = 3.14*r*r
5. circumfurence = 2*3.14*r
6. return area,circumfurence
7.
8. # calling the function and extracting ghe value
9. a,c = circle(10)
10. print(f"Area of a circle is {a}, circumference is {c}")

Passing different data structures to a function:

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.

Here is an example of passing an entire list to a given 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)

A simpler way is by using set()

Take the list, pass it to the set it will remove the duplicate elements.

Then convert the set back into a list:

1. def remove_duplicates(lst):
2. return list(set(lst))

Local & global variables.

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.

Let's take an example to understand global and local variables.

1. count = 10 #this is called a global variable


2. print(count)
3.
4. def add():
5. # when we declare a variable inside a function it becomes a local
variable
6. # scope of a global variable is limited to the function, we cannot
access
7. # its value outside the fuction
8.
9. count = 20
10. print(count)
11.
12. add()

Let’s take another example

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.

A variable created in one function cannot be accessed in other function either.

Let’s create two functions with variable count.


1. def add():
2. count =1
3. print(count)
4.
5. def sub():
6. count =2
7.
8. print(count)
9.
10. sub()
11. add()

Accessing global variable inside a function

1. count = 10
2.
3. def increment():
4. print(count)
5.
6.
7. increment()

This will work because count here is a global variable.

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.

We do this using the global keyword.

1. count = 10
2.
3. def increment():
4. global count
5. count = count + 1
6. print(count)
7.
8.
9. increment()

Check if a given string is palindrome:

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.

If the string is found not to be a palindrome, we set the palindrome_flag to false.

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:

1. #formula to calculate emi is: P x R x (1+R)^N / [(1+R)^N-1]


2. #P: Principal loan amount = INR 10,000,00
3.
4. #N: Loan tenure in months = 120 months
5.
6. #R: Interest rate per month [7.2/12/100] = 0.006
7.
8. def emi_calculator(principal,rate,time):
9. #calculate the monthly rate
10. r = rate/12/100
11. emi = (principal * r * (1+r)**time) / ((1+r)**time -1 )
12. return emi
13.
14. #checking the function
15. print(emi_calculator(4858900, 8.75, 240))

Recursion:

Recursion in python, in simple term means a function calling itself.

1. def hello():
2. print('Hello')
3. hello()
4.
5.
6. hello()

How factorial is calculated mathematically:

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

Variable length positional arguments:

In some cases we don’t know the number of arguments we need to pass to a function.

Example:

A function sum which can accepts any number of numbers to be added.

Hence to create a function that can accept variable number of arguments we use
variable length arguments.

Variable length arguments are defined by *args.

When we pass arguments to *args it stores it in a tuple.

A program that can add any numbers passed to it.

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)

Variable length keyword arguments:

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.

Let’s take an example to understand this.

1. def chocolate():
2. print('chocolate')
3. chocolate()

When we call this, it simply prints chocolate.

Now let’s say I want to add a wrapper to the chocolate which prints wrapper and
wrapper before and after chocolate.

To do this, we use a decorator function.

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.

However, instead of that we can also use a simpler way.

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:

Decorators can be reused as well.

The decorator we used for wrapping can also be used for another function as well.

let’s create another function called cake.

1. @decorator
2. def cake():
3. print('cake')
4.
5. cake()

Decorating functions which accept an argument:

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

Now this works.

However when we now try to use the same decorator with chocolate it wont work
because we have not passed in name there.

Try doing it:

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")

Now both of them work well.

Decorating functions that return a value:

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

Now let’s create a decorator for it:

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))

You might also like