Python
Python
What is Programming
Programming is a way for us to tell computers what to do. Computer is a
very dumb machine and it only does what we tell it to do. Hence we learn
programming and tell computers to do what we are very slow at -
computation. If I ask you to calculate 5+6, you will immediately say 11.
How about 23453453 X 56456?
You will start searching for a calculator or jump to a new tab to calculate
the same. This 100 days of code series will help you learn python from
starting to the end. We will start from 0 and by the time we end this
course, I promise you will be a Job ready Python developer!
What is Python?
Python is a dynamically typed, general purpose programming
language that supports an object-oriented programming approach as
well as a functional programming approach.
Python is an interpreted and a high-level programming language.
It was created by Guido Van Rossum in 1989.
Features of Python
Python is simple and easy to understand.
It is Interpreted and platform-independent which makes debugging very
easy.
Python is an open-source programming language.
Python provides very big library support. Some of the popular libraries
include NumPy, Tensorflow, Selenium, OpenCV, etc.
It is possible to integrate other programming languages within
python.
What is Python used for
Python is used in Data Visualization to create plots and graphical
representations.
Python helps in Data Analytics to analyze and understand raw data
for insights and trends.
It is used in AI and Machine Learning to simulate human behavior
and to learn from past data without hard coding.
It is used to create web applications.
It can be used to handle databases.
It is used in business and accounting to perform complex
mathematical operations along with quantitative and qualitative
analysis
What is a variable?
Variable is like a container that holds data. Very similar to how our
containers in kitchen holds sugar, salt etc Creating a variable is like
creating a placeholder in memory and assigning it some value. In
Python its as easy as writing:
a=1
b = True
c = "Harry"
d = None
What is a Data Type?
Data type specifies the four variables of different data types.
type of value a variable holds. This is required in programming to do
various operations without causing an error.
In python, we can print the type of any operator using type function:
a=1
print(type(a))
b = "1"
print(type(b))
By default, python provides the following built-in data types:
1. Numeric data: int, float, complex
int: 3, -8, 0
float: 7.349, -9.0, 0.0000001
complex: 6 + 2i
2. Text data: str
str: "Hello World!!!", "Python Programming"
3. Boolean data:
Boolean data consists of values True or False.
4. Sequenced data: list, tuple
list: A list is an ordered collection of data with elements separated
by a comma and enclosed within square brackets. Lists are mutable
and can be modified after creation.
Example:
list1 = [8, 2.3, [-4, 5], ["apple", "banana"]]
print(list1)
Output:
[8, 2.3, [-4, 5], ['apple', 'banana']]
Tuple: A tuple is an ordered collection of data with elements
separated by a comma and enclosed within parentheses. Tuples are
immutable and can not be modified after creation.
Example:
tuple1 = (("parrot", "sparrow"), ("Lion", "Tiger"))
print(tuple1)
Output:
(('parrot', 'sparrow'), ('Lion', 'Tiger'))
5. Mapped data: dict
dict: A dictionary is an unordered collection of data containing a
key:value pair. The key:value pairs are enclosed within curly
brackets.
Example:
dict1 = {"name":"Sakshi", "age":20, "canVote":True}
print(dict1)
Output:
{'name': 'Sakshi', 'age': 20, 'canVote': True}
Operators
+ Addition 15+7
- Subtraction 15-7
* Multiplication 5*7
** Exponential 5**3
/ Division 5/3
% Modulus 15%7
Exercise
n = 15
m = 7
ans1 = n+m
print("Addition of",n,"and",m,"is", ans1)
ans2 = n-m
print("Subtraction of",n,"and",m,"is", ans2)
ans3 = n*m
print("Multiplication of",n,"and",m,"is", ans3)
ans4 = n/m
print("Division of",n,"and",m,"is", ans4)
ans5 = n%m
print("Modulus of",n,"and",m,"is", ans5)
ans6 = n//m
print("Floor Division of",n,"and",m,"is", ans6)
Explaination
Here 'n' and 'm' are two variables in which the integer value is being
stored. Variables 'ans1' , 'ans2' ,'ans3', 'ans4','ans5' and 'ans6' contains
the outputs corresponding to addition, subtraction,multiplication, division,
modulus and floor division respectively.
Typecasting in python
The conversion of one data type into the other data type is known as
type casting in python or type conversion in python.
Python supports a wide variety of functions or methods like: int(),
float(), str(), ord(), hex(), oct(), tuple(), set(), list(), dict(), etc. for the
type casting in python.
Two Types of Typecasting:
1. Explicit Conversion (Explicit type casting in python)
2. Implicit Conversion (Implicit type casting in python).
Explicit typecasting:
The conversion of one data type into another data type, done via
developer or programmer's intervention or manually as per the
requirement, is known as explicit type conversion.
It can be achieved with the help of Python’s built-in type conversion
functions such as int(), float(), hex(), oct(), str(), etc .
Example of explicit typecasting:
string = "15"
number = 7
string_number = int(string) #throws an error if the string is not a valid
integer
sum= number + string_number
print("The Sum of both the numbers is: ", sum)
Output:
The Sum of both the numbers is 22
Implicit type casting:
Data types in Python do not have the same level i.e. ordering of data
types is not the same in Python. Some of the data types have higher-
order, and some have lower order. While performing any operations on
variables with different data types in Python, one of the variable's data
types will be changed to the higher data type. According to the level,
one data type is converted into other by the Python interpreter itself
(automatically). This is called, implicit typecasting in python.
Python converts a smaller data type to a higher data type to prevent
data loss.
Example of implicit type casting:
# Python automatically converts
# a to int
a=7
print(type(a))
# Quick Quiz:
# nm = "Harry"
# print(nm[-4:-2])
# @codewithharry
String methods
Python provides a set of built-in methods that we can use to alter and
modify the strings.
upper() :
The upper() method converts a string to upper case.
Example:
str1 = "AbcDEfghIJ"
print([Link]())
Output:
ABCDEFGHIJ
lower()
The lower() method converts a string to lower case.
Example:
str1 = "AbcDEfghIJ"
print([Link]())
Output:
abcdefghij
strip() :
The strip() method removes any white spaces before and after the string.
Example:
str2 = " Silver Spoon "
print([Link])
Output:
Silver Spoon
rstrip() :
the rstrip() removes any trailing characters. Example:
str3 = "Hello !!!"
print([Link]("!"))
Output:
Hello
replace() :
The replace() method replaces all occurences of a string with another
string. Example:
str2 = "Silver Spoon"
print([Link]("Sp", "M"))
Output:
Silver Moon
split() :
The split() method splits the given string at the specified instance and
returns the separated strings as list items.
Example:
str2 = "Silver Spoon"
print([Link](" ")) #Splits the string at the whitespace " ".
Output:
['Silver', 'Spoon']
There are various other string methods that we can use to modify our
strings.
capitalize() :
The capitalize() method turns only the first character of the string to
uppercase and the rest other characters of the string are turned to
lowercase. The string has no effect if the first character is already
uppercase.
Example:
str1 = "hello"
capStr1 = [Link]()
print(capStr1)
str2 = "hello WorlD"
capStr2 = [Link]()
print(capStr2)
Output:
Hello
Hello world
center() :
The center() method aligns the string to the center as per the parameters
given by the user.
Example:
str1 = "Welcome to the Console!!!"
print([Link](50))
Output:
Welcome to the Console!!!
We can also provide padding character. It will fill the rest of the fill
characters provided by the user.
Example:
str1 = "Welcome to the Console!!!"
print([Link](50, "."))
Output:
............Welcome to the Console!!!.............
count() :
The count() method returns the number of times the given value has
occurred within the given string.
Example:
str2 = "Abracadabra"
countStr = [Link]("a")
print(countStr)
Output:
4
endswith() :
The endswith() method checks if the string ends with a given value. If yes
then return True, else return False.
Example :
str1 = "Welcome to the Console !!!"
print([Link]("!!!"))
Output:
True
We can even also check for a value in-between the string by providing
start and end index positions.
Example:
str1 = "Welcome to the Console !!!"
print([Link]("to", 4, 10))
Output:
True
find() :
The find() method searches for the first occurrence of the given value and
returns the index where it is present. If given value is absent from the
string then return -1.
Example:
str1 = "He's name is Dan. He is an honest man."
print([Link]("is"))
Output:
10
As we can see, this method is somewhat similar to the index() method.
The major difference being that index() raises an exception if value is
absent whereas find() does not.
Example:
str1 = "He's name is Dan. He is an honest man."
print([Link]("Daniel"))
Output:
-1
index() :
The index() method searches for the first occurrence of the given value
and returns the index where it is present. If given value is absent from the
string then raise an exception.
Example:
str1 = "He's name is Dan. Dan is an honest man."
print([Link]("Dan"))
Output:
13
As we can see, this method is somewhat similar to the find() method. The
major difference being that index() raises an exception if value is absent
whereas find() does not.
Example:
str1 = "He's name is Dan. Dan is an honest man."
print([Link]("Daniel"))
Output:
ValueError: substring not found
isalnum() :
The isalnum() method returns True only if the entire string only consists of
A-Z, a-z, 0-9. If any other characters or punctuations are present, then it
returns False.
Example 1:
str1 = "WelcomeToTheConsole"
print([Link]())
Output:
True
isalpha() :
The isalnum() method returns True only if the entire string only consists of
A-Z, a-z. If any other characters or punctuations or numbers(0-9) are
present, then it returns False.
Example :
str1 = "Welcome"
print([Link]())
Output:
True
islower() :
The islower() method returns True if all the characters in the string are
lower case, else it returns False.
Example:
str1 = "hello world"
print([Link]())
Output:
True
isprintable() :
The isprintable() method returns True if all the values within the given
string are printable, if not, then return False.
Example :
str1 = "We wish you a Merry Christmas"
print([Link]())
Output:
True
isspace() :
The isspace() method returns True only and only if the string contains
white spaces, else returns False.
Example:
str1 = " " #using Spacebar
print([Link]())
str2 = " " #using Tab
print([Link]())
Output:
True
True
istitle() :
The istitile() returns True only if the first letter of each word of the string is
capitalized, else it returns False.
Example:
str1 = "World Health Organization"
print([Link]())
Output:
True
Example:
str2 = "To kill a Mocking bird"
print([Link]())
Output:
False
isupper() :
The isupper() method returns True if all the characters in the string are
upper case, else it returns False.
Example :
str1 = "WORLD HEALTH ORGANIZATION"
print([Link]())
Output:
True
startswith() :
The endswith() method checks if the string starts with a given value. If
yes then return True, else return False.
Example :
str1 = "Python is a Interpreted Language"
print([Link]("Python"))
Output:
True
swapcase() :
The swapcase() method changes the character casing of the string. Upper
case are converted to lower case and lower case to upper case.
Example:
str1 = "Python is a Interpreted Language"
print([Link]())
Output:
pYTHON IS A iNTERPRETED lANGUAGE
title() :
The title() method capitalizes each letter of the word within the string.
Example:
str1 = "He's name is Dan. Dan is an honest man."
print([Link]())
Output:
He'S Name Is Dan. Dan Is An Honest Man.
if-else Statements
Sometimes the programmer needs to check the evaluation of certain
expression(s), whether the expression(s) evaluate to True or False. If the
expression evaluates to False, then the program execution follows a
different path than it would have if the expression had evaluated to True.
Based on this, the conditional statements are further classified into
following types:
if
if-else
if-else-elif
nested if-else-elif.
Example:
applePrice = 210
budget = 200
if (applePrice <= budget):
print("Alexa, add 1 kg Apples to the cart.")
else:
print("Alexa, do not add Apples to the cart.")
Output:
Alexa, do not add Apples to the cart.
Example program
a = int(input("Enter your age: "))
print("Your age is:", a)
# Conditional operators
# >, <, >=, <=, ==, !=
# print(a>18)
# print(a<=18)
# print(a==18)
# print(a!=18)
if(a>18):
print("You can drive")
print("Yes")
else:
print("You cannot drive")
print("No")
print("Yay!")
elif Statements
Sometimes, the programmer may want to evaluate more than one
condition, this can be done using an elif statement.
Working of an elif statement
Execute the block of code inside if statement if the initial expression
evaluates to True. After execution return to the code out of the if block.
Execute the block of code inside the first elif statement if the expression
inside it evaluates True. After execution return to the code out of the if
block.
Execute the block of code inside the second elif statement if the
expression inside it evaluates True. After execution return to the code out
of the if block.
.
.
.
Execute the block of code inside the nth elif statement if the expression
inside it evaluates True. After execution return to the code out of the if
block.
Execute the block of code inside else statement if none of the expression
evaluates to True. After execution return to the code out of the if block.
Example:
num = 0
if (num < 0):
print("Number is negative.")
elif (num == 0):
print("Number is Zero.")
else:
print("Number is positive.")
Output:
Number is Zero.
Nested if statements
We can use if, if-else, elif statements inside other if statements as well.
Example:
num = 18
if (num < 0):
print("Number is negative.")
elif (num > 0):
if (num <= 10):
print("Number is between 1-10")
elif (num > 10 and num <= 20):
print("Number is between 11-20")
else:
print("Number is greater than 20")
else:
print("Number is zero")
Output:
Number is between 11-20
Introduction to Loops
Sometimes a programmer wants to execute a group of statements a
certain number of times. This can be done using loops. Based on this
loops are further classified into following main types;
for loop
while loop
range():
What if we do not want to iterate over a sequence? What if we want to
use for loop for a specific number of times?
Here, we can use the range() function.
Example:
for k in range(5):
print(k)
Output:
0
1
2
3
4
Here, we can see that the loop starts from 0 by default and increments at
each iteration.
But we can also loop over a specific range.
Example:
for k in range(4,9):
print(k)
Output:
4
5
6
7
8
Quick Quiz
Explore about third parameter of range (ie range(x, y, z))
Answer is: Third parameter is step count
The break statement enables a program to skip over a part of the code.
A break statement terminates the very loop it lies within.
example
for i in range(1,101,1):
print(i ,end=" ")
if(i==50):
break
else:
print("Mississippi")
print("Thank you")
output
1 Mississippi
2 Mississippi
3 Mississippi
4 Mississippi
5 Mississippi
.
.
.
50 Mississippi
Continue Statement
The continue statement skips the rest of the loop statements and causes
the next iteration to occur.
example
for i in [2,3,4,6,8,0]:
if (i%2!=0):
continue
print(i)
output
2
4
6
8
0
Python Functions
A function is a block of code that performs a specific task whenever it is
called. In bigger programs, where we have large amounts of code, it is
advisable to create or use existing functions that make the program flow
organized and neat.
1. Built-in functions
2. User-defined functions
Built-in functions:
min(), max(), len(), sum(), type(), range(), dict(), list(), tuple(), set(),
print(), etc.
User-defined functions:
We can create functions to perform specific tasks as per our needs. Such
functions are called user-defined functions.
Syntax:
def function_name(parameters):
pass
# Code and Statements
Create a function using the def keyword, followed by a function
name, followed by a paranthesis (()) and a colon(:).
Any parameters and arguments should be placed within the
parentheses.
Rules to naming function are similar to that of naming variables.
Any statements and other code within the function should be
indented.
Calling a function:
Example:
def name(fname, lname):
print("Hello,", fname, lname)
name("Sam", "Wilson")
Output:
Hello, Sam Wilson
Program example:
def calculateGmean(a, b):
mean = (a*b)/(a+b)
print(mean)
a = 9
b = 8
isGreater(a, b)
calculateGmean(a, b)
# gmean1 = (a*b)/(a+b)
# print(gmean1)
c = 8
d = 74
isGreater(c, d)
calculateGmean(c, d)
# gmean2 = (c*d)/(c+d)
# print(gmean2)
Default Arguments
Keyword Arguments
Variable length Arguments
Required Arguments
Default arguments:
We can provide a default value while creating a function. This way the
function assumes a default value even if a value is not provided in the
function call for that argument.
Example:
def name(fname, mname = "Jhon", lname = "Whatson"):
print("Hello,", fname, mname, lname)
name("Amy")
Output:
Hello, Amy Jhon Whatson
Keyword arguments:
We can provide arguments with key = value, this way the interpreter
recognizes the arguments by the parameter name. Hence, the the order
in which the arguments are passed does not matter.
Example:
def name(fname, mname, lname):
print("Hello,", fname, mname, lname)
name(mname = "Peter", lname = "Wesker", fname = "Jade")
Output:
Hello, Jade Peter Wesker
Required arguments:
In case we don’t pass the arguments with a key = value syntax, then it is
necessary to pass the arguments in the correct positional order and the
number of arguments passed should match with actual function
definition.
Variable-length arguments:
Arbitrary Arguments:
Example:
def name(*name):
print("Hello,", name[0], name[1], name[2])
name("James", "Buchanan", "Barnes")
Output:
Hello, James Buchanan Barnes
Example:
def name(**name):
print("Hello,", name["fname"], name["mname"],
name["lname"])
name(mname = "Buchanan", lname = "Barnes", fname = "James")
Output:
Hello, James Buchanan Barnes
return Statement
The return statement is used to return the value of the expression back to
the calling function.
Example:
def name(fname, mname, lname):
return "Hello, " + fname + " " + mname + " " + lname
print(name("James", "Buchanan", "Barnes"))
Output:
Hello, James Buchanan Barnes
Python Collections (Arrays)
There are four collection data types in the Python programming language:
Video example
def average(*numbers):
# print(type(numbers))
sum = 0
for i in numbers:
sum = sum + i
# print("Average is: ", sum / len(numbers))
# return 7
return sum / len(numbers)
# average(4, 6)
# average(b=9)
c = average(5, 6, 7, 1)
print(c)
Python Lists
Each item/element in a list has its own unique index. This index can be
used to access any particular item from the list. The first item has index
[0], second item has index [1], third item has index [2] and so on.
Example:
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
# [0] [1] [2] [3] [4]
We can access list items by using its index with the square bracket syntax
[]. For example colors[0] will give "Red", colors[1] will give "Green" and so
on...
Positive Indexing:
As we have seen that list items have index, as such we can access items
using these indexes.
Example:
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
# [0] [1] [2] [3] [4]
print(colors[2])
print(colors[4])
print(colors[0])
Output:
Blue
Green
Red
Negative Indexing:
Example:
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
# [-5] [-4] [-3] [-2] [-1]
print(colors[-1])
print(colors[-3])
print(colors[-5])
Output:
Green
Blue
Red
We can check if a given item is present in the list. This is done using
the in keyword.
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
if "Yellow" in colors:
print("Yellow is present.")
else:
print("Yellow is absent.")
Output:
Yellow is present.
colors = ["Red", "Green", "Blue", "Yellow", "Green"]
if "Orange" in colors:
print("Orange is present.")
else:
print("Orange is absent.")
Output:
Orange is absent.
Range of Index:
You can print a range of list items by specifying where you want to start,
where do you want to end and if you want to skip elements in between
the range.
Syntax:
listName[start : end : jumpIndex]
Note: jump Index is optional. We will see this in later examples.
Output:
['mouse', 'pig', 'horse', 'donkey']
['bat', 'mouse', 'pig', 'horse', 'donkey']
Here, we provide index of the element from where we want to start and
the index of the element till which we want to print the values.
Note: The element of the end index provided will not be included.
Example: printing all element from a given index till the end
animals = ["cat", "dog", "bat", "mouse", "pig", "horse",
"donkey", "goat", "cow"]
print(animals[4:]) #using positive indexes
print(animals[-4:]) #using negative indexes
Output:
['pig', 'horse', 'donkey', 'goat', 'cow']
['horse', 'donkey', 'goat', 'cow']
When no end index is provided, the interpreter prints all the values till the
end.
Output:
['cat', 'dog', 'bat', 'mouse', 'pig', 'horse']
['cat', 'dog', 'bat', 'mouse', 'pig', 'horse']
When no start index is provided, the interpreter prints all the values from
start up to the end index provided.
Example: Printing alternate values
animals = ["cat", "dog", "bat", "mouse", "pig", "horse",
"donkey", "goat", "cow"]
print(animals[::2]) #using positive indexes
print(animals[-8:-1:2]) #using negative indexes
Output:
['cat', 'bat', 'pig', 'donkey', 'cow']
['dog', 'mouse', 'horse', 'goat']
Here, we have not provided start and index, which means all the values
will be considered. But as we have provided a jump index of 2 only
alternate values will be printed.
Output:
['dog', 'pig', 'goat
Here, jump index is 3. Hence it prints every 3rd element within given
index.
List Comprehension
List comprehensions are used for creating new lists from other iterables
like lists, tuples, dictionaries, sets, and even in arrays and strings.
Syntax:
Example 1: Accepts items with the small letter “o” in the new list
names = ["Milo", "Sarah", "Bruno", "Anastasia", "Rosa"]
namesWith_O = [item for item in names if "o" in item]
print(namesWith_O)
Output:
['Milo', 'Bruno', 'Rosa']
Output:
['Sarah', 'Bruno', 'Anastasia']
Video example
marks = [3, 5, 6, "Harry", True, 6, 7 , 2, 32, 345, 23]
# print(marks)
# print(type(marks))
# print(marks[0])
# print(marks[1])
# print(marks[2])
# print(marks[3])
# print(marks[4])
# print(marks[5])
# if "6" in marks:
# print("Yes")
# else:
# print("No")
# print(marks[0:7])
# print(marks[1:9])
# print(marks[1:9:3])
LIST COMPREHENSION………………………………………………
lst = [i*i for i in range(10)]
print(lst)
lst = [i*i for i in range(10) if i%2==0]
print(lst)
List Methods
[Link]()
This method sorts the list in ascending order. The original list is updated
Example 1:
Output:
Example:
Output:
Note: Do not mistake the reverse parameter with the reverse method.
reverse()
Example:
Output:
index()
This method returns the index of the first occurrence of the list item.
Example:
count()
Returns the count of the number of items with the given value.
Example:
Output:
2
3
copy()
Returns copy of the list. This can be done to perform operations on the
list without modifying the original list.
Example:
Output:
append():
Example:
Output:
insert():
This method inserts an item at the given index. User has to specify index
and the item to be inserted within the insert() method.
Example:
Output:
This method adds an entire list or any other collection datatype (set,
tuple, dictionary) to the existing list.
Example 1:
Output:
Example:
Output:
Python Tuples
Tuples are ordered collection of data items. They store multiple items in a
single variable. Tuple items are separated by commas and enclosed
within round brackets (). Tuples are unchangeable meaning we can not
alter them after creation.
Example 1:
tuple1 = (1,2,2,3,5,4,6)
tuple2 = ("Red", "Green", "Blue")
print(tuple1)
print(tuple2)
Output:
(1, 2, 2, 3, 5, 4, 6)
('Red', 'Green', 'Blue')
Example 2:
Output:
Tuple Indexes
Each item/element in a tuple has its own unique index. This index can be
used to access any particular item from the tuple. The first item has index
[0], second item has index [1], third item has index [2] and so on.
Example:
I. Positive Indexing:
As we have seen that tuple items have index, as such we can access
items using these indexes.
Example:
country = ("Spain", "Italy", "India",)
# [0] [1] [2]
print(country[0])
print(country[1])
print(country[2])
Output:
Spain
Italy
India
Example:
Output:
Germany
India
Italy
We can check if a given item is present in the tuple. This is done using
the in keyword.
Example 1:
Output:
Germany is present.
Example 2:
Output:
Russia is absent.
You can print a range of tuple items by specifying where do you want to
start, where do you want to end and if you want to skip elements in
between the range.
Syntax:
Output:
Example: Printing all element from a given index till the end
Output:
Output:
Output:
Output:
if 3421 in tup:
print("Yes 342 is present in this tuple")
tup2 = tup[1:4]
print(tup2)
Manipulating Tuples
Tuples are immutable, hence if you want to add, remove or change tuple
items, then first you must convert the tuple to a list. Then perform
operation on that list and convert it back to tuple.
Example:
countries = ("Spain", "Italy", "India", "England", "Germany")
temp = list(countries)
[Link]("Russia") #add item
[Link](3) #remove item
temp[2] = "Finland" #change item
countries = tuple(temp)
print(countries)
Output:
('Spain', 'Italy', 'Finland', 'Germany', 'Russia')
Thus, we convert the tuple to a list, manipulate items of the list using list
methods, then convert list back to a tuple.
Example:
countries = ("Pakistan", "Afghanistan", "Bangladesh",
"ShriLanka")
countries2 = ("Vietnam", "India", "China")
southEastAsia = countries + countries2
print(southEastAsia)
Output:
('Pakistan', 'Afghanistan', 'Bangladesh', 'ShriLanka',
'Vietnam', 'India', 'China')
Tuple methods
count() Method
The count() method of Tuple returns the number of times the given
element appears in the tuple.
Syntax:
[Link](element)
Example
Tuple1 = (0, 1, 2, 3, 2, 3, 1, 3, 2)
res = [Link](3)
print('Count of 3 in Tuple1 is:', res)
Output
3
index() method
The Index() method returns the first occurrence of the given element
from the tuple.
Syntax:
Example
Tuple = (0, 1, 2, 3, 2, 3, 1, 3, 2)
res = [Link](3)
print('First occurrence of 3 is', res)
Output
f-strings in python
When we prefix the string with the letter 'f', the string becomes the f-
string itself. The f-string can be formatted in much same as the
[Link]() method. The f-string offers a convenient way to embed
Python expression inside string literals for formatting.
Example
val = 'Geeks'
print(f"{val}for{val} is a portal for {val}.")
name = 'Tushar'
age = 23
print(f"Hello, My name is {name} and I'm {age} years old.")
Output:
Example
print(f"{2 * 30})"
Output:
60
print([Link](country, name))
print(f"Hey my name is {name} and I am from {country}")
print(f"We use f-strings like this: Hey my name is {{name}}
and I am from {{country}}")
price = 49.09999
txt = f"For only {price:.2f} dollars!"
print(txt)
# print([Link]())
print(type(f"{2 * 30}"))
output
Hey my name is Harry and I am from India
Hey my name is Harry and I am from India
We use f-strings like this: Hey my name is {name} and I am from
{country}
For only 49.10 dollars!
<class 'str'>
Docstrings in python
Python docstrings are the string literals that appear right after the
definition of a function, method, class, or module.
Example
def square(n):
'''Takes in a number n, returns the square of n'''
print(n**2)
square(5)
Here,
Output:
25
Here is another example:
def add(num1, num2):
"""
Add up two integer numbers.
This function simply wraps the ``+`` operator, and does
not
do anything interesting, except for illustrating what
the docstring of a very simple function looks like.
Parameters
----------
num1 : int
First number to add.
num2 : int
Second number to add.
Returns
-------
int
The sum of ``num1`` and ``num2``.
See Also
--------
subtract : Subtract one integer from another.
Examples
--------
>>> add(2, 2)
4
>>> add(25, 0)
25
>>> add(10, -10)
0
"""
return num1 + num2
Python Comments
Comments are descriptions that help programmers better understand the
intent and functionality of the program. They are completely ignored by
the Python interpreter.
Python docstrings
As mentioned above, Python docstrings are strings used right after the
definition of a function, method, class, or module (like in Example 1).
They are used to document our code.
Example
def square(n):
'''Takes in a number n, returns the square of n'''
return n**2
print(square.__doc__)
Output:
PEP 8
PEP stands for Python Enhancement Proposal, and there are several of
them. A PEP is a document that describes new features proposed for
Python and documents aspects of Python, like design and style, for the
community.
Long time Pythoneer Tim Peters succinctly channels the BDFL’s guiding
principles for Python’s design into 20 aphorisms, only 19 of which have
been written down.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to
do it.
Although that way may not be obvious at first unless you're
Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good
idea.
Namespaces are one honking great idea -- let's do more of
those!
Easter egg
import this
Recursion in python
def factorial(num):
if (num == 1 or num == 0):
return 1
else:
return (num * factorial(num - 1))
# Driver Code
num = 7;
print("Number: ",num)
print("Factorial: ",factorial(num))
Output:
number: 7
Factorial: 5040
EXAMPLE PROGRAM
# factorial(7) = 7*6*5*4*3*2*1
# factorial(6) = 6*5*4*3*2*1
# factorial(5) = 5*4*3*2*1
# factorial(4) = 4*3*2*1
# factorial(0) = 1
# factorial(n) = n * factorial(n-1)
def factorial(n):
if (n == 0 or n == 1):
return 1
else:
return n * factorial(n - 1)
print(factorial(5))
# 5 * factorial(4)
# 5 * 4 * factorial(3)
# 5 * 4 * 3 * factorial(2)
# 5 * 4 * 3 * 2 * factorial(1)
# 5 * 4 * 3 * 2 * 1
Python Sets
Sets are unordered collection of data items. They store multiple items in a
single variable. Set items are separated by commas and enclosed within
curly brackets {}. Sets are unchangeable, meaning you cannot change
items of the set once created. Sets do not contain duplicate items.
Example:
info = {"Carla", 19, False, 5.9, 19}
print(info)
Output:
{False, 19, 5.9, 'Carla'}
Here we see that the items of set occur in random order and hence they
cannot be accessed using index numbers. Also sets do not allow duplicate
values.
Quick Quiz: Try to create an empty set. Check using the type() function
whether the type of your variable is a set
Example:
info = {"Carla", 19, False, 5.9}
for item in info:
print(item)
Output:
False
Carla
19
5.9
Example video program
s = {2, 4, 2, 6}
print(s)
harry = set()
print(type(harry))
The union() and update() methods prints all items that are present in the
two sets. The union() method returns a new set whereas update() method
adds item into the existing set from another set.
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities3 = [Link](cities2)
print(cities3)
Output:
{'Tokyo', 'Madrid', 'Kabul', 'Seoul', 'Berlin', 'Delhi'}
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
[Link](cities2)
print(cities)
Output:
{'Berlin', 'Madrid', 'Tokyo', 'Delhi', 'Kabul', 'Seoul'}
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities3 = [Link](cities2)
print(cities3)
Output:
{'Madrid', 'Tokyo'}
Example :
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities.intersection_update(cities2)
print(cities)
Output:
{'Tokyo', 'Madrid'}
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities3 = cities.symmetric_difference(cities2)
print(cities3)
Output:
{'Seoul', 'Kabul', 'Berlin', 'Delhi'}
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Tokyo", "Seoul", "Kabul", "Madrid"}
cities.symmetric_difference_update(cities2)
print(cities)
Output:
{'Kabul', 'Delhi', 'Berlin', 'Seoul'}
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Seoul", "Kabul", "Delhi"}
cities3 = [Link](cities2)
print(cities3)
Output:
{'Tokyo', 'Madrid', 'Berlin'}
Example:
cities = {"Tokyo", "Madrid", "Berlin", "Delhi"}
cities2 = {"Seoul", "Kabul", "Delhi"}
print([Link](cities2))
Output:
{'Tokyo', 'Berlin', 'Madrid'}
Set Methods
There are several in-built methods used for the manipulation of [Link]
are explained below
isdisjoint():
The isdisjoint() method checks if items of given set are present in another
set. This method returns False if items are present, else it returns True.
Example:
Output:
False
issuperset():
The issuperset() method checks if all the items of a particular set are
present in the original set. It returns True if all the items are present, else
it returns False.
Example:
Output:
False
False
issubset():
The issubset() method checks if all the items of the original set are
present in the particular set. It returns True if all the items are present,
else it returns False.
Example:
Output:
True
add()
If you want to add a single item to the set use the add() method.
Example:
Output:
update()
If you want to add more than one item, simply create another set or any
other iterable object(list, tuple, dictionary), and use the update() method
to add it into the existing set.
Example:
Output:
remove()/discard()
We can use remove() and discard() methods to remove items form list.
Example :
Output:
Example:
Output:
KeyError: 'Seoul'
pop()
This method removes the last item of the set but the catch is that we
don’t know which item gets popped as sets are unordered. However, you
can access the popped item if you assign the pop() method to a variable.
Example:
Output:
del
del is not a method, rather it is a keyword which deletes the set entirely.
Example:
Output:
What if we don’t want to delete the entire set, we just want to delete all
items within that set?
clear():
This method clears all items in the set and prints an empty set.
Example:
Output:
set()
Example
Output:
Carla is present.
Python Dictionaries
Example:
Output:
Example:
Output:
Karan
True
We can print all the values in the dictionary using values() method.
Example:
Output:
We can print all the keys in the dictionary using keys() method.
Example:
Output:
We can print all the key-value pairs in the dictionary using items()
method.
Example:
Output:
Dictionary Methods
update()
The update() method updates the value of the key provided to it if the
item already exists in the dictionary, else it creates a new key-value pair.
Example:
Output:
There are a few methods that we can use to remove items from
dictionary.
clear():
The clear() method removes all the items from the list.
Example:
Output:
{}
pop():
The pop() method removes the key-value pair whose key is passed as a
parameter.
Example:
Output:
popitem():
The popitem() method removes the last key-value pair from the
dictionary.
Example:
Output:
del:
Example:
Output:
Example:
Output:
As you have learned before, the else clause is used along with the if
statement.
Python allows the else keyword to be used with the for and while loops
too. The else block appears after the body of the loop. The statements in
the else block will be executed after all iterations are completed. The
program exits the loop only after the else block is executed.
Syntax
Example:
for x in range(5):
print ("iteration no {} in for loop".format(x+1))
else:
print ("else block in loop")
print ("Out of loop")
Output:
else:
print("Sorry no i")
for x in range(5):
print ("iteration no {} in for loop".format(x+1))
else:
print ("else block in loop")
print ("Out of loop")
Exception Handling
Exception handling is the process of responding to unwanted or
unexpected events when a computer program runs. Exception handling
deals with these events to avoid the program or system crashing, and
without this process, exceptions would disrupt the normal operation of a
program.
Exceptions in Python
Python has many built-in exceptions that are raised when your program
encounters an error (something in the program goes wrong).
When these exceptions occur, the Python interpreter stops the current
process and passes it to the calling process until it is handled. If not
handled, the program will crash.
Python try...except
try….. except blocks are used in python to handle errors and exceptions.
The code in try block runs when there is no error. If the try block catches
the error, then the except block is executed.
Syntax:
try:
#statements which could generate
#exception
except:
#Soloution of generated exception
Example:
try:
num = int(input("Enter an integer: "))
except ValueError:
print("Number entered is not an integer.")
Output:
try:
num = int(input("Enter an integer: "))
a = [6, 3]
print(a[num])
except ValueError:
print("Number entered is not an integer.")
except IndexError:
print("Index Error")
Finally Clause
The finally code block is also a part of exception handling. When we
handle exception using the try and except block, we can include a finally
block at the end. The finally block is always executed, so it is generally
used for doing the concluding tasks like closing file resources or closing
database connection or may be ending the program execution with a
delightful message.
Syntax:
try:
#statements which could generate
#exception
except:
#solution of generated exception
finally:
#block of code which is going to
#execute in any situation
The finally block is executed irrespective of the outcome of try……
except…..else blocks
One of the important use cases of finally block is in a function which
returns a value.
Example:
try:
num = int(input("Enter an integer: "))
except ValueError:
print("Number entered is not an integer.")
else:
print("Integer Accepted.")
finally:
print("This block is always executed.")
Output 1:
Enter an integer: 19
Integer Accepted.
This block is always executed.
Output 2:
finally:
print("I am always executed")
# print("I am always executed")
x = func1()
print(x)
Raising Custom errors
In python, we can raise custom errors by using the raise keyword.
salary = int(input("Enter salary amount: "))
if not 2000 < salary < 5000:
raise ValueError("Not a valid salary")
In the previous tutorial, we learned about different built-in exceptions in
Python and why it is important to handle exceptions. However,
sometimes we may need to create our own custom exceptions that serve
our purpose.
There is also a shorthand syntax for the if-else statement that can be
used when the condition being tested is simple and the code blocks to be
executed are short. Here's an example:
a = 2
b = 330
print("A") if a > b else print("B")
You can also have multiple else statements on the same line:
Example
Another Example
Conclusion
c = 9 if a>b else 0
print(c)
Enumerate function in python
The enumerate function is a built-in function in Python that allows you to
loop over a sequence (such as a list, tuple, or string) and get the index
and value of each element in the sequence at the same time. Here's a
basic example of how it works:
# Loop over a list and print the index and value of each
element
fruits = ['apple', 'banana', 'mango']
for index, fruit in enumerate(fruits):
print(index, fruit)
The output of this code will be:
0 apple
1 banana
2 mango
As you can see, the enumerate function returns a tuple containing the
index and value of each element in the sequence. You can use the for
loop to unpack these tuples and assign them to variables, as shown in the
example above.
By default, the enumerate function starts the index at 0, but you can
specify a different starting index by passing it as an argument to the
enumerate function:
# Loop over a list and print the index (starting at 1) and
value of each element
fruits = ['apple', 'banana', 'mango']
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)
This will output:
1 apple
2 banana
3 mango
The enumerate function is often used when you need to loop over a
sequence and perform some action with both the index and value of each
element. For example, you might use it to loop over a list of strings and
print the index and value of each string in a formatted way:
fruits = ['apple', 'banana', 'mango']
for index, fruit in enumerate(fruits):
print(f'{index+1}: {fruit}')
This will output:
1: apple
2: banana
3: mango
In addition to lists, you can use the enumerate function with any other
sequence type in Python, such as tuples and strings. Here's an example
with a tuple:
# Loop over a tuple and print the index and value of each
element
colors = ('red', 'green', 'blue')
for index, color in enumerate(colors):
print(index, color)
And here's an example with a string:
# Loop over a string and print the index and value of each
character
s = 'hello'
for index, c in enumerate(s):
print(index, c)
EXAMPLE PROGRAM DESCRIBED IN VIDEO
#---------42 lecture-------
marks = [12, 56, 32, 98, 12, 45, 1, 4]
# index = 0
# for mark in marks:
# print(mark)
# if(index == 3):
# print("Harry, awesome!")
# index +=1
Example:
Here, myenv is the name of your environment folder (you can choose any name).
After activation, you’ll see (myenv) appear before your command prompt — meaning you’re
inside the virtual environment.
Step 5: Deactivate
or on Windows:
rmdir /s /q myenv
To import a module in Python, you use the import statement followed by the name of
the module. For example, to import the math module, which contains a variety of
mathematical functions, you would use the following statement:
import math
Once a module is imported, you can use any of the functions and variables defined in
the module by using the dot notation. For example, to use the sqrt function from the
math module, you would write:
import math
result = [Link](9)
print(result) # Output: 3.0
from keyword
You can also import specific functions or variables from a module using the from
keyword. For example, to import only the sqrt function from the math module, you
would write:
importing everything
It's also possible to import all functions and variables from a module using the *
wildcard. However, this is generally not recommended as it can lead to confusion and
make it harder to understand where specific functions and variables are coming from.
import math
print(dir(math))
This will output a list of all the names defined in the math module, including functions
like sqrt and pi, as well as other variables and constants.
In summary, the import statement in Python allows you to access the functions and
variables defined in a module from within your current script. You can import the
entire module, specific functions or variables, or use the * wildcard to import
everything. You can also use the as keyword to rename a module, and the dir function
to view the contents of a module.
print(dir(math))
print([Link], type([Link]))
[Link]()
print([Link])
if __name__ == "__main__":
# code to run only when the file is executed directly
⚙️How It Works
Every Python file has a special built-in variable called __name__.
Then:
__name__ == "__main__"
Then:
__name__ == "myfile"
🔍 Example
📄 [Link]
def greet():
print("Hello from mymodule!")
if __name__ == "__main__":
print("This runs only when executed directly.")
📄 [Link]
import mymodule
Output:
Output:
✅ Notice that the second print statement didn’t run — because mymodule was imported, not executed
directly.
💡 Why We Use It
✅ To separate code that should run when the file is executed
from code that should only define functions/classes for import.
if __name__ == "__main__":
print(add(5, 3))
print(sub(5, 3))
📄 [Link]
import calculator
print([Link](10, 20))
✅ When you run [Link], it only prints 30, not the demo code in [Link].
import os
➡️Returns the current working directory (the folder where your Python script is running).
📁 Change Directory
[Link]("C:\\Users\\Ishrath\\Documents")
print([Link]())
Or specify a path:
print([Link]("C:\\"))
Remove Folder
[Link]("new_folder")
📄 Join Paths
path = [Link]("C:\\Users", "Ishrath", "Desktop")
print(path)
📁 Split Path
print([Link]("C:\\Users\\Ishrath\\Desktop\\[Link]"))
# → ('C:\\Users\\Ishrath\\Desktop', '[Link]')
🧱 4. Environment Variables
🌍 Get Environment Variables
print([Link])
📦 Access Specific Variable
print([Link]('PATH'))
[Link]("dir") # Windows
[Link]("ls") # Linux/Mac
🧠 6. Useful Utilities
Rename File
[Link]("[Link]", "[Link]")
Remove File
[Link]("[Link]")
⚡ Summary Table
Function Description
[Link]() Get current directory
[Link](path) Change directory
[Link](path) List files/folders
[Link](name) Create folder
[Link](path) Create nested folders
[Link](file) Delete file
[Link](folder) Delete empty folder
[Link](path) Check if file/folder exists
[Link](a, b) Join two paths safely
[Link] Access environment variables
[Link](cmd) Run system command
🔍 Example Program
import os
# 4. Rename folder
[Link]("test_folder", "renamed_folder")
# 5. Remove folder
[Link]("renamed_folder")
EXAMPLES
import os
import os
if(not [Link]("data")):
[Link]("data")
🌍 Global Variables
Declared outside any function.
Can be accessed anywhere in the program (inside or outside functions).
Example:
x = 10 # global variable
def show():
print("Inside function:", x)
show()
print("Outside function:", x)
Output:
Inside function: 10
Outside function: 10
🏠 Local Variables
Declared inside a function.
Can only be accessed inside that function — not outside.
Example:
def func():
y = 5 # local variable
print("Inside function:", y)
func()
print("Outside function:", y) # ❌ Error: y is not defined
Output:
Inside function: 5
NameError: name 'y' is not defined
Example:
x = 100
def func():
x = 50
print("Inside function:", x)
func()
print("Outside function:", x)
Output:
Inside function: 50
Outside function: 100
Example:
x = 10
def func():
global x
x = 20 # modifies global x
print("Inside function:", x)
func()
print("Outside function:", x)
Output:
Inside function: 20
Outside function: 20
✅ Because of global x, the change inside the function affected the global variable.
def outer():
x = 10 # local to outer
def inner():
nonlocal x # refers to x in outer function, not global
x = 15
print("Inner:", x)
inner()
print("Outer:", x)
outer()
print("Global:", x)
Output:
Inner: 15
Outer: 15
Global: 5
Here, nonlocal lets you modify the variable from an enclosing function, not the global one.
📋 Summary Table
Type Declared In Accessible In Can Modify Global?
Global Outside any function Everywhere ✅ With global
Local Inside a function Inside that function only ❌ No
Nonlocal Inside nested functions In enclosing (outer) function ✅ With nonlocal
def test():
a = 2 # local
print("Inside:", a)
test()
print("Outside:", a)
Output:
Inside: 2
Outside: 1
my_function()
print(x) # prints 5
# print(y) # this will cause an error because y is a local variable and is not
accessible outside of the function