Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
138 views

Python Course by Yogesh

a course of python which covers the syllabus of rtmnu a very good guide for students who are persuing in rtmnu it has a very simple language its information is collected using chat gpt

Uploaded by

Yogesh Khandare
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
138 views

Python Course by Yogesh

a course of python which covers the syllabus of rtmnu a very good guide for students who are persuing in rtmnu it has a very simple language its information is collected using chat gpt

Uploaded by

Yogesh Khandare
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 87

complete python

course by yogesh
Electrical engg.

Yogesh 1/21/23 Python


YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

CHAPTER 1: - INTRODUCTION TO PYTHON

❖ Introduction to python
Python is a high-level, interpreted programming language that is widely
used for web development, scientific computing, data analysis, artificial
intelligence, and other applications. It is known for its simple syntax, which
makes it easy to learn and understand. Python also has a large and active
community, which means there are many resources available for learning and
troubleshooting. Some popular Python libraries include NumPy, pandas, and
scikit-learn for data analysis, and TensorFlow and PyTorch for machine learning.

❖ What is python
Python is a high-level, interpreted programming language that is widely
used for web development, scientific computing, data analysis, artificial
intelligence, and other applications. It was first released in 1991 by Guido van
Rossum and it has become one of the most popular programming languages in
the world. Python is known for its simple and easy-to-read syntax, which makes
it an excellent choice for beginners. Its versatility and wide range of libraries also
make it a powerful tool for experienced programmers. Python's libraries and
frameworks such as NumPy, pandas, TensorFlow and Pytorch are used in Data
Science, Machine Learning and AI. Python also has a strong support for object-
oriented, imperative and functional programming or procedural styles. Python is
also platform-independent, meaning that code written on one platform can run on
other platforms without modification.

❖ Operators
Python operators are special symbols in Python that carry out arithmetic
or logical computation. The value that the operator operates on is called the
operand. For example:
• Arithmetic operators: +, -, *, /, %, **, //
• Comparison operators: ==, =, >, <, >=, <=

P a g e 1 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

• Logical operators: and, or, not


• Assignment operators: =, +=, -=, *=, /=, %=, **=, //=
• Identity operators: is, is not
• Membership operators: in, not in
• Bitwise operators: &, |, ^, ~, <<, >>
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication and division, whereas logical operators are used to
perform logical operations like and, or, not. The comparison operators are used to
compare values and return a Boolean value (True or False). The assignment
operators are used to assign values to variables. The identity operators are used to
compare the memory locations of two objects, and the membership operators are
used to test whether a value or variable is found in a sequence. Bitwise operators are
used to perform bit-level operations on integers

❖ Identifier
In Python, an identifier is a name given to a variable, function, class,
module, or other object. Identifiers in Python must follow certain rules:
1. They must begin with a letter or an underscore (_).
2. They can contain letters, digits, and underscores.
3. They are case-sensitive, meaning that myVariable and myvariable are
considered different identifiers.
4. They cannot be a Python keyword. Python has a set of reserved words that
cannot be used as identifiers. Examples of keywords include if, else, for,
while, def, class, etc.
5. They should be descriptive and self-explanatory
Some examples of valid Python identifiers are: my_variable, counter,
process_data, class_name.

P a g e 2 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

It is a best practice to use meaningful and self-explanatory names for the variables
and functions, and also following a naming convention like snake case or CamelCase
for the variables and functions

❖ Relational operator
In Python, relational operators are used to compare values and determine
their relationship. The result of a relational operator is always a Boolean value
(True or False). The following are the relational operators in Python:
• ==: Equality operator, returns True if the values on either side of the operator
are equal.
• ! =: Not equal to operator, returns True if the values on either side of the
operator are not equal.
• >: Greater than operator, returns True if the value on the left side of the
operator is greater than the value on the right side.
• <: Less than operator, returns True if the value on the left side of the operator
is less than the value on the right side.
• >=: Greater than or equal to operator, returns True if the value on the left side
of the operator is greater than or equal to the value on the right side.
• <=: Less than or equal to operator, returns True if the value on the left side of
the operator is less than or equal to the value on the right side.
Example:

P a g e 3 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ User input and output


In Python, there are several ways to get input from the user and display output.
1. input() function: The input() function is used to get input from the user. It
takes an optional string argument, which is used as a prompt for the user. The
function returns the input entered by the user as a string.

Example:
name = input("What is your name? ")
print("Hello, " + name + "!")
2. print() function: The print() function is used to display output. It takes one
or more arguments, which can be strings, numbers, variables, or expressions,
and prints them to the screen.

Example:
x=5
y = 10
print("The sum of", x, "and", y, "is", x + y)
3. print(f"{}") function: This function is used to display output by using the
format specifier {}. It is more powerful than the print() function and it allows
to embed expressions inside string literals, using curly braces {}.
Example:
x=5
y = 10
print(f"The sum of {x} and {y} is {x+y}")
It is important to note that in all cases, the input and output are always in the form
of strings, so if you want to use them as numbers, you'll have to cast them using the
appropriate data type.

P a g e 4 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

CHAPTER 2: - DATA TYPES OF PYTHON


❖ String
strings can be created by enclosing the character or the sequence of
characters in the quotes. Python allows us to use single quotes, double quotes, or
triple quotes to create strings. Strings are Arrays. Like many other popular
programming languages, strings in Python are arrays of bytes representing
Unicode characters. Python has a built-in string class named "str" with many
handy features (there is an older module named "string" which you should not
use). A string is a data structure in Python that represents a sequence of
characters. It is an immutable data type, meaning that once you have created it,
you cannot change it. The syntax for raw strings is exactly the same as for normal
strings with the exception of the raw string operator, the letter "r," which precedes
the quotation marks. String indexing in Python is zero-based: the first character
in the string has index 0, the next has index 1, and so on. The index of the last
character will be the length of the string minus one.
a string is a sequence of characters enclosed in quotation marks (either
single or double quotes). Strings are used to represent text, and they are one of
the most basic data types in Python.

Example:

You can access individual characters in a string using indexing. In Python,


the index of the first character is 0.

P a g e 5 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

You can also use negative indexing to access characters from the end of the string.

Python also has several built-in methods for working with strings, such as:
• len(): returns the number of characters in a string
• str.upper(): returns the string in uppercase
• str.lower(): returns the string in lowercase
• str.replace(old, new): replaces all occurrences of the old string with the new
string
• str.split(separator): splits the string into a list of substrings using the
separator
• str.strip(): removes leading and trailing whitespace from the string
For more advanced string manipulation, Python also has a module called
re which stands for regular expressions, it allows to perform complex string
search and replace operations.

Example :-

P a g e 6 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

It is also possible to concatenate and repeat strings using the + and *


operator respectively.

❖ Indexing and slicing


In Python, indexing and slicing are used to access and manipulate parts of a string,
list, tuple, or other sequence data types.
❖ Indexing:
In Python, indexing is used to access individual elements of a sequence by their
position or index. Python uses zero-based indexing, which means that the first
element has an index of 0, the second element has an index of 1, and so on.

You can also use negative indexing to access characters from the end of the string.

P a g e 7 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

Slicing: Slicing is used to extract a substring from a string or a subsequence from a


list, tuple, or other sequence data type. The slice operator [:] is used to extract a
substring or a subsequence. The syntax is sequence[start:stop:step], where start is
the index of the first element, stop is the index of the last element, and step is the
number of steps between each element. If step is not specified, it defaults to 1.

It is important to note that the stop index is not included in the slice, so if you want
to extract the last n characters of a string, you would use the stop index as -n and
step -1

The same applies to lists, tuples, and other sequence data types. You can use slicing
to extract a sublist, subtuple, etc

Slicing can also be used to modify the elements of a list, but it's important to note
that it creates a new list, rather than modifying the original list.

P a g e 8 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ Methods for string


In Python, strings have built-in methods that can be used to manipulate and
perform operations on them. Here are some of the most commonly used string
methods in Python:
• str.upper(): returns the string in uppercase.
• str.lower(): returns the string in lowercase.
• str.capitalize(): returns a copy of the string with the first character capitalized
and the rest in lowercase.
• str.title(): returns a copy of the string with the first letter of each word
capitalized and the rest in lowercase.
• str.strip(): returns a copy of the string with leading and trailing whitespace
removed.
• str.lstrip(): returns a copy of the string with leading whitespace removed.
• str.rstrip(): returns a copy of the string with trailing whitespace removed.
• str.replace(old, new): replaces all occurrences of the old string with the new
string.
• str.split(separator): splits the string into a list of substrings using the
separator.
• str.find(substring): returns the index of the first occurrence of the substring
in the string, or -1 if the substring is not found.
• str.count(substring): returns the number of occurrences of the substring in
the string.
• str.startswith(substring): returns True if the string starts with the substring,
or False otherwise.
• str.endswith(substring): returns True if the string ends with the substring, or
False otherwise.
• str.isalnum(): returns True if the string contains only alphanumeric characters
and is not empty, or False otherwise.
• str.isalpha(): returns True if the string contains only alphabetical characters
and is not empty, or False otherwise.
• str.isdigit(): returns True if the string contains only digits and is not empty,
or False otherwise.

P a g e 9 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

• str.join(iterable): returns a string in which the elements of the iterable are


concatenated with the string as a separator.
These are just a few examples of the string methods available in Python. There
are many more methods that can be used to perform various operations on strings,
depending on your specific needs.
Example:

❖ Isupper
The str.isupper() method in Python is used to check if all the
characters in a string are uppercase. It returns True if all the characters in the string
are uppercase, and False if any of the characters are lowercase

If you want to check for only alphabets in uppercase and ignore digits, spaces and
special characters, you can use a regular expression to match uppercase characters.

P a g e 10 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ Upper
The str.upper() method in Python is used to convert all the characters in a string to
uppercase. It returns a new string with all the characters in uppercase. This method
does not modify the original string, instead, it returns a new string with the converted
characters.
Example:

As you can see in the example above, the upper() method is used to convert the string
"Hello World!" to "HELLO WORLD!" .
It is important to note that the upper() method is also case sensitive, meaning that it
does not convert special characters or numbers, it only converts the alphabets to
uppercase.
You can also use the upper() method on variables that are already in uppercase, it
will return the same string.

You can also use the upper() method on variables that contain numbers or special
characters, it will return the same string with no changes.

P a g e 11 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

It is important to note that the upper() method is a string method, and it can only be
used on string type variable.
Lower
The str.lower() method in Python is used to convert all the characters in a string to
lowercase. It returns a new string with all the characters in lowercase. This method
does not modify the original string, instead, it returns a new string with the converted
characters.

Here's an example:

As you can see in the example above, the lower() method is used to convert the
string "Hello World!" to "hello world!" .
It is important to note that the lower() method is also case sensitive, meaning that
it does not convert special characters or numbers, it only converts the alphabets to
lowercase.
You can also use the lower() method on variables that are already in lowercase, it
will return the same string.

It's worth noting that this method only converts alphabetical characters to lowercase
and leaves the digits, special characters and spaces unchanged.

P a g e 12 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

The .lower() method is commonly used when working with strings that need to be
compared or searched, as case-insensitivity is often desired in these cases. It's also
useful when you want to normalize the case of a string for further processing.
❖ Capitalize

The str.capitalize() method in Python is used to convert the first character of a string
to uppercase and the rest of the characters to lowercase. It returns a new string with
the first character capitalized and the rest in lowercase. This method does not modify
the original string, instead, it returns a new string with the converted characters.
Example:

As you can see in the example above, the capitalize() method is used to convert the
string "Hello World!" to "Hello world!" .
It is important to note that the capitalize() method is also case sensitive, meaning
that it only converts the first character of the string to uppercase, it doesn't convert
special characters or numbers.
You can also use the capitalize() method on variables that are already capitalized,
it will return the same string.

P a g e 13 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

You can also use the capitalize() method on variables that contain numbers or
special characters, it will return the same string with the first character capitalized.

It is important to note that the capitalize() method is a string method, and it can only
be used on string type variables.
❖ Title
The str.title() method in Python is used to convert the first character of each
word in a string to uppercase and the rest of the characters to lowercase. It returns a
new string with the first letter of each word capitalized and the rest in lowercase.
This method does not modify the original string, instead, it returns a new string with
the converted characters.
Example:-

As you can see in the example above, the title() method is used to convert the string
"Hello World! How are you today?" to "Hello World! How Are You Today?" .
It is important to note that the title() method is also case sensitive, meaning that it
only converts the first character of each word in a string to uppercase, it doesn't
convert special characters or numbers.
You can also use the title() method on variables that are already in titlecase, it will
return the same string.

P a g e 14 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

You can also use the title() method on variables that contain numbers or special
characters, it will return the same string with the first letter of each word capitalized.

It is important to note that the title() method is a string method, and it can only be
used on string type variables.
❖ Strip
The .strip() method in Python is a string method that removes whitespace characters
from the beginning and end of a string. This method does not take any arguments,
and it returns a new string with the leading and trailing whitespaces removed. The
original string remains unchanged.
The whitespace characters that will be removed by the .strip() method include
spaces, tabs, and newlines.
Here's an example:

You can also use the str.strip() function to remove leading and trailing whitespaces
from a string.

P a g e 15 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

If you want to remove leading and trailing whitespaces of a string only at the left or
right side, you can use .lstrip() and .rstrip() methods respectively.

The .strip() method is useful when you want to clean up text data, for example when
you read data from a file or user input. It can also be used to remove unwanted
whitespace from a string before further processing.
❖ Replace
The .replace(old, new) method in Python is a string method that replaces all
occurrences of a substring with another substring in a string. This method takes two
arguments: the first argument is the substring that you want to replace, and the
second argument is the new substring that will replace it. The method returns a new
string with the specified replacement. The original string remains unchanged.

Here's an example:

You can also use the str.replace() function to replace a substring in a string.

P a g e 16 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

It's worth noting that the .replace() method only replaces the first occurrence of the
substring by default. If you want to replace all occurrences of the substring, you can
use string.replace(old, new, count) where count is the number of occurrences you
want to replace.

The .replace() method is useful when you want to make a specific change to a string.
It's commonly used when you want to update specific parts of a string, for example,
when you want to change the name of a variable in a program or update a word in a
sentence.
❖ Split
The .split(sep) method in Python is a string method that splits a string into a list of
substrings using a specified separator. The method takes one argument, which is the
separator (sep) that you want to use to split the string. The method returns a list of
substrings that are obtained by splitting the original string at each occurrence of the
specified separator. The original string remains unchanged.
Here's an example:

P a g e 17 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

You can also use the str.split() function to split a string into a list of substrings.

It's worth noting that if the separator is not found in the string, the method returns a
list containing the original string.

By default, the .split() method splits a string into substrings using whitespace
characters (spaces, tabs, and newlines) as the separator. If you want to split a string
using a different separator, you can pass it as the argument to the method. The .split()
method is useful when you want to extract specific parts of a string, for example,
when you want to extract words from a sentence or fields from a CSV file.
❖ Join
The .join(iterable) method in Python is a string method that joins a list of strings
into a single string using the string on which the method is called as a separator. This
method takes one argument, which is an iterable (e.g. list, tuple, etc) of strings that
you want to join. The method returns a new string that is created by concatenating
the elements of the iterable, separated by the string on which the method is called.
The original string and the iterable remains unchanged.
Here's an example:

P a g e 18 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

You can also use the str.join() function to join a list of strings into a single string.

It's worth noting that the iterable passed to the .join() method must be an iterable of
strings. If it contains any other type of elements, a TypeError will be raised.

The .join() method is useful when you want to create a single string from a list of
strings, for example, when you want to create a sentence from a list of words or
create a URL from a list of path segments.
❖ Find
The .find(substring) method in Python is a string method that returns the index of
the first occurrence of a substring in a string. The method takes one argument, which
is the substring that you want to search for. The method returns the index of the first
occurrence of the substring, or -1 if the substring is not found in the string. The
original string remains unchanged.
Here's an example:

P a g e 19 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

You can also use the str.find() function to find the first occurrence of a substring in
a string.

It's worth noting that the .find() method is case-sensitive and only returns the index
of the first occurrence of the substring. If you want to find all occurrences of a
substring, you can use a loop and call the .find() method in each iteration starting
from the index returned by the previous call.

The .find() method is useful when you want to check if a specific substring exists in
a string and find its location if it does. It's commonly used in situations

❖ Count
The .count(substring) method in Python is a string method that returns the number
of occurrences of a substring in a string. The method takes one argument, which is
the substring that you want to count. The method returns the number of occurrences
of the substring in the string. The original string remains unchanged.

P a g e 20 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

Here's an example:

You can also use the str.count() function to count the number of occurrences of a
substring in a string.

It's worth noting that the .count() method is case-sensitive, and it returns the number
of exact occurrences of the substring in the string. If you want to count the number
of occurrences of a substring regardless of its case, you can convert the string and
the substring to lowercase or uppercase before calling the .count() method.

The .count() method is useful when you want to count the number of occurrences of
a specific substring in a string, for example, when you want to count the number of
times a word appears in a text or count the number of times a specific character
appears in a string. It's commonly used in situations where you need to analyze text
data.

P a g e 21 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ Startswith
The .startswith(prefix) method in Python is a string method that checks if a string
starts with a specified prefix. The method takes one argument, which is the prefix
that you want to check for. The method returns True if the string starts with the
specified prefix, and False otherwise. The original string remains unchanged.
Here's an example:

You can also use the str.startswith() function to check if a string starts with a
specified prefix.

It's worth noting that the .startswith() method is case-sensitive, and it only checks
if the string starts with the exact prefix. If you want to check if the string starts with
a prefix regardless of its case, you can convert the string and the prefix to lowercase
or uppercase before calling the .startswith() method.

The .startswith() method is useful when you want to check if a string starts with a
specific prefix, for example, when you want to check if a file name has a specific
extension or check if a URL starts with 'https://'. This method can also be used to
validate user input and filter out unwanted inputs.

P a g e 22 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ Endswith
The .endswith(substring) method in Python is a string method that checks if a string
ends with a specified substring. The method takes one argument, which is the
substring that you want to check for. The method returns True if the string ends with
the specified substring and False otherwise. The original string remains unchanged.
Here is an example:

t's worth noting that the .endswith() method is case-sensitive and only checks if the
string ends with the exact substring. If you want to check if the string ends with a
substring regardless of its case, you can convert the string and the substring to
lowercase or uppercase before calling the .endswith() method.

The .endswith() method is useful when you want to check if a string ends with a
specific substring, for example, when you want to check if a file name ends with a
specific extension, or if a URL ends with a specific path. This method can also be
used to validate user input and filter out unwanted inputs.
It's also useful to extract specific part of string, such as extracting the file extension
from a file name.
It's worth noting that the .endswith() method can also take a tuple of substrings as
its argument, in that case it will check if the string ends with any of the given
substrings and return True if it does.

P a g e 23 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ List
A list in Python is a collection of items, similar to an array in other programming
languages. Lists are ordered, meaning that the items in a list have a specific order,
and they are mutable, meaning that items can be added, removed, or changed. Lists
are created by placing a comma-separated sequence of items inside square brackets
[].
Examples:

You can access individual items in a list using indexing. In Python, the index of the
first item is 0.

You can also use negative indexing to access items from the end of the list

P a g e 24 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

Method for list

In Python, lists have built-in methods that can be used to manipulate and
perform operations on them. Here are some of the most commonly used list
methods in Python:
• list.append(item): adds an item to the end of the list.
• list.extend(iterable): adds all the items in an iterable (e.g. list, tuple) to the
end of the list.
• list.insert(index, item): inserts an item at a specific index in the list.
• list.remove(item): removes the first occurrence of an item from the list.
• list.pop(index): removes and returns the item at a specific index in the list. If
no index is specified, the last item is removed and returned.
• list.clear(): removes all items from the list.
• list.index(item): returns the index of the first occurrence of an item in the list.
• list.count(item): returns the number of occurrences of an item in the list.
• list.sort(): sorts the items in the list in ascending order.
• list.reverse(): reverses the order of the items in the list.
• list.copy(): returns a shallow copy of the list.
Example:

P a g e 25 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ Indexing in list
In Python, you can access the items of a list by their index, which is the position of
the item in the list, starting from 0. You can use the square brackets [] to access an
item by its index.
numbers = [1, 2, 3, 4, 5]
print(numbers[0]) # Output: 1
print(numbers[2]) # Output: 3
You can also use negative indexing to access items from the end of the list.
numbers = [1, 2, 3, 4, 5]
print(numbers[-1]) # Output: 5
print(numbers[-3]) # Output: 3
You can use the index() method to get the index of an item in the list. This method
takes one argument, which is the item whose index you want to find. It returns the
index of the first occurrence of the item in the list or throws a ValueError if the item
is not found.
numbers = [1, 2, 3, 4, 5]
print(numbers.index(3)) # Output: 2

It's worth noting that if the list contains duplicate items, the index() method returns
the index of the first occurrence of the item.
You can also use the in keyword to check if an item is in a list
numbers = [1, 2, 3, 4, 5]
print(3 in numbers) # Output: True

You can use the list indexing and the in keyword to access and check the presence
of an element in a list. This is a very common operation when working with lists.

P a g e 26 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ Slicing in list
In Python, you can use slicing to access a range of items in a list. Slicing is done by
specifying the start and end indexes separated by a colon :. The start index is
inclusive and the end index is exclusive, meaning that the slice includes the items at
the start index and all the items before the end index.
numbers = [1, 2, 3, 4, 5]
print(numbers[1:4]) # Output: [2, 3, 4]

You can also leave the start or end index blank to slice from the beginning or to the
end of the list respectively.

numbers = [1, 2, 3, 4, 5]
print(numbers[:3]) # Output: [1, 2, 3]
print(numbers[2:]) # Output: [3, 4, 5]

You can also use negative indexes in slicing to count from the end of the list.
numbers = [1, 2, 3, 4, 5]
print(numbers[-3:-1]) # Output: [3, 4]
You can also use slicing to create a new list, which is a copy of a slice of the original
list. This is called slicing a list, because the new list is a "slice" of the original list.
numbers = [1, 2, 3, 4, 5]
new_numbers = numbers[1:4]
print(new_numbers) # Output: [2, 3, 4]
Slicing is a very useful feature when working with lists, it allows you to easily access
and manipulate a range of items in a list.

P a g e 27 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ Copy in list
In Python, when you create a new variable and assign a list to it, the new variable is
actually a reference to the original list. This means that changes made to the new
variable will also affect the original list. To create a true copy of a list, you can use
the copy() method or slicing with no indexes
original_list = [1, 2, 3, 4, 5]
new_list = original_list.copy()
new_list2 = original_list[:]
Both new_list and new_list2 are now independent copies of the original list and any
changes made to them will not affect the original list.
It's worth noting that if the list contains other mutable objects, like lists or
dictionaries, the copy method only creates a shallow copy of the list, which means
that the new list will still contain references to the original objects. To create a deep
copy of the list, you can use the copy module's deepcopy() method.
import copy
original_list = [[1,2], [3,4]]
deep_copy = copy.deepcopy(original_list)
Here deep_copy is an independent copy of the original_list and the nested lists
inside original_list are also copied.
It's important to understand the difference between a shallow copy and a deep copy,
especially when working with nested data structures.
In Python, there are two types of copying lists: shallow copy and deep copy.
A shallow copy of a list creates a new list, but the elements inside the list are still
references to the original elements. This means that if the original elements are
mutable (e.g. lists, dictionaries), any changes made to them will be reflected in both
the original and the copied list. Here is an example of creating a shallow copy of a
list using the list() constructor or the slicing [:] operator:

P a g e 28 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

original_list = [[1, 2], 3]


shallow_copy = list(original_list)
shallow_copy_2 = original_list[:]
shallow_copy[0][0] = 0
print(original_list) # Output: [[0, 2], 3]

A deep copy of a list creates a new list, and creates new copies of the elements inside
the list. This means that if the original elements are mutable, changes made to them
will not affect the deep copied list. Here is an example of creating a deep copy of a
list using the copy module:

import copy
original_list = [[1, 2], 3]
deep_copy = copy.deepcopy(original_list)
deep_copy[0][0] = 0
print(original_list) # Output: [[1, 2], 3]
It's worth noting that for immutable elements like integers or strings, a shallow copy
and deep copy will behave the same, as these elements can't be modified.
In most of the cases, a shallow copy is enough, but when you work with

❖ Methods for list


In Python, lists have several built-in methods that can be used to manipulate and
access the items in a list. Here are some of the most commonly used list methods:

• append(item): Adds an item to the end of the list

• extend(iterable): Adds all the items from an iterable (such as a list or a tuple)
to the end of the list

• insert(index, item): Inserts an item at a specific index in the list

P a g e 29 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

• remove(item): Removes the first occurrence of an item from the list

• pop(index): Removes and returns an item from a specific index in the list, or
the last item if no index is provided

• index(item): Returns the index of the first occurrence of an item in the list

• count(item): Returns the number of occurrences of an item in the list

• sort(): Sorts the items in the list in ascending order

• reverse(): Reverses the order of the items in the list

• clear(): Removes all items from the list

• copy(): Returns a shallow copy of the list

These methods allow you to add, remove, and modify items in a list, as well as access
and analyze the items in a list. It's important to keep in mind that many of these
methods modify the original list, so be careful when working with lists that you want
to keep unchanged.

❖ Len
In Python, the len() function returns the number of items in an iterable, such as a list,
tuple, or string. The function takes one argument, which is the iterable that you want
to get the length of.
Here's an example of how to use the len() function with a list:
numbers = [1, 2, 3, 4, 5]
print(len(numbers)) # Output: 5
Here's an example of how to use the len() function with a string:
string = "Hello World"
print(len(string)) # Output: 11

P a g e 30 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

The len() function can be used to get the length of any iterable, not only lists, but
also tuples, strings, sets, etc. It's a very useful function when working with different
data types and it's commonly used to loop over sequences, check the number of items
in a container or to check the length of a string or a file.
It's worth noting that the len() function returns the number of elements in the iterable,
not the size in bytes, which can be obtained using the sys.getsizeof() function.

❖ Append
In Python, the append() method is used to add an item to the end of a list. The
method takes one argument, which is the item you want to add. The item can be of
any data type.

Here's an example of how to use the append() method:


numbers = [1, 2, 3, 4, 5]
numbers.append(6)
print(numbers) # Output: [1, 2, 3, 4, 5, 6]As you can see in the example above, the
append() method is called on the list numbers, and the integer 6 is passed as the
argument. This adds the integer 6 to the end of the list.
It's worth noting that the append() method modifies the original list, so if you want
to keep the original list intact, you should create a copy of the list before calling the
append() method.

original_numbers = [1, 2, 3, 4, 5]
new_numbers = original_numbers.copy()
new_numbers.append(6)
print(original_numbers) # Output: [1, 2, 3, 4, 5]
print(new_numbers) # Output: [1, 2, 3, 4, 5, 6]

The append() method is very useful when you want to add an item to a list. It's a
simple and straightforward method that can be used to build lists dynamically, for
example when reading data from a file or user input.

P a g e 31 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ Extend
In Python, the extend() method is used to add multiple items to a list. The method
takes an iterable (such as a list, tuple, or string) as an argument, and it adds each item
of the iterable to the end of the list.
Here's an example of how to use the extend() method:
numbers = [1, 2, 3, 4, 5]
numbers.extend([6, 7, 8])
print(numbers) # Output: [1, 2, 3, 4, 5, 6, 7, 8]
As you can see in the example above, the extend() method is called on the list
numbers, and the list [6, 7, 8] is passed as the argument. This adds the integers 6, 7,
and 8 to the end of the list.
It's worth noting that the extend() method modifies the original list, so if you want
to keep the original list intact, you should create a copy of the list before calling the
extend() method.

original_numbers = [1, 2, 3, 4, 5]
new_numbers = original_numbers.copy()
new_numbers.extend([6, 7, 8])
print(original_numbers) # Output: [1, 2, 3, 4, 5]
print(new_numbers) # Output: [1, 2, 3, 4, 5, 6, 7, 8]

The extend() method is useful when you want to add multiple items to a list at once,
instead of adding them one by one using the append() method. It's also useful when
you want to concatenate two lists together, you can use extend() method on one of
the list to add the items of another list to it. It's a useful method when you want to
build lists dynamically, for example when reading data from a file or user input. It's
also useful when working with large data sets, it can save time when compared to
using append() method repeatedly.

P a g e 32 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ Sort
In Python, the sort() method is used to sort the items of a list in ascending order.
The method modifies the original list and does not return a new list.

Here's an example of how to use the sort() method:


numbers = [5, 2, 1, 4, 3]
numbers.sort()
print(numbers) # Output: [1, 2, 3, 4, 5]

As you can see in the example above, the sort() method is called on the list numbers,
and it sorts the items in ascending order.
It's worth noting that the sort() method only works with lists that contain items of
the same data type. If the list contains items of different data types, you will get a
TypeError.
You can also sort the list in descending order by passing the argument reverse =
True in the sort method.

numbers = [5, 2, 1, 4, 3]
numbers.sort(reverse = True)
print(numbers) # Output: [5, 4, 3, 2, 1]

The sort() method is useful when you want to sort the items of a list in a specific
order, for example, when you want to find the largest or smallest item in a list, or
when you want to display items in a specific order. It's also useful when working
with large data sets, it makes it easy to find and access specific elements. It's also
useful when you want to group or classify similar items in a list. It's important to
keep in mind that the sort method modifies the original list and does not return a new
list.
❖ Insert
In Python, the insert() method is used to insert an item at a specific position in a list.
The method takes two arguments: the index where you want to insert the item, and
the item itself.

P a g e 33 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

Here's an example of how to use the insert() method:


numbers = [1, 2, 3, 4, 5]
numbers.insert(2, 0)
print(numbers) # Output: [1, 2, 0, 3, 4, 5]

As you can see in the example above, the insert() method is called on the list
numbers, and the integer 0 is inserted at index 2 of the list.
It's worth noting that if the index passed to the insert() method is greater than the
length of the list, the item will be added to the end of the list. Also, if the index
passed is a negative number, it will be treated as counting from the end of the list.

numbers = [1, 2, 3, 4, 5]
numbers.insert(5, 0)
print(numbers) # Output: [1, 2, 3, 4, 5, 0]
numbers = [1, 2, 3, 4, 5]
numbers.insert(-1, 0)
print(numbers) # Output: [1, 2, 3, 4, 0, 5]
The insert() method is useful when you want to add an item at a specific position in
a list, for example, when you want to insert an item at the beginning or middle of a
list. It's also useful when you want to insert an item at a specific position based on
some condition or logic, for example when reading data from a file or user input. It's
important to keep in mind that the insert method modifies the original list. It's also a
relatively expensive

P a g e 34 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ Delete
In Python, there are several ways to delete items from a list:
• The del statement can be used to delete an item from a list by its index.

numbers = [1, 2, 3, 4, 5]
del numbers[2]
print(numbers) # Output: [1, 2, 4, 5]

• The remove() method can be used to remove the first occurrence of a specific
item from a list.

numbers = [1, 2, 3, 4, 5]
numbers.remove(3)
print(numbers) # Output: [1, 2, 4, 5]

• The pop() method can be used to remove and return an item from a specific
index in the list. If no index is provided, the method removes and returns the
last item.

numbers = [1, 2, 3, 4, 5]
numbers.pop(2)
print(numbers) # Output: [1, 2, 4, 5]
• The clear() method can be used to remove all items from a list.

numbers = [1, 2, 3, 4, 5]
numbers.clear()
print(numbers) # Output: []

It's important to note that all the above methods modify the original list. It's also
worth noting that the remove() method throws a ValueError if the item is not found
in the list. It's a good practice to

P a g e 35 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ Pop
In Python, the pop() method is used to remove and return an item from a specific
index in a list. The method takes an optional single argument, which is the index of
the item you want to remove. If no index is provided, the method removes and
returns the last item in the list.
Here's an example of how to use the pop() method:
numbers = [1, 2, 3, 4, 5]
item = numbers.pop(2)
print(item) # Output: 3
print(numbers) # Output: [1, 2, 4, 5]
As you can see in the example above, the pop() method is called on the list numbers,
and the item at index 2 (which is 3) is removed and returned.
Here is an example of how to use the pop() method without passing any argument.
numbers = [1, 2, 3, 4, 5]
item = numbers.pop()
print(item) # Output: 5
print(numbers) # Output: [1, 2, 3, 4]
As you can see in this example, the pop() method is called on the list numbers, and
the last item in the list is removed and returned.
The pop() method is useful when you want to remove an item from a specific
position in a list, for example, when you want to remove the first or last item in a
list. It's also useful when you want to remove an item based on some condition or
logic, for example when reading data from a file or user input. It's important to

P a g e 36 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ Max, Min, Sum, Count


In Python, several built-in functions are available for working with lists:
• max(iterable): Returns the largest item in an iterable (such as a list or tuple)
• min(iterable): Returns the smallest item in an iterable
• sum(iterable): Returns the sum of all items in an iterable, only works with
numbers
• count(item): Returns the number of occurrences of an item in a list

Here's an example of how to use these functions with a list:


numbers = [1, 2, 3, 4, 5]
print(max(numbers)) # Output: 5
print(min(numbers)) # Output: 1
print(sum(numbers)) # Output: 15
print(numbers.count(3)) # Output: 1

The max() and min() functions are useful when you want to find the largest or
smallest item in a list, respectively. The sum() function is useful when you want to
add up all items in a list of numbers, for example when working with financial data
or statistics. The count() function is useful when you want to find the number of
occurrences of an item in a list, for example when counting the number of times a
specific value appears in a list. It's worth noting that these functions work with any
iterable, not only lists, but also tuples, sets, etc. It's also important to keep in mind
that these functions do not modify the original list, they return a result based on the
original list.

❖ List Comprehensions
In Python, list comprehensions are a concise way to create lists. They allow you to
create a new list by applying an operation to each item in an existing iterable (such
as a list, tuple, or string).

P a g e 37 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

Here's an example of a simple list comprehension:


numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
print(squares) # Output: [1, 4, 9, 16, 25]

As you can see in the example above, the list comprehension [x**2 for x in
numbers] creates a new list squares, containing the squares of each item in the list
numbers.
You can also use conditionals in a list comprehension. Here's an example that creates
a new list containing only the even numbers from a given list:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


even_numbers = [x for x in numbers if x % 2 == 0]
print(even_numbers) # Output: [2, 4, 6, 8, 10]
List comprehensions are a powerful and expressive feature in Python. They allow
you to create new lists, filter items, or perform calculations on the items of an
existing list in a concise and readable way. They are also more efficient than using
a for loop, especially when working with large data sets. It's a good practice to use
list comprehensions when the logic is simple and when the operation you want to
perform on the list is simple and straightforward. It's also worth noting that list
comprehensions can be nested to create more complex lists.

P a g e 38 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ Tuples
❖ Tuples according to Eric Matthes
Eric Matthes, the author of "Python Crash Course: A Hands-On, Project-Based
Introduction to Programming," defines tuples as "an immutable list." This means
that unlike lists, tuples cannot be modified after they are created.

In his book, Matthes uses tuples to store related pieces of information that cannot be
changed, such as the dimensions of a rectangle or the x-y coordinates of a point.
Because tuples are immutable, they provide a way to store data that needs to remain
constant throughout the life of a program.

He also uses tuples to unpack multiple values from a function or to group together
multiple values as a single, composite value.

He also mentions that Tuples are also used to store multiple items in a single
variable. This allows you to access the items by indexing the variable.

He also notes that because tuples are immutable, they are useful when you want to
ensure that data is not accidentally modified. They are also useful in situations where
you want to use multiple values as a single, composite value.

In summary, Eric Matthes defines tuples as an immutable list, they are useful when
you want to store related pieces of information that cannot be changed, unpack
multiple values from a function, group together multiple values as a single,
composite value and when you want to ensure that data is not accidentally modified.

❖ Tuples
Tuples are a built-in data type in Python that are similar to lists, but they are
immutable. This means that once a tuple is created, its items cannot be modified,
added, or removed. Tuples are defined using parentheses () and items are separated
by commas.

P a g e 39 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

Here's an example of a tuple:


coordinates = (3, 4)
You can access the items of a tuple by indexing it, just like you would with a list:
x = coordinates[0]
y = coordinates[1]
print(x) # Output: 3
print(y) # Output: 4
Tuples are commonly used to store related pieces of information that should not be
modified, such as a person's name and age, or the dimensions of an object. They can
also be used to return multiple values from a function.
Tuples are also useful in situations where you want to use multiple values as a single,
composite value and when you want to ensure that data is not accidentally modified.
It's also worth noting that you can use the tuple() function to convert a list or other
iterable into a tuple, and the list() function to convert a tuple into a list.
numbers = [1,2,3,4,5]
tup_numbers = tuple(numbers)
print(tup_numbers) # Output: (1, 2, 3, 4, 5)
You can also use indexing, slicing and other related methods with tuples as well but
you can't change the values of a tuple once it's created.

❖ Discard
In Python, the discard() method is not a built-in method for tuples, because tuples
are immutable and their items cannot be modified, added, or removed.
However, you can use the remove() method to remove an item from a list and then
convert the list back to a tuple.

P a g e 40 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

tup = (1,2,3,4,5)
temp_list = list(tup)
temp_list.remove(4)
tup = tuple(temp_list)

Here, temp_list is a list version of tuple, we use the remove method to remove 4
from the list, and then we convert the list back to tuple.
Alternatively, you can use tuple comprehension to create a new tuple without the
item you want to discard.
tup = (1,2,3,4,5)
tup = tuple(x for x in tup if x != 4)
Here, the tuple comprehension creates a new tuple with only the items that are not
equal to 4.
It's worth noting that discard() is available in set data structure, which is mutable,
unlike tuple. It is used to remove an element from a set if it is present in the set.
s = {1, 2, 3, 4, 5}
s.discard(4)
In this example, 4 is removed from the set if it is present in the set. It's important to
keep in mind that tuples are immutable, so you can't remove or discard items from
them directly, but you can create a new tuple without the item you want to discard

❖ Pop
In Python, the pop() method is not a built-in method for tuples, because tuples are
immutable and their items cannot be modified, added, or removed.
You can use the index() method to find the index of an item in a tuple, and then use
slicing to create a new tuple without that item.

P a g e 41 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

tup = (1,2,3,4,5)
index = tup.index(4)
tup = tup[:index] + tup[index+1:]
Here, the index() method is used to find the index of the item you want to remove,
and then slicing is used to create a new tuple without that item.
Alternatively, you can use tuple comprehension to create a new tuple without the
item you want to remove.

tup = (1,2,3,4,5)
tup = tuple(x for x in tup if x != 4)
Here, the tuple comprehension creates a new tuple with only the items that are not
equal to 4.
It's worth noting that pop() is available in list data structure, which is mutable, unlike
tuple. It is used to remove and return an item from a specific index in the list or the
last item if no index is provided.

numbers = [1, 2, 3, 4, 5]
numbers.pop(2)
In this example, the item at index 2 (which is 3) is removed and returned. It's
important to keep in mind that tuples are immutable, so you can't remove or pop
items from them directly, but you can create a new tuple without the item you want
to remove.

❖ Dictionary in python
In Python, a dictionary is a built-in data structure that stores key-value pairs. It is
also known as a hash map or associative array. A dictionary is defined using curly
braces {} and each item is a key-value pair separated by a colon :. The keys must be
unique and can be of any immutable type (e.g. strings, numbers, tuples) while the
values can be of any type.

P a g e 42 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

Here's an example of a simple dictionary:


person = {'name': 'John Doe', 'age': 30, 'gender': 'male'}
You can access the values of a dictionary by using the keys in square brackets []
name = person['name']
age = person['age']
gender = person['gender']
print(name) # Output: 'John Doe'
print(age) # Output: 30
print(gender) # Output: 'male'
You can also use the get() method to access the values of a dictionary, which returns
None if the key is not found in the dictionary, instead of raising a KeyError.

name = person.get('name')
age = person.get('age')
gender = person.get('gender')
print(name) # Output: 'John Doe'
print(age) # Output: 30
print(gender) # Output: 'male'
Dictionaries are commonly used to store data in a structured way, such as a database
of users or a catalog of products. They are also useful for counting and grouping
items, such as counting the number of occurrences of words in a text.
You can add, modify, and remove items from a dictionary using the assignment
operator =, the update() method, and the del statement, respectively.
It's also worth noting that the keys of a dictionary have to be unique, and duplicate
keys will overwrite the previous value. You can also use dictionary comprehension
which is similar to list comprehensions. It allows you to create a new dictionary by
applying an operation to each item in an existing iterable.

P a g e 43 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

In summary, a dictionary is a built-in data structure in Python that stores key-value


pairs, it is defined using curly braces {} and each item is a key-value pair separated
by a colon :, it is commonly used to store data in a structured way and useful for
counting and grouping items.
❖ Creation method
In Python, there are several ways to create a dictionary:
1. Using curly braces {} and the assignment operator =:
d = {'key1': 'value1', 'key2': 'value2'}
2. Using the dict() constructor:

d = dict(key1='value1', key2='value2')
3. Using a list of tuples as an argument to the dict() constructor:

d = dict([('key1', 'value1'), ('key2', 'value2')])


4. Using a key-value pair list as an argument to the dict() constructor:

d = dict(zip(['key1', 'key2'], ['value1', 'value2']))


5. Using a comprehension:
d = {x: x ** 2 for x in range(10)}
6. Using the fromkeys() method:
d = dict.fromkeys(['a','b','c'], 0)
Each of these methods creates a dictionary with the same key-value pairs. The first
method is the most common way to create a dictionary, while the other methods are
useful in specific situations, such as when creating a dictionary from an existing data
structure like a list of tuples or when creating a dictionary with the same value for
all keys.
The dict() constructor is useful when creating a dictionary from keyword arguments
or a sequence of key-value pairs.

P a g e 44 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

The fromkeys() method creates a new dictionary with keys from the specified
iterable and values set to the specified value.
The comprehension method creates a dictionary by applying an operation to each
item in an existing iterable.
In summary, there are several ways to create a dictionary in Python, using curly
braces and the assignment operator, using the dict() constructor, using a list of tuples,
using a key-value pair list, using a comprehension, or using the fromkeys() method.
❖ Lists of tuples in dictionary
In Python, it is possible to use lists of tuples as the values in a dictionary. Each tuple
in the list would represent a key-value pair, and the first item in the tuple would be
the key and the second item would be the value.

Here's an example of creating a dictionary that has a list of tuples as its values:

data = {'person1': [('name', 'John Doe'), ('age', 30), ('gender', 'male')],

'person2': [('name', 'Jane Smith'), ('age', 25), ('gender', 'female')]}

You can access the values in the list of tuples by using the keys of the dictionary and
then indexing the list and the tuple:

name = data['person1'][0][1]

age = data['person1'][1][1]

gender = data['person1'][2][1]

print(name) # Output: 'John Doe'

print(age) # Output: 30

print(gender) # Output: 'male'

P a g e 45 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

Alternatively, you can convert the list of tuples to a dictionary using the dict()
constructor and then access the values using the keys:

person1 = dict(data['person1'])
name = person1['name']
age = person1['age']
gender = person1['gender']
print(name) # Output: 'John Doe'
print(age) # Output: 30
print(gender) # Output: 'male'

Using lists of tuples in this way can be useful for storing multiple related pieces of
information for each key in the dictionary, and it can be a good way to structure data
when the number of key-value pairs for each key is not fixed.
It's also worth noting that this approach is not very efficient when it comes to
lookups, as you'll have to iterate over the list of tuples to find the desired key-value
pair. If you need to frequently look up values by key, it's better to use a dictionary
of dictionaries, where the key-value pairs are stored in nested dictionaries.
In summary, it is possible to use lists of tuples as the values in a dictionary in python.
Each tuple in the list would represent a key-value pair, and the first item in the tuple
would be the key and the second item would be the value. This approach can be
useful for storing multiple related pieces of information for each key in the
dictionary, but it's not very efficient when it comes to lookups.

P a g e 46 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ List of lists in dictionary


In Python, it is possible to use lists of lists as the values in a dictionary. Each list
would represent a set of related data, and the items in the list would be the individual
pieces of data.
Here's an example of creating a dictionary that has a list of lists as its values:

data = {'person1': [['John Doe', 30, 'male'], ['Jane Smith', 25, 'female']],
'person2': [['Bob Smith', 35, 'male'], ['Samantha Jones', 40, 'female']]}
You can access the values in the list of lists by using the keys of the dictionary and
then indexing the list:

name = data['person1'][0][0]
age = data['person1'][0][1]
gender = data['person1'][0][2]
print(name) # Output: 'John Doe'
print(age) # Output: 30
print(gender) # Output: 'male'
Using lists of lists in this way can be useful for storing multiple sets of related data
for each key in the dictionary, and it can be a good way to structure data when the
number of data sets for each key is not fixed.
It's also worth noting that this approach is not very efficient when it comes to
lookups, as you'll have to iterate over the lists to find the desired data set. If you need
to frequently look up values by key, it's better to use a dictionary of dictionaries,
where the data sets are stored in nested dictionaries.
In summary, it is possible to use lists of lists as the values in a dictionary in python.
Each list would represent a set of related data, and the items in the list would be the
individual pieces of data. This approach can be useful for storing multiple sets of
related data for each key in the dictionary, but it's not very efficient when it comes
to lookups.

P a g e 47 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ Len and del in dictionary


In Python, the len() function can be used to find the number of key-value pairs in a
dictionary. The del statement can be used to remove a specific key-value pair or to
delete the entire dictionary.
Here's an example of using len() to find the number of key-value pairs in a
dictionary:

person = {'name': 'John Doe', 'age': 30, 'gender': 'male'}


print(len(person)) # Output: 3
The del statement can be used to remove a specific key-value pair from a dictionary:

del person['age']
print(person) # Output: {'name': 'John Doe', 'gender': 'male'}
You can also use the pop() method to remove a specific key-value pair and return
its value:
age = person.pop('age')
The del statement can also be used to delete the entire dictionary:

del person
It's worth noting that the del statement raises a KeyError when the key is not found
in the dictionary and the pop() method raises a KeyError if the key is not found and
also returns the value associated with the key.
In summary, the len() function can be used to find the number of key-value pairs in
a dictionary, the del statement can be used to remove a specific key-value pair or to
delete the entire dictionary. The del statement raises a KeyError when the key is not
found in the dictionary and the pop() method raises a KeyError if the key is not
found and also returns the value associated with the key.

P a g e 48 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ Deep and shallow copy in dictionary


In Python, when you create a copy of a dictionary, you have the option of creating
either a shallow copy or a deep copy.
A shallow copy of a dictionary creates a new dictionary object with the same key-
value pairs as the original dictionary, but the keys and values themselves are not
copied. Instead, the new dictionary simply references the same keys and values as
the original dictionary. This means that if you modify the original dictionary, the
changes will be reflected in the shallow copy, and vice versa.
Here's an example of creating a shallow copy of a dictionary using the built-in dict()
function:

original = {'a': [1, 2, 3], 'b': [4, 5, 6]}


shallow_copy = dict(original)
A deep copy of a dictionary creates a new dictionary object with the same key-value
pairs as the original dictionary, but it also creates new objects for the keys and values
themselves. This means that if you modify the original dictionary, the changes will
not be reflected in the deep copy, and vice versa.
Here's an example of creating a deep copy of a dictionary using the copy() method
from the copy module:

import copy
original = {'a': [1, 2, 3], 'b': [4, 5, 6]}
deep_copy = copy.deepcopy(original)
It's worth noting that when the values of a dictionary are mutable (e.g. lists,
dictionaries), the shallow copy shares the same references with the original
dictionary, so changes made to the original dictionary will also be reflected in the
shallow copy. On the other hand, deep copy creates a new object, so the original and
the copy are independent.

P a g e 49 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

In summary, when you create a copy of a dictionary, you have the option of creating
either a shallow copy or a deep copy. A shallow copy creates a new dictionary object
with the same key-value pairs as the original dictionary, but the keys and values
themselves are not copied, a deep copy creates a new dictionary object with the same
key-value pairs as the original dictionary, but it also creates new objects for the keys
and values themselves, so they are not linked.

❖ Methods for dictionary


In Python, there are several built-in methods for working with dictionaries:
1. clear(): Removes all items from the dictionary.
d = {'a': 1, 'b': 2}
d.clear()
print(d) # Output: {}
2. copy(): Returns a shallow copy of the dictionary.

d = {'a': 1, 'b': 2}
d_copy = d.copy()
3. fromkeys(iterable, value): Returns a new dictionary with keys from the
specified iterable and values set to the specified value.

d = dict.fromkeys(['a','b','c'], 0)
4. get(key, default): Returns the value of the specified key, or the default value
if the key is not found in the dictionary.

d = {'a': 1, 'b': 2}
print(d.get('a', 0)) # Output: 1
print(d.get('c', 0)) # Output: 0

P a g e 50 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

5. items(): Returns a view object that contains the key-value pairs of the
dictionary.
d = {'a': 1, 'b': 2}
print(d.items()) # Output: dict_items([('a', 1), ('b', 2)])
6. keys(): Returns a view object that contains the keys of the dictionary.

d = {'a': 1, 'b': 2}
print(d.keys()) # Output: dict_keys(['a', 'b'])

7. pop(key, default): Removes the specified key-value pair from the dictionary
and returns its value, or the default value if the key is not found in the
dictionary.

d = {'a': 1, 'b': 2}
print(d.pop('a', 0)) # Output: 1
print(d.pop('c', 0)) # Output: 0
8. popitem(): Removes and returns an arbitrary key-value pair from the
dictionary.

d = {'a': 1, 'b': 2}
print(d.popitem()) # Output: ('b', 2)
9. setdefault(key, default): Returns the value of the specified key, or the default
value if the key is not found in the dictionary.

d = {'a': 1, 'b': 2}

P a g e 51 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ Dictionary comprehension
In Python, dictionary comprehension is a concise and expressive way to create a new
dictionary by applying an operation to each item in an existing iterable. It has a
similar syntax to list comprehension, but instead of creating a list, it creates a new
dictionary.
Here's an example of using a dictionary comprehension to create a new dictionary
that contains the squares of the numbers from 1 to 5:

squares = {x: x ** 2 for x in range(1, 6)}


print(squares) # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
You can also use dictionary comprehension with conditional statements to filter the
items of the iterable:
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_squares = {x: x ** 2 for x in numbers if x % 2 == 0}
print(even_squares) # Output: {2: 4, 4: 16, 6: 36, 8: 64, 10: 100}

Dictionary comprehension can also be used to create a dictionary from another data
structure, like a list of tuples:

data = [('a', 1), ('b', 2), ('c', 3)]


d = {k: v for k, v in data}
print(d) # Output: {'a': 1, 'b': 2, 'c': 3}

You can also use dictionary comprehension to transform the keys or values of an
existing dictionary

original_dict = {'a': 1, 'b': 2, 'c': 3}


transformed_dict = {k.upper(): v*2 for k, v in original_dict.items()}
print(transformed_dict) # Output: {'A': 2, 'B': 4, 'C': 6}

P a g e 52 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

In summary, dictionary comprehension is a concise and expressive way to create a


new dictionary by applying an operation to each item in an existing iterable. It has a
similar syntax to list comprehension and it can be used to create a new dictionary,
filter items, transform keys or values from an existing dictionary, among other
possibilities.

❖ SETS
In Python, sets are a built-in data type that can store an unordered collection of
unique elements. Sets are similar to lists and dictionaries, but they only store the
keys and do not store any values. Sets are often used to perform mathematical set
operations like union, intersection, difference, etc.
Here's an example of creating a set:

# Using curly braces {}


s = {1, 2, 3}

# Using set() constructor


s = set([1, 2, 3])

# Using set comprehension


s = {x for x in range(1, 4)}
Sets have a number of useful methods, such as:
1. add(element): adds an element to the set
2. update(iterable): adds multiple elements to the set
3. remove(element): removes an element from the set, raises KeyError if the
element is not found in the set

P a g e 53 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

4. discard(element): removes an element from the set, does not raise an error if
the element is not found in the set
5. pop(): removes and returns an arbitrary element from the set
6. clear(): removes all elements from the set
7. union(iterable): returns a new set containing all elements from the original
set and all elements from the specified iterable
8. intersection(iterable): returns a new set containing only the elements that
exist in both the original set and the specified iterable
9. difference(iterable): returns a new set containing only the elements that exist
in the original set but not in the specified iterable
10.symmetric_difference(iterable): returns a new set containing only the
elements that exist in either the original set or the specified iterable, but not in
both
It's worth noting that sets are unordered, so the elements in a set have no index and
order. Also, sets are mutable, you can add or remove items, but cannot change the
items once they are added.
In summary, sets are a built-in data type in python that can store an unordered
collection of unique elements, sets are often used to perform mathematical set
operations like union, intersection, difference, etc, They have a number of useful
methods that you can use to add, remove, and modify the elements in a set, sets are
unordered and mutable.

P a g e 54 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

CHAPTER 3: - FUNCTIONS,LOOPS AND MODULES


❖ Control statement
❖ Conditional statement :-
In Python, conditional statements are used to control the flow of a program by
allowing the program to make decisions based on certain conditions. The two most
commonly used conditional statements are if and if-else.
The basic syntax for an if statement is:

if condition:
# code to be executed if the condition is True

The Basic syntax for an ‘if-else’ statement is :-


if condition:
# code to be executed if the condition is True
else:
# code to be executed if the condition is False
Example:-

In this example, the if statement checks if the value of x is greater than 0. Since it is,
the code inside the if block will be executed and the program will output "x is
positive".

P a g e 55 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

Example:

In this example, the if-else statement checks if the value of x is greater than 0. Since
it is, the code inside the if block will be executed and the program will output "x is
positive". If the value of x was negative, then the code inside the else block would
be executed and the program would output "x is negative".
You can also use the elif statement to check multiple conditions, like this:

In this example, the program first checks if x is greater than 0, if it is not then it will
check if x is less than 0 and if it is not then it will execute the code inside the else
block.
It is important to note that each conditional block should end with a colon ":", and
that the code inside the conditional block should be indented.

P a g e 56 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ Loop statement
In Python, loop statements are used to execute a block of code multiple times. The
two most commonly used loop statements are for and while.
The basic syntax for a for loop is:

for variable in iterable:


# code to be executed for each item in the iterable

The for loop iterates over the elements of an iterable (e.g. list, tuple, string, etc.) and
assigns the current element to a variable on each iteration.
Example:

In this example, the for loop iterates over the elements of the list colors and assigns
the current element to the variable color on each iteration. The program will output:

The basic syntax of ‘while’ loop is

while condition:
# code to be executed while the condition is True

P a g e 57 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

The while loop repeatedly executes the code inside its block as long as the given
condition is true.
Example:

In this example, the while loop will execute as long as the value of x is greater than
0. The program will output:

It is important to note that the while loop will continue executing as long as the
condition is true, so you need to make sure that the condition will eventually become
false, otherwise, the loop will run indefinitely (infinite loop).
You can use the break statement to exit a loop before its normal ending, and the
continue statement to skip the current iteration and move on to the next one.
It is also important to note that the code inside the loop should be indented and each
loop should end with a colon ":".

P a g e 58 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ Control statement
In Python, control statements are used to alter the flow of a program. The three most
commonly used control statements in loops are break, continue, and pass.
break statement: The break statement is used to exit a loop before its normal ending.
When the break statement is executed inside a loop, the loop is immediately
terminated, and the program continues with the next statement after the loop.
Example:

In this example, the for loop starts at 0 and runs through 9. But when the value of i
becomes equal to 5, the break statement is executed, the loop is terminated and the
program continues with the next statement after the loop. The program will output:

continue statement: The continue statement is used to skip the current iteration of
a loop and move on to the next one. When the continue statement is executed inside
a loop, the current iteration is skipped and the program continues with the next
iteration.

P a g e 59 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

Example:

In this example, the for loop starts at 0 and runs through 9. But when the value of i
is even, the continue statement is executed, the current iteration is skipped and the
program continues with the next iteration. The program will output:

pass statement: The pass statement is used as a placeholder in situations where a


statement is required syntactically, but you do not want any code to be executed.
Example:

P a g e 60 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

In this example, the for loop starts at 0 and runs through 9. But when the value of i
becomes equal to 5, the pass statement is executed, and the program continues with
the next iteration without doing anything. The program will output:

❖ Introduction to function
It is important to note that using break, continue, and pass statements correctly can
make the code more readable, and it can help to avoid mistakes and bugs.
Functions are a fundamental concept in computer programming and are used to
organize and structure code. They allow you to encapsulate a specific piece of
functionality and reuse it throughout your code.
In Python, a function is defined using the def keyword, followed by the function
name, and a set of parentheses that can include parameters. The code inside the
function is indented, and the function is called by using its name followed by
parentheses (). For example:

P a g e 61 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

In this example, the function greet() takes in one parameter, name, and uses it to
print a greeting. The function is called with the argument "Yogesh" which is passed
as the parameter "name" and the function greet the user by saying Hello Yogesh .
Functions can also return a value using the return keyword. For example:

In this example, the function add() takes in two parameters, a and b, and returns the
sum of the two values. The function is called with the arguments 3 and 4, and the
returned value 7 is stored in the variable result and printed out.
Functions are a powerful tool for structuring your code, making it more readable,
and reducing the likelihood of errors. They also make it easier to test and debug your
code, as you can test each function separately.
❖ Logic with python function
Logic is a fundamental concept in computer programming and is used to control the
flow of a program. In Python, logic can be implemented in functions using
conditional statements such as if, elif, and else.
For example, consider a function that takes in a number and returns whether it is
positive, negative, or zero:

P a g e 62 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

In this example, the function check_sign() takes in one parameter, num, and uses a
series of if, elif, and else statements to check the value of num. Depending on the
value, the function returns a string indicating whether the number is positive,
negative or zero.
Another example of using logic in python function is using loops, like for and while
loops. For example:

In this example, the function print_even_numbers() takes in one parameter, n, and


uses a for loop to iterate through a range of numbers from 1 to n+1. Inside the loop,
an if statement checks if the current number is even using modulus operator. If the
current number is even, it will be printed.
Incorporating logic in functions allows you to control the flow of the program and
make decisions based on certain conditions. This makes your code more dynamic
and able to handle different inputs and scenarios.

P a g e 63 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ Keyword argument
In Python, function arguments can be passed in two ways: Positional arguments and
keyword arguments.
Positional arguments are passed to a function in the order they are defined in the
function signature. For example:

In this example, the function print_info() takes in two arguments: name and age.
The values "John" and 30 are passed as positional arguments, in that order.
Keyword arguments, on the other hand, are passed to a function by explicitly
specifying the argument name along with its value. For example:

In this example, the values "John" and 30 are passed as keyword arguments,
explicitly specifying the argument name "name" and "age" respectively.
When using keyword arguments, the order of the arguments does not matter, as long
as the argument names are correct. This can make your code more readable and less
prone to errors, as the function call clearly shows what value is being passed for each
argument.

P a g e 64 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

It's also possible to mix positional and keyword arguments in a function call.
Positional arguments should be passed first, followed by keyword arguments.
However, a keyword argument can't be passed before a positional argument.

In this example, the function print_info() takes in three arguments: name, age and
city. The first argument is passed as positional argument, and the other two as
keyword arguments.
Keyword arguments are particularly useful when a function has a lot of parameters,
or when the parameters have default values, which can be overridden by the caller.
❖ Args and kwargs
In Python, *args and **kwargs are used to pass a variable number of arguments to
a function.
*args is used to pass a non-keyworded, variable-length list of arguments to a
function. For example:

In this example, the function print_args() takes in a variable number of arguments,


represented by the *args parameter. The function uses a for loop to iterate through
the passed arguments and print each one.

P a g e 65 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

**kwargs is used to pass a keyworded, variable-length list of arguments to a


function. For example:

In this example, the function print_kwargs() takes in a variable number of keyword


arguments, represented by the **kwargs parameter. The function uses a for loop to
iterate through the passed keyword arguments and print the key and value of each
one.
It's also possible to use *args and **kwargs together in the same function definition.
The *args parameter should come before **kwargs in the function signature. For
example:

In this example, the function print_args_kwargs() takes in a variable number of


arguments and keyword arguments. The arguments are passed as *args and the
keyword arguments are passed as **kwargs. The function uses a for loop to iterate
through the passed arguments and keyword arguments and print each one.
Using *args and **kwargs allows a function to accept a variable number of
arguments, making it more flexible and adaptable to different situations. However,

P a g e 66 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

it's recommended to use them with care, as they can make the code harder to
understand and debug.
❖ Return Statement
In Python, the return statement is used in a function to specify a value or values to
be returned to the caller. The returned value can then be assigned to a variable or
used in an expression.
For example, consider a simple function that takes in two numbers and returns their
sum:

In this example, the function add() takes in two parameters, a and b, and uses the
return statement to return the sum of the two values. The returned value, 7, is then
assigned to the variable result and printed out.
A function can also return multiple values using tuple packing and unpacking. For
example:

In this example, the function divide() takes in two parameters, a and b, and uses the
return statement to return the result of division and remainder, the returned values

P a g e 67 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

are then unpacked and assigned to the variables result and remainder and printed
out.
It's also possible for a function to return None, which is the default return value if
the return statement is not used or if it is used without any value.

In this example, the function print_info() takes in two parameters, name and age,
and uses the print statement to display the name and age, but it does not return
anything, so the default return value is None.
The return statement is an important tool for structuring your code and making it
more modular, as it allows you to separate the logic of a function from the logic of
the caller. It also makes it possible to use the same function multiple times with
different input values and get different results.
❖ Lambda
In Python, a lambda function is a small, anonymous function that is defined using
the lambda keyword. Lambda functions are often used to create small, throwaway
functions for one-time use.
A lambda function is defined using the following syntax:
lambda arguments: expression
For example:

P a g e 68 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

In this example, the lambda function takes one argument x and returns the square of
x. The function is assigned to the variable square, and it can be used just like any
other function.
Lambda functions can also take multiple arguments and they can return any
expression.

In this example, the lambda function takes two arguments x and y and returns their
sum.
Lambda functions are often used in combination with other built-in Python
functions, such as map() and filter(), which allow you to operate on lists and other
iterable objects.
For example:

In this example, the map() function applies the lambda function to each element in
the numbers list, returning a new list of squared numbers.
Lambda functions are also useful when you need to pass a small function as an
argument to another function, like sorted()

P a g e 69 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

In this example, the sorted() function uses the lambda function to sort the words by
their length.
Lambda functions are a powerful and concise way to define small, throwaway
functions for one-time use, and they can help make your code more readable and
maintainable. However, it's important to keep in mind that they can make your code
harder to understand if overused or if the logic inside them is complex.
❖ Map and filter
In Python, map() and filter() are built-in functions that allow you to operate on lists
and other iterable objects.
map() applies a given function to each item of an iterable and returns a new iterable
with the modified items. For example:

In this example, the map() function applies the lambda function (which squares the
number) to each element in the numbers list, returning a new iterable containing the
squared numbers.
filter() applies a given function to each item of an iterable and returns a new iterable
containing only the items for which the function returned True. For example:

In this example, the map() function applies the lambda function (which squares the
number) to each element in the numbers list, returning a new iterable containing the
squared numbers.

P a g e 70 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

filter() applies a given function to each item of an iterable and returns a new iterable
containing only the items for which the function returned True. For example:

In this example, the filter() function applies the lambda function (which checks if
the number is even) to each element in the numbers list, returning a new iterable
containing only the even numbers.
Both map() and filter() return an iterable (map object or filter object) that can be
converted to a list using the list() function.
These functions are useful for performing operations on large collections of data, as
they allow you to manipulate the data in a concise and readable way, without the
need for explicit loops. They also help to separate the logic of the operation from the
logic of the iteration, making your code more modular and easier to understand.
It's also possible to use list comprehension to achieve the same results as map and
filter functions. For example:

List comprehension is a more concise and readable way of achieving the same results
as map and filter functions, but it can be harder to understand if the logic inside them
is complex.
❖ Import module
In Python, a module is a collection of related functions and variables that can be
imported and used in your code. A module is a Python file that contains definitions

P a g e 71 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

and statements. To use a module in your code, you must first import it using the
import statement.
For example, consider the built-in math module, which contains mathematical
functions such as sqrt() and sin(). To use these functions in your code, you would
import the math module and then call the functions using the dot notation:

You can also import specific functions or variables from a module using the from
keyword.

This way you do not need to use the dot notation to call the function.
You can also use the as keyword to give an imported module or function a different
name. This can be useful if the module or function has a long name or if you want
to use a shorter or more descriptive name.

P a g e 72 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

or

It's also possible to import all functions and variables from a module using the *
operator.

It's not recommended to use * operator as it can lead to name conflicts if two modules
have functions with the same name.
When you import a module, Python runs the code in the module file, so you should
be careful when importing modules that contain code that may have unintended side
effects, such as modifying global variables or printing output.
Also, you can use dir() function to see the list of functions and variables that are
available in a module after importing it.

This will give you a list of all the functions and variables defined in the math module.

P a g e 73 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ Datetime with python and exception handling


The datetime module in Python is a built-in module that provides classes for
manipulating dates and times. The most commonly used classes in the datetime
module are datetime, date, and time.
datetime class is used to work with both date and time.

This code snippet uses the now() function of the datetime class to get the current
date and time, and assigns it to the variable current_time.
date class is used to work with date.

This code snippet uses the today() function of the date class to get the current date,
and assigns it to the variable today.
time class is used to work with time.

This code snippet creates a time object representing the current time and assigns it
to the variable current_time.

P a g e 74 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

In addition to these classes, the datetime module also includes other useful functions
and classes for working with dates and times, such as timedelta for working with
time durations, tzinfo for working with time zones, and strftime() for formatting
date and time strings.
When working with the datetime module, it's important to be aware of exception
handling. Exception handling allows you to handle errors that may occur in your
code in a controlled and predictable way.
For example, when working with datetime, it's possible to encounter a ValueError
if the date or time passed to a function is not valid.

In this example, the code will raise a ValueError exception because the date passed
to the `strptime()
❖ Time class
The time class in the Python datetime module is used to work with time. The time
class takes three optional arguments: hour, minute, and second. These arguments are
used to create a time object representing a specific time. If no arguments are passed,
the time object will be set to the current time.

P a g e 75 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

The time class has several useful attributes, such as hour, minute, and second,
which allow you to get or set the individual components of a time object.

The time class also has a isoformat() method which returns a string representation
of the time in the ISO format.

In addition, the time class also has a strftime() method which allows you to format
the time as a string using the same format codes as the strftime() function in the
datetime module.

❖ Date time class


The datetime class in the Python datetime module is used to work with both date
and time. The datetime class takes several optional arguments: year, month, day,
hour, minute, and second. These arguments are used to create a datetime object

P a g e 76 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

representing a specific date and time. If no arguments are passed, the datetime object
will be set to the current date and time.

The datetime class has several useful attributes, such as year, month, day, hour,
minute, and second, which allow you to get or set the individual components of a
datetime object.

The datetime class also has a isoformat() method which returns a string
representation of the date and time in the ISO format.

In addition, the datetime class also has a strftime() method which allows you to
format the date and time as a string using the same format codes as the strftime()
function.

P a g e 77 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ Date from time stamp


A timestamp is a numerical representation of a specific point in time, usually in the
form of a Unix timestamp, which is the number of seconds that have elapsed since
January 1, 1970.
To convert a timestamp to a date in Python, you can use the
datetime.fromtimestamp() function from the datetime module. This function takes
a timestamp as an argument and returns a datetime object representing the date and
time that the timestamp represents.

You can also use the datetime.utcfromtimestamp() function to convert a


timestamp to a UTC datetime object.

It's important to note that the datetime.fromtimestamp() and


datetime.utcfromtimestamp() functions assume that the timestamp is in seconds.

P a g e 78 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

If your timestamp is in milliseconds, you need to divide it by 1000 before passing it


to the function.

Once you have the datetime object, you can use its attributes or methods to extract
the date and time information or to format it as a string.
❖ Time delta
The timedelta class in the Python datetime module is used to represent a duration
of time. A timedelta object can be created by passing values for days, seconds,
microseconds, milliseconds, minutes, hours, or weeks to the timedelta() constructor.

P a g e 79 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

Once you have a timedelta object, you can perform arithmetic operations on it, such
as addition, subtraction, and multiplication. For example, you can add a timedelta
object to a datetime object to find a new date and time.

You can also use the attributes of timedelta objects to extract the duration
information, such as days, seconds, microseconds

timedelta objects are useful for performing calculations with dates and times, such
as finding the difference between two dates, or finding the date and time a certain
duration from now.
❖ String format time
The strftime() function in Python allows you to format date and time objects as
strings. The function takes a format string as an argument, which contains codes that
are replaced with the corresponding date and time values.

P a g e 80 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

For example, the code "%Y-%m-%d %H:%M:%S" in the format string will be
replaced with the four-digit year, two-digit month, and two-digit day, and hour,
minute, and second of the date and time.
When working with datetime, date, time classes you can use the strftime() method
to format it as a string.

Here's a list of some of the most commonly used format codes for strftime():
• %Y: four-digit year
• %m: two-digit month
• %d: two-digit day
• %H: hour (24-hour clock)
• %I: hour (12-hour clock)
• %M: two-digit minute
• %S: two-digit second
• %A: full weekday name
• %B: full month name
• %p: AM or PM
You can also use the strftime() method of date and time classes in the same way.

P a g e 81 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

It is important to note that strftime() method raises a ValueError exception if the


format string contains an invalid format code.
❖ String past time
In Python, to represent the time that has passed since a certain date and time
represented by a string, you can convert the string to a datetime object using the
datetime.strptime() function, as I mentioned in my previous answer, and then
subtract that datetime object from the current time using the datetime.now() method.
For example:

P a g e 82 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

The time_passed variable here is a timedelta object, which represents the difference
between two datetime objects. You can extract the amount of time passed in specific
units like days, seconds, or microseconds using the attributes of timedelta objects
like days, seconds, microseconds.
You can also format the timedelta object in a human-readable format using the
strftime() method:

Keep in mind that the strftime() method for timedelta only supports a limited set of
format codes.

❖ Handling timezone in python


Python's datetime module does not include built-in support for working with time
zones. However, the pytz library provides time zone support for the datetime
module and can be used to handle timezones in Python.
To use pytz, you first need to install it by running pip install pytz in the command
line.
To work with time zones, you can create a datetime object with a time zone using
the pytz.timezone.localize() method. For example, to create a datetime object
representing the current time in the "US/Eastern" time zone:

P a g e 83 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

The last part of the output "-05:00" indicates the offset from UTC.
You can also convert a datetime object to a different time zone using the
pytz.timezone.normalize() method.

It's important to note that pytz uses the IANA time zone database, which means that
it is aware of historical time zone changes. This is important when working with
historical dates and times.
Additionally, you can use pytz.all_timezones to get a list of all timezones known to
pytz and pytz.country_timezones to get a list of timezones for a specific country.

Managing timezones can be tricky, and it's important to understand the nuances of
time zone calculations and the rules that govern daylight saving time. The pytz

P a g e 84 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

❖ Exception handling
Exception handling is a mechanism in Python that allows you to handle runtime
errors and unexpected conditions in your code. It enables you to write code that can
continue to execute even when an error occurs, instead of stopping abruptly and
causing the program to crash.
In Python, exceptions are raised using the raise statement, and handled using the try
and except statements.
The try block contains the code that may raise an exception. The except block
contains the code that will be executed if an exception is raised. If no exception is
raised, the code in the except block will be skipped.
For example, consider the following code that tries to open a file:

If the file "example.txt" does not exist, the open() function will raise a
FileNotFoundError exception, and the code in the except block will be executed,
printing "An error occurred while opening the file"
You can also specify the type of exception that you want to catch using the except
statement.

P a g e 85 | 86
YOGESH
1/21/23
COMPLETE PYTHON COURSE BY YOGESH

You can also use the finally block to run code that must be executed regardless of
whether an exception is raised or not.

P a g e 86 | 86

You might also like