Introduction to Python Programming Basics
Introduction to Python Programming Basics
Introduction to Python
History: Python is an object-oriented, interpreted, high-level programming language. It is general purpose, and
we use it to develop GUI (A graphical user interface (GUI) is a digital interface in which a user interacts with
graphical components such as icons, buttons, and menus.) and web applications. With Python, we can
concentrate on the business logic of our code rather than investing a lot of time in common programming tasks.
Python was created by Guido van Rossum, and first released on February 20, 1991. While we may know the
python as a large snake, the name of the Python programming language comes from an old BBC television
comedy sketch series called Monty Python's Flying Circus.
2. It has libraries for almost everything. Django for web development and Matplotlib for data visualization.
3. Machine Learning, Data Science and Deep Learning Models using Sklearn, TensorFlow, Theano, and Spark.
Features:
1. Free and Open Source
Python language is freely available at the official website. Since it is open-source; this means that source code
is also available to the public. So you can download it, use it as well as share it.
2. Easy to code
Python is a high-level programming language. Python is very easy to learn the language as compared to other
languages like C, C#, Javascript, Java, etc. It is very easy to code in the Python language and anybody can
learn Python basics in a few hours or days. It is also a developer-friendly language.
3. Easy to Read
As you will see, learning Python is quite simple. As was already established, Python’s syntax is really
straightforward. The code block is defined by the indentations rather than by semicolons or brackets.
4. Object-Oriented Language
One of the key features of Python is Object-Oriented programming. Python supports object-oriented language
and concepts of classes, object encapsulation, etc.
6. High-Level Language
Python is a high-level language. When we write programs in Python, we do not need to remember the system
architecture, nor do we need to manage the memory.
8. Easy to Debug
Excellent information for mistake tracing. You will be able to quickly identify and correct the majority of
your program’s issues once you understand how to interpret Python’s error traces. Simply by glancing at the
code, you can determine what it is designed to perform.
This will take you to the page where the different Python releases for Windows can be found. Since we are
using a 64bit system, We will select “Windows x86-64 executable installer”.
Once the executable file download is complete, you can open it to install Python.
If you want to save the installation file in a different location, click on Customize installation; otherwise,
continue with Install Now. Also, select the checkbox at the bottom to Add Python 3.7 to PATH.
Once the installation is complete, the below pop-up box will appear: Setup was successful.
Now that the installation is complete, you need to verify that everything is working fine.
As you can see, we have successfully printed “Hello World” in Python Shell. Using the Python Shell, you can
write one line of code and execute it by pressing Enter.
Python also has a command-line interpreter that works similarly to Python IDLE. Let’s print “Hello world” in
the command-line.
Python’s command-line interpreter and IDLE are suitable for any beginner to start with. However, to work in a
developer environment and build large scale projects, you should use other popular IDEs and code editors, such
as PyCharm, Atom, and Sublime Text. You can also try out the Anaconda Distribution of Python, which has
Jupyter Notebook and Spyder.
Most popular IDLE (Integrated Development and Learning Environment) for python:
Python Variables: A variable is a memory location where we can store values. In Python, the data type will be
identified according to the data we provide.
A variable should start with a letter or an underscore and can’t start with numbers. There are two ways of
assigning values to a variable:
1. print("Hello, World!")
Hello, World!
2. name="John"
type(name)
str
3. name=1
type(name)
int
4. name=1.5
type(name)
float
Python is a duck typing language. It means the data types of variables can change as long as the syntax is
compatible. It will look at variable it’s a number so assign class as int, and we can use it.
5. 1+1
6. "abc"+"def"
'abcdef'
7. "abc"+1
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[8], line 1
----> 1 "abc"+1
1. a=10
Name="Victor"
Salary=200000
print(a)
print(Name)
print(Salary)
10
Victor
200000
2. Name="Victor"
print(Name)
Victor
3. 1Name="Victor"
print(Name)
4. _Name="Victor"
print(_Name)
Victor
5. Name1="Victor"
print(Name)
Victor
6. $Name="Victor"
print(Name)
Cell In[16], line 1
$Name="Victor"
^
SyntaxError: invalid syntax
7. Name$="Victor"
print(Name)
Cell In[16], line 1
$Name="Victor"
^
SyntaxError: invalid syntax
8. ___Name="Victor"
print(Name)
Victor
Assigning a Multiple Value to a Variable:
a=b=c=10
x,y,z=10,20,30
print(a)
print(b)
print(c)
print(x)
print(y)
print(z)
10
10
10
10
20
30
Python Tokens
Python Tokens: In Python, every logical line of code is broken down into components known as Tokens.
Keywords
Identifiers
Literals
Operators
Keywords: Python keywords are special reserved words; they convey a special meaning to the
compiler/Interpreter. Each keyword has a special meaning and a specific operation and never uses it as a
variable.
1. ret=7
print(ret)
2. return=7
print(ret)
Cell In[23], line 1
return=7
^
SyntaxError: invalid syntax
Identifiers: Python Identifier is the name we give to identify a variable, function, class, module or other object
Or Identifier is nothing but a name is python.
Lowercase letters (a to z)
Uppercase letters (A to Z)
Digits (0 to 9)
Underscore (_)
Invalid Identifiers In Python Examples:
!var1
1 var
1_var
var#1
1. var=7
Var=8
print(var)
print(Var)
7
8
String literals
Numeric literals
Boolean literals
Special literals
String literals: Formed by enclosing a text within quotes. Both single and double quotes can be used.
Name="Victor"
print(Name)
Victor
Numeric literals: Formed by string of digits from 0 to 9, decimal point, and a plus/minus sign.
1. num=-77
print(num)
type(num)
-77
Int
2. num= 7.5
print(num)
type(num)
7.5
Float
3. num= 7.5+5j
print(num)
type(num)
(7.5+5j)
complex
1. password="abcd"
confrimpassword ="abcd"
password == confrimpassword
True
2. password="abcd"
confrimpassword ="abcde"
password == confrimpassword
False
Special literals:
confrimpassword =None
print(confrimpassword)
type (confrimpassword)
None
NoneType
Operators: Operators are special symbols that are used to carry out arithmetic and logical operations.
Arithmetic
Assignment
Comparison
Logical
Identity
Membership
Bitwise
a=7
b=2
# addition
print ('Sum: ', a + b)
# subtraction
print ('Subtraction: ', a - b)
# multiplication
print ('Multiplication: ', a * b)
# division
print ('Division: ', a / b)
# modulo
print ('Modulo: ', a % b)
# floor division
print ('Floor Division: ', a // b)
The division operator / in Python returns the exact result of the division operation as a floating-point number,
while the floor division operator // returns the quotient rounded down to the nearest integer.
# a to the power b
print ('Power: ', a ** b)
x=5
y=5
z=5
res = x == y
res2 = x == z
print (res)
print (res2)
True
True
x=5
y = 10
res = x != y
print (res)
True
x=5
y = 10
res = x < y
res1 = y < x
print (res)
print (res1)
True
False
x=5
y = 10
res = x > y
res1 = y > x
print (res)
print (res1)
False
True
x=5
y=5
z = 10
res = x >= y
res2 = x >= z
print (res)
print (res2)
True
False
x=5
y=5
z = 10
res = x <= y
res1 = x <= z
print (res)
print (res1)
True
True
# logical AND
print(True and True) # True
print(True and False) # False
True
False
# logical OR
print(True or False) # True
True
# logical NOT
print(not True) # False
False
1. x=5
y=16
x==5
True
2. x=5
y=16
y!=16
False
3. x=5
y=16
x==5 and y!=16
False
x = ["bread", "cake"]
y = ["bread", "cake"]
z=x
print(x is z)
print(x is not z)
x = ["apple", "banana"]
print("banana" in x)
x = ["apple", "banana"]
print("pineapple" not in x)
Bitwise Operators: Used to compare binary numbers. In Python, bitwise operators are used to perform
bitwise calculations on integers. The integers are first converted into binary and then operations are
performed on each bit or corresponding pair of bits, hence the name bitwise operators. The result is then
returned in decimal format.
Bitwise AND(&)
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)
a & b = 1010
&
0100
= 0000
= 0 (Decimal)
Bitwise OR(|)
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)
a | b = 1010
|
0100
= 1110
= 14 (Decimal)
Bitwise NOT(~)
Python’s bitwise NOT operator ~x inverts each bit from the binary representation of integer x so that 0
becomes 1 and 1 becomes 0. This is semantically the same as calculating ~x == -x-1 . For example, the
bitwise NOT expression ~0 becomes -1 , ~9 becomes -10 , and ~32 becomes -33 .
Bitwise XOR(^)
a = 10 = 1010 (Binary)
b = 4 = 0100 (Binary)
a ^ b = 1010
^
0100
= 1110
= 14 (Decimal)
a = 10
b=4
Output:
a&b=0
a | b = 14
~a = -11
a ^ b = 14
a = 14
Output:
a >> 1 = 7
a >> 2 = 3
a << 1 = 28
a << 2= 56
Decimal to Binary Examples
Example 1:
Solution:
160 ÷ 2 80 0 0 (LSB)
80 ÷ 2 40 0 0
40 ÷ 2 20 0 0
20 ÷ 2 10 0 0
10 ÷ 2 5 0 0
5÷2 2 1 1
2÷2 1 0 0
1÷2 0 1 1 (MSB)
Example 2:
Solution:
17 ÷ 2 8 1 1 (LSB)
8÷2 4 0 0
4÷2 2 0 0
2÷2 1 0 0
1÷2 0 1 1 (MSB)
Solution:
Now, multiplying each digit from MSB to LSB with reducing the power of the base number 2.
1 × 23 + 1 × 2 2 + 0 × 2 1 + 1 × 2 0
=8+4+0+1
= 13
Indentation in Python
Indentation is a very important concept of Python because without properly indenting the Python code, you
will end up seeing Indentation Error and the code will not get compiled.
Python Indentation
Python indentation refers to adding white space before a statement to a particular block of code. In another
word, all the statements with the same space to the right, belong to the same code block.
Python indentation is a way of telling a Python interpreter that the group of statements belongs to a particular
block of code. A block is a combination of all these statements. Block can be regarded as the grouping of
statements for a specific purpose. Most programming languages like C, C++, and Java use braces { } to
define a block of code. Python uses indentation to highlight the blocks of code. Whitespace is used for
indentation in Python. All statements with the same distance to the right belong to the same block of code. If
a block has to be more deeply nested, it is simply indented further to the right.
Statements: A simple statement is a construct that occupies a single logical line, like an assignment statement.
A compound statement is a construct that occupies multiple logical lines, such as a for loop or
a conditional statement. Statements use key words, it may or may not lead to result. The Python language has
many different types of statements like assignment statements, conditional statements, looping statements, etc.,
that help a programmer get the desired output.
Expressions: A combination of operands and operators is called an expression. The expression in Python
produces some value or result after being interpreted by the Python interpreter. An expression in Python is a
combination of operators and operands.
x = 25 # a statement
x = x + 10 # an expression
print(x)
output: 35
x = 10 + 15
x = 10
y=5
addition = x + y
subtraction = x - y
product = x * y
division = x / y
power = x**y
3. Integral Expressions: These are the kind of expressions that produce only integer results after all
computations and type conversions.
x = 10 # an integer number
y = 5.0 # a floating point number
# we need to convert the floating-point number into an integer or vice versa for summation.
result = x + int(y)
4. Floating Expressions: These are the kind of expressions which produce floating point numbers as result
after all computations and type conversions.
x = 10 # an integer number
y = 5.0 # a floating point number
# we need to convert the integer number into a floating-point number or vice versa for summation.
result = float(x) + y
Output
The sum of x and y is: 15.0
5. Relational Expressions: In these types of expressions, arithmetic expressions are written on both sides of
relational operator (> , < , >= , <=). Those arithmetic expressions are evaluated first, and then compared as per
relational operator and produce a boolean output in the end. These expressions are also called Boolean
expressions.
a = 25
b = 14
c = 48
d = 45
# The expression checks if the sum of (a and b) is the same as the difference of (c and d).
result = (a + b) == (c - d)
print("Type:", type(result))
print("The result of the expression is: ", result)
Output
Type: <class 'bool'>
The result of the expression is: False
6. Logical Expressions: These are kinds of expressions that result in either True or False. It basically
specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal to 9. As we know it is
not correct, so it will return False. Studying logical expressions, we also come across some logical operators
which can be seen in logical expressions most often. Here are some logical operators in Python:
and P and Q It returns true if both P and Q are true otherwise returns false
# Logical Expressions
R = P and Q
S = P or Q
T = not P
print(R)
print(S)
print(T)
Output
False
True
True
7. Bitwise Expressions: These are the kind of expressions in which computations are performed at bit level.
# Bitwise Expressions
a = 12
x = a >> 2
y = a << 1
print(x, y)
Output
3 24
8. Combinational Expressions: We can also use different types of expressions in a single expression, and
that will be termed as combinational expressions.
# Combinational Expressions
a = 16
b = 12
c = a + (b >> 1)
print(c)
Output
22
Control Structures: In the Python programming language, control structures are used to manage the flow of
execution in a program. They enable you to specify the order in which statements are executed based on certain
conditions.
Conditional Statements
Loops
Conditional Statements: There are situations in real life when we need to make some decisions and based
on these decisions, we decide what we should do next. Similar situations arise in programming also where we
need to make some decisions and based on these decisions we will execute the next block of code.
Conditional statements in Python languages decide the direction (Control Flow) of the flow of program
execution.
Types of Conditional Statements in Python:
1. The if statement
2. The if-else statement
3. The if-elif-else ladder
4. The nested-if statement
1. The if statement: The if statement is used to test a particular condition and if the condition is true, it
executes a block of code known as if-block. The condition of if statement can be any valid logical expression
which can be either evaluated to true or false.
Syntax:
if expression:
statement
Flowchart:
Example 1
# Simple Python program to understand the if statement
num = int(input("enter the number:"))
# Here, we are taking an integer num and taking input dynamically
if num%2 == 0:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("The Given number is an even number")
Output:
enter the number: 10
The Given number is an even number
Example 2 : Program to print the largest of the three numbers.
Output:
Enter a: 100
Enter b: 120
Enter c: 130
From the above three numbers given c is largest
2. The if-else statement: The if-else statement provides an else block combined with the if statement which is
executed in the false case of the condition. If the condition is true, then the if-block is executed. Otherwise, the
else-block is executed.
Syntax:
if condition:
#block of statements
else:
#another block of statements (else-block)
Flowchart:
Output:
3. The if-elif-else ladder: An if-elif-else ladder in python is a conditional statement that allows you to execute
different blocks of code based on multiple conditions. It is an extension of the if-else statement, and it is used when
there are more than two possible conditions to check.
Syntax:
if expression 1:
# block of statements
elif expression 2:
# block of statements
elif expression 3:
# block of statements
else:
# block of statements
Flowchart:
Example 1
# Simple Python program to understand elif statement
number = int(input("Enter the number?"))
# Here, we are taking an integer number and taking input dynamically
if number==10:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("The given number is equals to 10")
elif number==50:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("The given number is equal to 50");
elif number==100:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("The given number is equal to 100");
else:
print("The given number is not equal to 10, 50 or 100");
Output:
Example 2
# Simple Python program to understand elif statement
marks = int(input("Enter the marks? "))
# Here, we are taking an integer marks and taking input dynamically
if marks > 85 and marks <= 100:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("Congrats ! you scored grade A ...")
elif marks > 60 and marks <= 85:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("You scored grade B + ...")
elif marks > 40 and marks <= 60:
# Here, we are checking the condition. If the condition is true, we will enter the block
print("You scored grade B ...")
elif (marks > 30 and marks <= 40):
# Here, we are checking the condition. If the condition is true, we will enter the block
print("You scored grade C ...")
else:
print("Sorry you are fail ?")
Output:
4. The nested-if statement: We can have an if statement inside another if statement. This is called nesting in
computer programming. Any number of these statements can be nested inside one another. Indentation is the
only way to figure out the level of nesting. This can get confusing, so it must be avoided if we can.
Syntax: if (condition1):
# Executes when condition1 is true
if (condition2):
# Executes when condition2 is true
# if Block is end here
# if Block is end here
Flowchart:
Example 1:
# Python program to demonstrate
# nested if statement
num = 15
if num >= 0:
if num == 0:
print("Zero")
else:
print("Positive number")
else:
print("Negative number")
Output:
Positive number
Example 2:
# Python program to demonstrate
# nested if statement
i = 13
if (i == 13):
# First if statement
if (i < 15):
print ("i is smaller than 15")
# Nested - if statement
# Will only be executed if statement above
# it is true
if (i < 12):
print ("i is smaller than 12 too")
else:
print ("i is greater than 12 and smaller than 15")
Output:
i is smaller than 15
i is greater than 12 and smaller than 15
Loops: Python programming language provides two types of loops 1. For loop 2. While loop to handle
looping requirements.
1. For Loop: In computer programming, loops are used to repeat a block of code.
Output
Swift
Python
Go
In the above example, we have created a list called languages. As the list has 3 elements, the loop
iterates 3 times.
The value of i is
Swift in the first iteration.
Python in the second iteration.
Go in the third iteration.
for loop Syntax
Here, val accesses each item of the sequence on each iteration. The loop continues until we reach the last item
in the sequence.
language = 'Python'
P
y
t
h
o
n
Here, we have printed each character of the string language using a for loop.
values = range(4)
0
1
2
3
1st 0 Prints 0 No
2nd 1 Prints 1 No
3rd 2 Prints 2 No
Yes
4th 3 Prints 3
The loop terminates.
A for loop can have an optional else clause. This else clause executes after the iteration completes.
digits = [0, 1, 5]
for i in digits:
print(i)
else:
print("No items left.")
Output
0
1
5
No items left.
Here, the for loop prints all the items of the digits list. When the loop finishes, it executes the else block and
prints No items left.
Note: The else block will not execute if the for loop is stopped by a break statement.
We can also use for loop to repeat an action a certain number of times. For example,
languages = ['Swift', 'Python', 'Go']
Hi
Hi
Hi
Here, we used the list languages to run the loop three times. However, we didn't use any of the elements of the
list.
In such cases, it is clearer to use the _ (underscore) as the loop variable. The _ indicates that a loop variable is a
placeholder and its value is intentionally being ignored.
For example,
A for loop can also have another for loop inside it. For each cycle of the outer loop, the inner loop completes its
entire sequence of iterations. For example,
# outer loop
for i in range(2):
# inner loop
for j in range(2):
print(i,j)
Output
00
01
10
11
In this example, we have used a nested for loop. This is how the above code executes.
Python while loop is used to run a block code until a certain condition is met.
while condition:
# body of while loop
Here,
1
2
3
4
5
i = 1
True 1 is printed. i is increased to 2.
n=5
i = 2
True 2 is printed. i is increased to 3.
n=5
i = 3
True 3 is printed. i is increased to 4.
n=5
i = 4
True 4 is printed. i is increased to 5.
n=5
i = 5
True 5 is printed. i is increased to 6.
n=5
i = 6
False The loop is terminated.
n=5
total = 0
Enter a number: 12
Enter a number: 4
Enter a number: -5
Enter a number: 0
total = 11
In the above example, the while iterates until the user enters zero. When the user enters zero, the test condition
evaluates to False and the loop ends.
If the condition of a loop is always True, the loop runs for infinite times (until the memory is full). For
example,
age = 32
Inside loop
Inside loop
Inside loop
Inside else
Note: The else block will not execute if the while loop is terminated by a break statement.
counter = 0
print('Inside loop')
counter = counter + 1
else:
print('Inside else')
Output
Inside loop
The for loop is usually used when the number of iterations is known. For example,
# this loop is iterated 4 times (0 to 3)
for i in range(4):
print(i)
The while loop is usually used when the number of iterations is unknown. For example,
while condition:
# run code until the condition evaluates to False
In programming, the break and continue statements are used to alter the flow of loops:
break exits the loop entirely
continue skips the current iteration and proceeds to the next one.
break
The above image shows the working of break statements in for and while loops.
Note: The break statement is usually used with decision-making statements such as if...else.
Example: break Statement with for Loop
We can use the break statement with the for loop to terminate the loop when a certain condition is met. For
example,
for i in range(5):
if i == 3:
break
print(i)
Output
0
1
2
if i == 3:
break
terminates the loop when i is equal to 3. Hence, the output doesn't include values after 2.
Note: We can also terminate the while loop using break statement
We can also terminate the while loop using the break statement. For example,
i=0
while i < 5:
if i == 3:
break
print(i)
i += 1
Output
0
1
2
if i == 3:
break
terminates the loop when i is equal to 3.
The continue statement skips the current iteration of the loop and the control flow of the program goes to the
next iteration.
Syntax
continue
We can use the continue statement with the for loop to skip the current iteration of the loop and jump to the
next iteration. For example,
for i in range(5):
if i == 3:
continue
print(i)
Output
0
1
2
4
skips the current iteration when i is equal to 3, and continues the next iteration. Hence, the output has all the
values except 3.
Note: We can also use the continue statement with a while loop.
We can skip the current iteration of the while loop using the continue statement. For example,
# program to print odd numbers from 1 to 10
num = 0
if (num % 2) == 0:
continue
print(num)
Output
1
3
5
7
9
In the above example, we have used the while loop to print the odd numbers between 1 and 10. Here,
if (num % 2) == 0:
continue
skips the current iteration when the number is even and starts the next iteration.
UNIT-II
Data Types
Mutable vs immutable data type: Mutable or immutable is the fancy word for explaining the property of
data types of being able to get updated after being initialized. The basic explanation is thus: A mutable object is
one whose internal state is changeable. On the contrary, once an immutable object in Python has been created,
we cannot change it in any way.
Anything is said to be mutable when anything can be modified or changed. The term "mutable" in Python refers
to an object's capacity to modify its values. These are frequently the things that hold a data collection.
Immutable refers to a state in which no change can occur over time. A Python object is referred to as immutable
if we cannot change its value over time. The value of these Python objects is fixed once they are made.
Numbers - Introduction to Numbers: Numbers in Python refer to the numeric data types in Python
programming. Python supports three kinds of numeric data types: int, float, and complex.
Integers:
In Python, integers are zero, positive or negative whole numbers without a fractional part and having
unlimited precision, e.g. 0, 100, -10. The followings are valid integer literals in Python.
#integer variables
x=0
print(x)
x = 100
print(x)
x = -10
print(x)
x = 1234567890
print(x)
x = 5000000000000000000000000000000000000000000000000000000
print(x)
Output
0
100
-10
1234567890
5000000000000000000000000000000000000000000000000000000
Float:
In Python, floating point numbers (float) are positive and negative real numbers with a fractional part
denoted by the decimal symbol. e.g. 1234.56, 3.142, -1.55, 0.23.
f = 1.2
print(f) #output: 1.2
print(type(f)) #output: <class 'float'>
Complex Numbers: A complex number is a number with real and imaginary components. For
example, 5 + 6j is a complex number where 5 is the real component and 6 multiplied by j is an imaginary
component.
a = 5+2j
print(a)
print(type(a))
(5+2j)
<class 'complex'>
Built-in Functions: Python provides a lot of built-in functions that ease the writing of code.
Function Name Description
Return true if all the elements of a given iterable( List, Dictionary, Tuple, set,
Python all() Function etc) are True else it returns False
Returns true if any of the elements of a given iterable( List, Dictionary, Tuple,
Python any() Function set, etc) are True else it returns False
Python anext() Function used for getting the next item from an asynchronous iterator
Python bool() Function Return or convert a value to a Boolean value i.e., True or False
Python breakpoint() It is used for dropping into the debugger at the call site during runtime for
Function debugging purposes
Python bytearray() Returns a byte array object which is an array of given bytes
Function
Python chr() Function Returns a string representing a character whose Unicode code point is an integer
Function Name Description
Python delattr() Function Delete the named attribute from the object
Python dir() Function Returns a list of the attributes and methods of any object
Python divmod() Takes two numbers and returns a pair of numbers consisting of their quotient
Function and remainder
Python enumerate() Adds a counter to an iterable and returns it in a form of enumerating object
Function
Parses the expression passed to it and runs Python expression(code) within the
Python eval() Function program
Python exec() Function Used for the dynamic execution of the program
Filters the given sequence with the help of a function that tests each element in
Python filter() Function the sequence to be true or not
Python globals() Returns the dictionary of the current global symbol table
Function
Python hasattr() Check if an object has the given named attribute and return true if present
Function
Python help() Function Display the documentation of modules, functions, classes, keywords, etc
Python hex() Function Convert an integer number into its corresponding hexadecimal form
Python locals() Function Returns the dictionary of the current local symbol table
Returns a map object(which is an iterator) of the results after applying the given
Python map() Function function to each item of a given iterable
Python max() Function Returns the largest item in an iterable or the largest of two or more arguments
Python min() Function Returns the smallest item in an iterable or the smallest of two or more arguments
Python next() Function Receives the next item from the iterator
Python ord() Function Returns the Unicode equivalence of the passed argument
Python reversed() Returns an iterator that accesses the given sequence in the reverse order
Function
Python round() Function Rounds off to the given number of digits and returns the floating-point number
Returns a list with the elements in a sorted manner, without modifying the
Python sorted() Function original sequence
Python vars() Function Returns the __dict__ attribute for a module, class, instance, or any other object
Related Modules: Python Module is a file that contains built-in functions, classes, its and variables. There
are many Python modules, each with its specific work.
Output:
4.0
720
Syntax:
from module_name import *
Output:
4.0
720
Sequences: Sequences are an object type in Python that allows the user to store data one after each other.
Operations can be performed on a sequence, to examine and manipulated the stored items. There are several
different types of sequence objects in Python; those are 1. Strings 2. Lists 3. Tuples 4. Dictionaries 5. Set
Types.
1. Strings: A String is a data structure in Python that represents a sequence of characters. It is an immutable
data type, meaning that once we have created a string, we cannot change it. Strings are used widely in many
different applications, such as storing and manipulating text data, representing names, addresses, and other
types of data that can be represented as text.
Example:
In this example, we will demonstrate different ways to create a Python String. We will create a string using
single quotes (‘ ‘), double quotes (” “), and triple double quotes (“”” “””). The triple quotes can be used to
declare multiline strings in Python.
1. Accessing Characters by Positive Index Number: In this type of Indexing, we pass a Positive index(which
we want to access) in square brackets. The index number starts from index number 0 (which denotes the first
character of a string).
2. Accessing Characters by Negative Index Number: In this type of Indexing, we pass the Negative
index(which we want to access) in square brackets. Here the index number starts from index number -1 (which
denotes the last character of a string)
# declaring the string
str = "GEEKSFORGEEKS"
Output
Output
Slicing
Syntax :
string[start : end : step]
start : We provide the starting index.
end : We provide the end index(this is not included in substring).
step : It is an optional argument that determines the increment between each index for slicing.
# declaring the string
str ="GEEKSFORGEEKS"
Output
GEE
EK
SEGOSE
print("GEEKSFORGEEKS:-")
print(str)
Output
GEEKSFORGEEKS:-
GEEKSFORGEEKS
Reverse String :-
SKEEGROFSKEEG
1. string="abcdefgh"
len(string)
2. string[0]
'a'
3. string[7]
'h'
4. string[8]
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Cell In[46], line 1
----> 1 string[8]
5. string[0:4]
'abcd'
6. string[3:4]
'd'
7. string[:4]
'abcd'
8. string[5:4]
''
9. string[5:]
'fgh'
10. string[:-1]
'abcdefg'
11. string[:-4]
'abcd'
Modify Strings:
Upper Case
a = "Hello, World!"
print([Link]())----------------HELLO, WORLD!
Lower Case
a = "Hello, World!"
print([Link]())----------------hello, world!
Remove Whitespace
Whitespace is the space before and/or after the actual text, and very often we want to remove this space.
Example
The strip() method removes any whitespace from the beginning or the end:
a = "Hello, World!"
print([Link]("H", "J"))--------------------- Jello, World!
Split String
The split() method returns a list where the text between the specified separator becomes the list items.
Example
The split() method splits the string into substrings if it finds instances of the separator:
a = "Hello, World!"
print([Link](",")) # returns ['Hello', ' World!']
String Concatenation
Example
a = "Hello"
b = "World"
c=a+b
print(c)----------- HelloWorld
Example
a = "Hello"
b = "World"
c=a+""+b
print(c)------------ Hello World
Format – Strings
we cannot combine strings and numbers like this:
age = 36
txt = "My name is John, I am " + age
print(txt)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[12], line 2
1 age = 36
----> 2 txt = "My name is John, I am " + age
3 print(txt)
But we can combine strings and numbers by using the format() method!
The format() method takes the passed arguments, formats them, and places them in the string where the
placeholders {} are:
Example
age = 36
txt = "My name is John, and I am {}"
print([Link](age))---------------------------- My name is John, and I am 36
2. Lists: Python Lists are just like dynamically sized arrays, declared in other languages .list is a collection
of things, enclosed in [ ] and separated by commas. Simply a sequence of mutable objects.
Lists are used to store multiple items in a single variable.
# Create a List:
List Items
List items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that lists are ordered, it means that the items have a defined order, and that order will not change.
If we add new items to a list, the new items will be placed at the end of the list.
Changeable
The list is changeable, meaning that we can change, add, and remove items in a list after it has been created.
Allow Duplicates
Since lists are indexed, lists can have items with the same value:
Example
List Length
To determine how many items a list has, use the len() function:
Example
Example
Access Items
List items are indexed and we can access them by referring to the index number:
Example
Range of Indexes
We can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new list with the specified items.
Example
By leaving out the start value, the range will start at the first item:
Example
This example returns the items from the beginning to, but NOT including, "kiwi":
Example
Example
To change the value of items within a specific range, define a list with the new values, and refer to the range of
index numbers where we want to insert the new values:
Example
Change the values "banana" and "cherry" with the values "blackcurrant" and "watermelon":
thislist = ["apple", "banana", "cherry", "orange", "kiwi", "mango"]
thislist[1:3] = ["blackcurrant", "watermelon"]
print(thislist)-------------- ['apple', 'blackcurrant', 'watermelon', 'orange', 'kiwi', 'mango']
If we insert more items than we replace, the new items will be inserted where we specified, and the remaining
items will move accordingly:
Example
If we insert less items than we replace, the new items will be inserted where we specified, and the remaining
items will move accordingly:
Example
Change the second and third value by replacing it with one value:
Insert Items
To insert a new list item, without replacing any of the existing values, we can use the insert() method.
The insert() method inserts an item at the specified index:
Example
Append Items
To add an item to the end of the list, use the append() method:
Example
Example
Example
Remove "banana":
If there are more than one item with the specified value, the remove() method removes the first occurance:
Example
Example
Example
3. Tuples: Tuples are used to store multiple items in a single variable. A tuple is a collection which is ordered
and unchangeable. Tuples are written with round brackets.
Tuple Items
Tuple items are ordered, unchangeable, and allow duplicate values.
Tuple items are indexed, the first item has index [0], the second item has index [1] etc.
Ordered
When we say that tuples are ordered, it means that the items have a defined order, and that order will not
change.
Unchangeable
Tuples are unchangeable, meaning that we cannot change, add or remove items after the tuple has been created.
Allow Duplicates
Since tuples are indexed, they can have items with the same value:
Example
Tuple Length
To determine how many items a tuple has, use the len() function:
Example
Range of Indexes
We can specify a range of indexes by specifying where to start and where to end the range.
When specifying a range, the return value will be a new tuple with the specified items.
Example
Example
This example returns the items from the beginning to, but NOT included, "kiwi":
By leaving out the end value, the range will go on to the end of the tuple:
Example
This example returns the items from "cherry" and to the end:
Add Items
Since tuples are immutable, they do not have a built-in append() method, but there are other ways to add items
to a tuple.
1. Convert into a list: Just like the workaround for changing a tuple, we can convert it into a list, add wer
item(s), and convert it back into a tuple.
Example
Convert the tuple into a list, add "orange", and convert it back into a tuple:
2. Add tuple to a tuple. We are allowed to add tuples to tuples, so if we want to add one item, (or many), create
a new tuple with the item(s), and add it to the existing tuple:
Example
Create a new tuple with the value "orange", and add that tuple:
Remove Items
Tuples are unchangeable, so we cannot remove items from it, but we can use the same workaround as we used
for changing and adding tuple items:
Example
Convert the tuple into a list, remove "apple", and convert it back into a tuple:
Example
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[19], line 3
1 thistuple = ("apple", "banana", "cherry")
2 del thistuple
----> 3 print(thistuple) #this will raise an error because the tuple no longer exists
If the number of variables is less than the number of values, we can add an * to the variable name and the values
will be assigned to the variable as a list:
Example
print(green)
print(yellow)
print(red)
apple
banana
['cherry', 'strawberry', 'raspberry']
If the asterisk is added to another variable name than the last, Python will assign values to the variable until the
number of values left matches the number of variables left.
Example
print(green)
print(tropic)
print(red)
apple
['mango', 'papaya', 'pineapple']
cherry
Example
4. Dictionaries: Dictionaries are used to store data values in key: value pairs. A dictionary is a collection
which is ordered, changeable and do not allow duplicates. Dictionaries are mutable objects.
Dictionaries are written with curly brackets, and have keys and values:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict)----------- {'brand': 'Ford', 'model': 'Mustang', 'year': 1964}
Dictionary Items
Dictionary items are ordered, changeable, and does not allow duplicates.
Dictionary items are presented in key:value pairs, and can be referred to by using the key name.
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])--------- Ford
Ordered
When we say that dictionaries are ordered, it means that the items have a defined order, and that order will not
change.
Changeable
Dictionaries are changeable, meaning that we can change, add or remove items after the dictionary has been
created.
Duplicates Not Allowed
Dictionaries cannot have two items with the same key:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964,
"year": 2020
}
print(thisdict)---------------- {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
thisdict = {
"brand": "Ford",
"electric": False,
"year": 1964,
"colors": ["red", "white", "blue"]
}
{'brand': 'Ford', 'electric': False, 'year': 1964, 'colors': ['red', 'white', 'blue']}
Accessing Items
We can access the items of a dictionary by referring to its key name, inside square brackets:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
x = thisdict["model"]------------- 'Mustang'
There is also a method called get() that will give we the same result:
Example
x = [Link]("model")------------ 'Mustang'
Get Keys
The keys() method will return a list of all the keys in the dictionary.
Example
Change Values
We can change the value of a specific item by referring to its key name:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["year"] = 2018--------------- {'brand': 'Ford', 'model': 'Mustang', 'year': 2018}
Update Dictionary
The update() method will update the dictionary with the items from the given [Link] argument must be a
dictionary, or an iterable object with key:value pairs.
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]({"year": 2020})----------------- {'brand': 'Ford', 'model': 'Mustang', 'year': 2020}
Adding Items
Adding an item to the dictionary is done by using a new index key and assigning a value to it:
Example
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
thisdict["color"] = "red"
print(thisdict)---------------- {'brand': 'Ford', 'model': 'Mustang', 'year': 1964, 'color': 'red'}
Removing Items
There are several methods to remove items from a dictionary:
Example
The pop() method removes the item with the specified key name:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
[Link]("model")
print(thisdict)-------------------- {'brand': 'Ford', 'year': 1964}
Nested Dictionaries
A dictionary can contain dictionaries, this is called nested dictionaries.
Example
Create a dictionary that contain three dictionaries:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
5. Set Types: Sets are used to store multiple items in a single variable.
Set items are unchangeable, but we can remove items and add new items.
ExampleCreate a Set:
thisset = {"apple", "banana", "cherry"}
print(thisset)-------------------------- {'apple', 'cherry', 'banana'}
Set Items
Set items are unordered, unchangeable, and do not allow duplicate values.
Unordered
Unordered means that the items in a set do not have a defined order. Set items can appear in a different order
every time we use them, and cannot be referred to by index or key.
Unchangeable
Set items are unchangeable, meaning that we cannot change the items after the set has been created. Once a set
is created, we cannot change its items, but we can remove items and add new items.
The values True and 1 are considered the same value in sets, and are treated as duplicates:
Example
True and 1 is considered the same value:
The values False and 0 are considered the same value in sets, and are treated as duplicates:
Example
False and 0 is considered the same value:
Example
String, int and boolean data types:
Access Items
We cannot access items in a set by referring to an index or a key.
But we can loop through the set items using a for loop, or ask if a specified value is present in a set, by using
the in keyword.
Example
Loop through the set, and print the values:
apple
cherry
banana
Example
Check if "banana" is present in the set:
thisset = {"apple", "banana", "cherry"}
print("banana" in thisset)---------------- True
Add Items
Once a set is created, we cannot change its items, but we can add new [Link] add one item to a set use
the add() method.
Example
Add Sets
To add items from another set into the current set, use the update() method.
Example
Add elements from tropical into thisset:
thisset = {"apple", "banana", "cherry"}
tropical = {"pineapple", "mango", "papaya"}
[Link](tropical)
print(thisset)------------------------- {'papaya', 'apple', 'cherry', 'banana', 'pineapple', 'mango'}
Remove Item
To remove an item in a set, use the remove(), or the discard() method.
Example
Remove "banana" by using the remove() method:
We can also use the pop() method to remove an item, but this method will remove a random item, so we cannot
be sure what item that gets removed.
Sets are unordered, so when using the pop() method, we do not know which item that gets removed.
Example
The clear() method empties the set:
thisset = {"apple", "banana", "cherry"}
[Link]()
print(thisset)---------------------- set()
Example
The del keyword will delete the set completely:
thisset = {"apple", "banana", "cherry"}
del thisset
print(thisset)
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[24], line 3
1 thisset = {"apple", "banana", "cherry"}
2 del thisset
----> 3 print(thisset)
Example
The union() method returns a new set with all items from both sets:
def greet():
print('Hello World!')
Here, we have created a simple function named greet() that prints Hello World!
Note: When writing a function, pay attention to indentation, which are the spaces at the start of a code line.
In the above code, the print() statement is indented to show it's part of the function body, distinguishing the
function's definition from its body.
Calling a Function:
In the above example, we have declared a function named greet().
def greet():
print('Hello World!')
If we run the above code, we won't get an output. It’s because creating a function doesn't mean we are executing
the code inside it. It means the code is there for us to use if we want to. To use this function, we need to call the
function.
Function Call
greet()
print('Outside function')
Output
Hello World!
Outside function
In the above example, we have created a function named greet(). Here's how the control of the program flows:
Here,
1. When the function greet() is called, the program's control transfers to the function definition.
2. All the code inside the function is executed.
3. The control of the program jumps to the next statement after the function call.
# pass argument
greet("John")
Sample Output 1
Hello John
Here, we passed 'John' as an argument to the greet() function. We can pass different arguments in each call,
making the function re-usable and dynamic. Let's call the function with a different argument.
greet("David")
Sample Output 2
Hello David
Output
Sum: 9
In the above example, we have created a function named add_numbers() with arguments: num1 and num2.
The return Statement
# function call
square = find_square(3)
print('Square:', square)
Output
Square: 9
In the above example, we have created a function named find_square(). The function accepts a number and
returns the square of the number.
Note: The return statement also denotes that the function has ended. Any code after return is not executed.
Output
Sum: 5
Sum: 10
Sum: 15
Here, we have provided default values 7 and 8 for parameters a and b respectively. Here's how this program
works
1. add_number(2, 3)
Both values are passed during the function call. Hence, these values are used instead of the default values.
2. add_number(2)
Only one value is passed during the function call. So, according to the positional argument 2 is assigned to
argument a, and the default value is used for parameter b.
3. add_number()
No value is passed during the function call. Hence, default value is used for both parameters a and b.
def find_sum(*numbers):
result = 0
Output
Sum = 6
Sum = 13
In the above example, we have created the function find_sum() that accepts arbitrary arguments. Notice the
lines,
find_sum(1, 2, 3)
find_sum(4, 9)
Here, we are able to call the same function with different arguments.
Note: After getting multiple values, numbers behave as an array so we are able to use the for loop to access
each value.
Python Recursion
Recursion is the process of defining something in terms of itself. A physical world example would be to place
two parallel mirrors facing each other. Any object in between them would be reflected recursively.
Following is an example of a recursive function to find the factorial of an integer. Factorial of a number is the
product of all the integers from 1 to that number. For example, the factorial of 6 (denoted as 6!)
is 1*2*3*4*5*6 = 720.
num = 3
print("The factorial of", num, "is", factorial(num))
Run Code
Output
The factorial of 3 is 6
In the above example, factorial() is a recursive function as it calls itself. When we call this function with a
positive integer, it will recursively call itself by decreasing the number. Each function multiplies the number
with the factorial of the number below it until it is equal to one. This recursive call can be explained in the
following steps.
Let's look at an image that shows a step-by-step process of what is going on:
Our recursion ends when the number reduces to 1. This is called the base condition. Every recursive function
must have a base condition that stops the recursion or else the function calls itself infinitely. The Python
interpreter limits the depths of recursion to help avoid infinite recursions, resulting in stack overflows.
Here,
argument(s) - any value passed to the lambda function
expression - expression is executed and returned
Let's see an example,
Here, we have defined a lambda function and assigned it to the variable named greet.
To execute this lambda function, we need to call it. Here's how we can call the lambda function
The lambda function above simply prints the text 'Hello World'.
# lambda call
greet_user('Delilah')
greet_user('Delilah')
File Handling: Files are named locations on disk to store related information. They are used to permanently
store data in a non-volatile memory (e.g. hard disk). Since Random Access Memory (RAM) is volatile (which
loses its data when the computer is turned off), we use files for future use of the data by permanently storing
them. When we want to read from or write to a file, we need to open it first. When we are done, it needs to be
closed so that the resources that are tied with the file are freed. Hence, in Python, a file operation takes place in
the following order:
1) Open a file
Opening a file: The key function for working with files in Python is the open() function. The open() function
takes two parameters; filename, and mode.
Syntax:-file object = open(<file-name>, <access-mode>)
In addition you can specify if the file should be handled as binary or text mode
"t" - Text - Default value. Text mode
"b" - Binary - Binary mode (e.g. images)
To open a file for reading it is enough to specify the name of the file:
f = open("[Link]")
Because "r" for read, and "t" for text are the default values, you do not need to specify them.
Note: Make sure the file exists, or else you will get an error.
Modes of file:
1) r : It opens the file to read-only mode. The file pointer exists at the beginning. The file is by default open in
this mode if no access mode is passed.
2) rb: It opens the file to read-only in binary format. The file pointer exists at the beginning of the file.
3) r+ : It opens the file to read and write both. The file pointer exists at the beginning of the file.
4) rb+: It opens the file to read and write both in binary format. The file pointer exists at the beginning of the
file.
5) w: It opens the file to write only. It overwrites the file if previously exists or creates a new one if no file
exists with the same name. The file pointer exists at the beginning of the file.
6) wb: It opens the file to write only in binary format. It overwrites the file if it exists previously or creates a
new one if no file exists. The file pointer exists at the beginning of the file.
7) w+: It opens the file to write and read both. It is different from r+ in the sense that it overwrites the previous
file if one exists where as r+ doesn't overwrite the previously written file. It creates a new file if no file exists.
The file pointer exists at the beginning of the file.
8) wb+: It opens the file to write and read both in binary format. The file pointer exists at the beginning of the
file.
9) a: It opens the file in the append mode. The file pointer exists at the end of the previously written file if exists
any. It creates a new file if no file exists with the same name.
10) ab: It opens the file in the append mode in binary format. The pointer exists at the end of the previously
written file. It creates a new file in binary format if no file exists with the same name.
11) a+: It opens a file to append and read both. The file pointer remains at the end of the file if a file exists. It
creates a new file if no file exists with the same name.
12) ab+: It opens a file to append and read both in binary format. The file pointer remains at the end of the file.
Assume we have the following file, located in the same folder as Python:
[Link]
Hello! Welcome to [Link]
This file is for testing purposes.
Good Luck!
The open() function returns a file object, which has a read() method for reading the content of the file:
Example
f = open("[Link]", "r")
print([Link]())
If the file is located in a different location, you will have to specify the file path, like this:
Example
f = open("D:\\myfiles\[Link]", "r")
print([Link]())
By default the read() method returns the whole text, but you can also specify how many characters you want to
return:
Example
f = open("[Link]", "r")
print([Link](5))
Read Lines
Example
Read one line of the file:
f = open("[Link]", "r")
print([Link]())
By calling readline() two times, you can read the two first lines:
Example
By looping through the lines of the file, you can read the whole file, line by line:
Example
f = open("[Link]", "r")
for x in f:
print(x)
Close Files
It is a good practice to always close the file when you are done with it.
Example
f = open("[Link]", "r")
print([Link]())
[Link]()
To write to an existing file, you must add a parameter to the open() function:
"a" - Append - will append to the end of the file
"w" - Write - will overwrite any existing content
Example
Open the file "[Link]" and append content to the file:
f = open("[Link]", "a")
[Link]("Now the file has more content!")
[Link]()
Example
Open the file "[Link]" and overwrite the content:
f = open("[Link]", "w")
[Link]("Woops! I have deleted the content!")
[Link]()
#open and read the file after the overwriting:
f = open("[Link]", "r")
print([Link]())
"x" - Create - will create a file, returns an error if the file exist
"a" - Append - will create a file if the specified file does not exist
"w" - Write - will create a file if the specified file does not exist
Example
Create a file called "[Link]":
f = open("[Link]", "x")
Result: a new empty file is created!
Example
Create a new file if it does not exist:
f = open("[Link]", "w")
Unit – IV
Modules
Modules and Files: In Python, modules are simply files with a .py extension that contain Python code. They
can be imported into other Python programs using the import statement.
Built-in modules: These modules are included with the Python interpreter. They provide a variety of functions
and classes that we can use in our programs.
User-defined modules: These modules are created by Python programmers. They can be used to share code
with other Python programmers or to organize our own code.
We can import built-in modules using the import statement. For example, the following code imports the math
module:
import math
We can import user-defined modules using the import statement. For example, the following code imports the
my_module module:
import my_module
We can also import specific functions and classes from modules using the from statement. For example, the
following code imports the sqrt() function from the math module:
from math import sqrt
This allows us to use the sqrt() function without having to prefix it with the math module name.
We can also import all of the functions and classes from a module using the import * statement. However, this
is not recommended, as it can make our code difficult to read and maintain.
Modules are a powerful tool that can help us to write more organized and reusable Python code.
Namespaces: A namespace is a system that has a unique name for each and every object in Python. An
object might be a variable or a method. Python itself maintains a namespace in the form of a Python
dictionary.
Types of namespaces: When Python interpreter runs solely without any user-defined modules, methods,
classes, etc. Some functions like print(), id() are always present, these are built-in namespaces. When a user
creates a module, a global namespace gets created, later the creation of local functions creates the local
namespace. The built-in namespace encompasses the global namespace and the global namespace
encompasses the local namespace.
A lifetime of a namespace depends upon the scope of objects, if the scope of an object ends; the lifetime of
that namespace comes to an end. Hence, it is not possible to access the inner namespace’s objects from an
outer namespace.
Built-in namespace
• The built-in namespace contains the names of all of Python’s built-in objects. These are available at all
times when Python is running.
• You can list the objects in the built-in namespace with the following command
Ex:
>>> dir(__builtins__)
The Python interpreter creates the built-in namespace when it starts up. This namespace remains in existence
until the interpreter terminates.
Global namespace
• The global namespace contains any names defined at the level of the main program. Python creates the
global namespace when the main program body starts, and it remains in existence until the interpreter
terminates.
• Strictly speaking, this may not be the only global namespace that exists. The interpreter also creates a
global namespace for any module that your program loads with the import statement.
• The interpreter creates a new namespace whenever a function executes. That namespace is local to the
function and remains in existence until the function terminates.
• Functions don’t exist independently from one another only at the level of the main program. You can
also define one function inside another
Importing Modules: To make use of the functions in a module, we need to import the module with
an import statement. An import statement is made up of the import keyword along with the name of the module.
import random
When we import a module, we are making it available to us in our current program as a separate namespace.
This means that we will have to refer to the function in dot notation, as in [module].[function].
In practice, with the example of the random module, this may look like a function such as:
Let’s create a for loop to show how we will call a function of the random module within program:
import random
for i in range(10):
print([Link](1, 25))
This small program first imports the random module on the first line, then moves into a for loop which will be
working with 10 elements. Within the loop, the program will print a random integer within the range of 1
through 25 (inclusive). The integers 1 and 25 are passed to [Link]() as its parameters.
When we run the program, we’ll receive 10 random integers as output. Because these are random you’ll likely
get different integers each time you run the program, but they’ll generate something like this:
Output
6
9
1
14
3
22
10
1
15
9
If you would like to use functions from more than one module, you can do so by adding
multiple import statements:
import random
import math
To make use of our additional module, we can add the constant pi from math to our program, and decrease the
number of random integers printed out:
import random
import math
for i in range(5):
print([Link](1, 25))
print([Link])
Now, when we run our program, we’ll receive output that looks like this, with an approximation of pi as our last
line of output:
Output
18
10
7
13
10
3.141592653589793
The import statement allows you to import one or more modules into your Python program, letting you make
use of the definitions constructed in those modules.
In other programs, you may see the import statement take in references to everything defined within the module
by using an asterisk (*) as a wildcard, but this is discouraged. Let’s first review at importing one specific
function, randint() from the random module:
Here, we first call the from keyword, then random for the module. Next, we use the import keyword and call the
specific function we would like to use.
Now, when we implement this function within our program, we will no longer write the function in dot notation
as [Link]() but instead will only write randint():
for i in range(10):
print(randint(1, 25))
When you run the program, you’ll receive output similar to what we received earlier.
Using the from … import construction allows us to reference the defined elements of a module within our
program’s namespace, letting us avoid dot notation.
Python Module Attributes: name, doc, file, dict
Python module has its attributes that describes it. Attributes perform some tasks or contain some information
about the module. Some of the important attributes are explained below:
__name__ Attribute
The __name__ attribute returns the name of the module. By default, the name of the file (excluding the
extension .py) is the value of __name__attribute.
In the same way, it gives the name of your custom module e.g. calc module will return 'calc'.
However, this can be modified by assigning different strings to this attribute. Change [Link] as shown
below.
• In addition to these many built-in functions, there are also a large number of pre-defined functions
available as a part of libraries bundled with Python distributions. These functions are defined in modules
which are known as built-in modules.
• These built-in modules are written in C language and integrated with the Python shell.
• To display a list of all of the available modules in Python Programming Language, we can use the
following command in the Python console:
help('modules')
• Math Module
• Statistics Module
Working with Math Module of Python: most popular mathematical functions that are defined in the math
module include,
Trigonometric functions
Representation functions
Logarithmic functions
Angle conversion functions, etc.
In addition, two mathematical constants- pi and e are also defined in this module.
>>>[Link]
3.141592653589793
Another well-known mathematical constant is e, which is known as Euler’s number. Its value
equals 2.718281828459045.
Ex:
>>>math.e
2.718281828459045
Trigonometric Ratios For calculating various trigonometric ratios for a given angle, the math module contains
several functions. The trigonometric functions such as sin, cos, tan, etc. take the angle argument in radians,
While we are used to express the angle in degrees.
In the math module, we have two angle conversion functions that help us to convert the angle from degrees to
radians and vice versa.
degrees()
radians()
For Example,
In this example, we will be converting the angle of 30 degrees to radians and then back again to the degree.
>>>[Link](30)
0.5235987755982988
>>>[Link](8.90)
509.9324376664327
In this example, we will find the value of sin, cos, and tan ratios for the angle of 30 degrees which in radians is
equal to 0.5235987755982988 radians.
>>>[Link](0.5235987755982988)
0.49999999999999994
>>>[Link](0.5235987755982988)
0.8660254037844387
>>>[Link](0.5235987755982988)
0.5773502691896257
[Link](),
math.log10()
[Link]()
[Link]()
[Link]()
[Link]()
[Link]() etc.
Working with Statistics Module of Python: The statistics module provides functions to mathematical
statistics of numeric data. Some of the popular statistical functions are defined in this module are as follows:
Mean
Median
Mode
Standard Deviation
Mean
The mean() method returns the arithmetic mean of the numbers present in a list.
For Example,
>>>statistics . mean([2,5,6,9])
5.5
Median
The median() method returns the middle value of numeric data present in a list.
For Example,
>>>[Link]([1,2,3,7,8,9])
5.0
>>>[Link]([1,2,3,8,9])
3.0
Mode
The mode() method returns the most common data point present in the list.
For Example,
>>>statistics . mode([2,5,3,2,8,3,9,4,2,5,6])
Standard Deviation
The stdev() method returns the standard deviation on a given sample in the form of a list.
For Example,
1.3693063937629153
Packages: We usually organize our files in different folders and subfolders based on some criteria, so that
they can be managed easily and efficiently. For example, we keep all our games in a Games folder and we
can even subcategorize according to the genre of the game or something like this. The same analogy is
followed by the packages in Python.
Every package in Python must contain an __init__.py file since it identifies the folder as a package. It generally
contains the initialization code but may also be left empty. A possible hierarchical representation of the shifting
items package in the first example can be given below. Here, shifting items is our main package. We further
divide this into three sub packages: books, CDs and toys. Each package and subpackage contains the
mandatory __init__.py file. Further, the sub packages contain files based on their utility. Books contain two
files [Link] and non_fiction.py, the package CDs contain [Link] and [Link], and the package toys contain
soft_toys.py and [Link].
Below is the folder structure of the python package.
calculator
|
|
|------ __init__.py
|
|
|------ [Link]
| |
| |---------- add()
|
|
|------ [Link]
| |
| |---------- sub()
|
|
|------ [Link]
| |
| |---------- mul()
|
|
|------ [Link]
|
|---------- div()
Now, let’s see how we can create a python package using the above steps. We will create a calculator package
with modules addition, subtraction, multiplication, and division. Now, let’s create all these modules.
[Link]
def add(a,b):
return a+b
[Link]
def sub(a,b):
return a-b
[Link]
def mul(a,b):
return a*b
[Link]
def div(a,b):
return a/b
How to Import Modules from the Python Packages.
We can import modules from the python packages using import and from keyword and using . operator. The
syntax to import the module from the python packages is given below.
Syntax:
Import package_name.mudule_name
Code:
from calculator import addition
from calculator import subtraction
from calculator import multiplication
from calculator import division
Output:
Addition of 8 and 4 is: 12
Subtraction of 7 and 2 is: 5
Multiplication of 3 and 4 is: 12
Division of 12 and 3 is: 4.0
Reusability
Working with modules makes the code reusable.
Simplicity
The module focuses on a small proportion of the problem, rather than focusing on the entire problem.
Scoping
A separate namespace is defined by a module that helps to avoid collisions between identifiers.
Unit – V
Classes in Python
class computer:
def config(self):
print("i5, 12 gb Ram, 1 Tb")
class computer:
def __init__(self):
print("KKR")
def config(self):
print("i5, 12 gb Ram, 1 Tb")
class computer:
def __init__(self,cpu,ram):
[Link]=cpu
[Link]=ram
def config(self):
print("config is ", [Link],[Link])
class Dog:
def __init__(self, name, breed):
[Link] = name
[Link] = breed
def bark(self):
print("Dog name & breed is ", [Link],[Link])
class Dog:
def __init__(self):
[Link] = "Buddy Golden"
[Link] = "Max"
class Dog:
def __init__(self):
[Link] = "Buddy Golden"
[Link] = "Max"
class Dog:
def __init__(self):
[Link] = "Buddy Golden"
[Link] = "Max"
class Dog:
bark="Woof" # Class Variable
def __init__(self):
[Link] = "Buddy Golden" # Instance Variable
[Link] = "Max" # Instance Variable
class Dog:
bark="Woof" # Class Variable
def __init__(self):
[Link] = "Buddy Golden" # Instance Variable
[Link] = "Max" # Instance Variable
1. Instance Methods
class student:
College="AITAM"
def __init__(self, m1,m2,m3):
self.m1 = m1
self.m2 = m2
self.m3 = m3
def avg(self):# Avg is called as insatnce methods because it's working with instance variables
return (self.m1+self.m2+self.m3)/3
s1=student(10,20,10)
s2=student(20,20,30)
print(s1.m1)
print([Link]())
print([Link]())
Output
10
13.333333333333334
23.333333333333332
2. Class Methods
@classmethod #In Python, decorators are a powerful and flexible way to modify
# or enhance the behavior of functions or methods without changing their source code
def info(cls):
return [Link]
print([Link]())
print([Link]())
print([Link]())
Output
20.0
23.333333333333332
AITAM
3. Statics Methods
class Student:
College = "AITAM" # Class variable
@classmethod
def college_info(cls): # Class method
return [Link]
@staticmethod
def display_info(): # Static method
print("Aitam Student")
Output
20.0
23.333333333333332
AITAM
Aitam Student
Inner Class: Inner classes are classes that are defined inside other classes.
class Human:
def __init__(self):
[Link] = 'John'
[Link] = [Link]()
class Head:
def talk(self):
return 'talking...'
Inheritance: Inheritance it allows us to create a new class by inheriting attributes and methods from an existing
class.
1. Single Inheritance:
class A:
def case1(self):
print("case 1 is working")
def case2(self):
print("case 2 is working")
class B(A):
def case3(self):
print("case 3 is working")
def case4(self):
print("case 4 is working")
Output
case 1 is working
case 2 is working
case 1 is working
case 2 is working
case 3 is working
2. Multiple Inheritances:
class A:
def case1(self):
print("case 1 is working")
def case2(self):
print("case 2 is working")
class B:
def case3(self):
print("case 3 is working")
def case4(self):
print("case 4 is working")
class C(A,B):
def case5(self):
print("case 5 is working")
def case6(self):
print("case 6 is working")
Output
case 1 is working
case 2 is working
case 3 is working
case 4 is working
case 5 is working
case 3 is working
case 2 is working
3. Multilevel Inheritance:
class A:
def case1(self):
print("case 1 is working")
def case2(self):
print("case 2 is working")
class B(A):
def case3(self):
print("case 3 is working")
def case4(self):
print("case 4 is working")
class C(B):
def case5(self):
print("case 5 is working")
def case6(self):
print("case 6 is working")
Output
case 1 is working
case 2 is working
case 1 is working
case 3 is working
case 5 is working
case 3 is working
case 2 is working
4. Hierarchal Inheritance:
class A:
def case1(self):
print("case 1 is working")
def case2(self):
print("case 2 is working")
class B(A):
def case3(self):
print("case 3 is working")
def case4(self):
print("case 4 is working")
class C(A):
def case5(self):
print("case 5 is working")
def case6(self):
print("case 6 is working")
class D(A):
def case7(self):
print("case 7 is working")
def case8(self):
print("case 8 is working")
Output
case 1 is working
case 2 is working
case 1 is working
case 3 is working
case 5 is working
case 2 is working
case 7 is working
case 2 is working
5. Hybrid Inheritance:
class A:
def case1(self):
print("case 1 is working")
def case2(self):
print("case 2 is working")
class B(A):
def case3(self):
print("case 3 is working")
def case4(self):
print("case 4 is working")
class C(A):
def case5(self):
print("case 5 is working")
def case6(self):
print("case 6 is working")
class D(A):
def case7(self):
print("case 7 is working")
def case8(self):
print("case 8 is working")
class E(B,D):
def case9(self):
print("case 9 is working")
def case10(self):
print("case 10 is working")
# Create instances of the classes
s1 = A()
s2 = B()
s3 = C()
s4= D()
s5= E()
Output
case 1 is working
case 2 is working
case 1 is working
case 3 is working
case 5 is working
case 2 is working
case 7 is working
case 2 is working
case 9 is working
case 2 is working
case 3 is working
case 7 is working
class A:
def __init__(self):
print("I am init from A")
def case1(self):
print("case 1 is working")
def case2(self):
print("case 2 is working")
class B(A):
def __init__(self):
super().__init__()
print("I am init from B")
def case3(self):
print("case 3 is working")
def case4(self):
print("case 4 is working")
Output
I am init from A
I am init from B
Polymorphism:
We know that the + operator is used extensively in Python programs. But, it does not have a single usage.
For integer data types, + operator is used to perform arithmetic addition operation.
num1 = 1
num2 = 2
print(num1+num2)----------------3
str1 = "Python"
str2 = "Programming"
print(str1+" "+str2)-------------- Python Programming
There are some functions in Python which are compatible to run with multiple data types.
One such function is the len() function. It can run with many data types in Python. Let's look at some example
use cases of the function.
print(len("Programiz"))------------------------------------------------9
print(len(["Python", "Java", "C"]))-----------------------------------3
print(len({"Name": "Luke", "Address": "Nepal"}))----------------2
Here, we can see that many data types such as string, list, tuple, set, and dictionary can work with
the len() function. However, we can see that it returns specific information about specific data types.
class Animal:
def speak(self):
pass
class Dog(Animal):
def speak(self):
return "Woof!"
class Cat(Animal):
def speak(self):
return "Meow!"
def animal_sound(animal):
return [Link]()
dog = Dog()
cat = Cat()
Polymorphism is the ability of different classes to be treated as objects of a common super class. In this case,
both Dog and Cat are subclasses of Animal. They each override the speak() method defined in the Animal class
with their own implementation. When you call the animal_sound() function with instances of Dog and Cat,
polymorphism allows the correct speak() method associated with each specific subclass to be called, producing
the appropriate sound for each animal.
So, the code exhibits polymorphism because objects of different classes (Dog and Cat) are treated as objects of
their common superclass (Animal) and can be operated on in a uniform manner (animal_sound() function), yet
the specific behavior associated with each subclass is executed.
Overriding occurs when two methods have the same method name and parameters. One of the methods is in
the parent class, and the other is in the child class. Overriding allows a child class to provide the specific
implementation of a method that is already present in its parent class.
Overloading occurs when two or more methods in one class have the same method name but different
parameters. Python does not support method overloading .
Overriding
class A:
def case1(self):
print('case 1 is working')
def case2(self):
print('case 2 is working')
class B(A):
# Modified function that is
# already exist in class A
def case1(self):
print('Modified case 1 of class A by class B')
def case3(self):
print('feature_3 of class B')
# Create instance
s1 = B()
# Call the override function
s1.case1()
Output
Modified case 1 of class A by class B
Encapsulation: Encapsulation is used to restrict access of data members and functions in a class.
Now when we are talking about access, 3 kinds of access specifiers can be used while performing Encapsulation
in Python. They are as follows :
1. Public Members
2. Private Members
3. Protected Members
As the name suggests, the public modifier allows variables and functions to be accessible from anywhere within
the class and from any part of the program. All member variables have the access modifier as public by default.
def Age(self):
print("name:",[Link],"age:",[Link],)
Evidently, from the above code, you can make out that we declared two variables and two methods of the class
pub_mod. We were able to access the variables and methods wherever we wanted with ease as the access
modifier for them was public, which means they should be accessible everywhere.
The private access modifier allows member methods and variables to be accessed only within the class. To
specify a private access modifier for a member, we make use of the double underscore __.
# illustrating private members & private access modifier
class Rectangle:
__length = 0 #private variable
__breadth = 0#private variable
def __init__(self):
self.__length = 5
self.__breadth = 3
#printing values of the private variable within the class
print(self.__length)
print(self.__breadth)
Output
5
3
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[7], line 14
12 rect = Rectangle() #object created
13 #printing values of the private variable outside the class
---> 14 print([Link])
15 print([Link])
We can see that we have received an Attribute Error in the output. Well, your thoughts should wander towards
the private access modifier! Since len is a private member and we have tried to access it outside the class that is
why we received the above error.
What sets protected members apart from private members is that they allow the members to be accessed within
the class and allow them to be accessed by the sub-classes involved. In Python, we demonstrate a protected
member by prefixing with an underscore _ before its name.
As we know, if the members have a protected access specifier, it can also be referenced then within the class
and the subsequent sub-clas
Output
Jason
35
Developer
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
Cell In[8], line 15
13 obj = pro_mod()
14 # direct access of protected member
---> 15 print("Name:",[Link])
16 print("Age:",[Link])
it is quite clear from the output that the class pro_mod was successfully able to inherit the variables from the
class details and print them to the console, although they were protected variables. And when we tried to refer
to them outside of their parent class and the sub-class, we got an Attribute Error for the same.
Regular Expressions
Regular Expressions(Reg Ex): A RegEx, or Regular Expression, is a sequence of characters that forms a
search pattern.
RegEx can be used to check if a string contains the specified search pattern.
RegEx Module
Python has a built-in package called re, which can be used to work with Regular Expressions.
RegEx in Python
When we have imported the re module, we can start using regular expressions:
Example
Search the string to see if it starts with "The" and ends with "Spain":
Import re
#Check if the string starts with "The" and ends with "Spain":
if x:
print("YES! We have a match!")
else:
print("No match")
RegEx Functions:
The re module offers a set of functions that allows us to search a string for a match:
Function Description
split Returns a list where the string has been split at each match
\ Signals a special sequence (can also be used to escape special characters) "\d"
| Either or "falls|stays"
Special Sequences:
A special sequence is a \ followed by one of the characters in the list below, and has a special meaning:
Character Description Example
\A Returns a match if the specified characters are at the beginning of the string "\AThe"
\b Returns a match where the specified characters are at the beginning or at the end of a r"\bain"
word
(the "r" in the beginning is making sure that the string is being treated as a "raw r"ain\b"
string")
\B Returns a match where the specified characters are present, but NOT at the beginning r"\Bain"
(or at the end) of a word
(the "r" in the beginning is making sure that the string is being treated as a "raw r"ain\B"
string")
\d Returns a match where the string contains digits (numbers from 0-9) "\d"
\D Returns a match where the string DOES NOT contain digits "\D"
\s Returns a match where the string contains a white space character "\s"
\S Returns a match where the string DOES NOT contain a white space character "\S"
\w Returns a match where the string contains any word characters (characters from a to "\w"
Z, digits from 0-9, and the underscore _ character)
\W Returns a match where the string DOES NOT contain any word characters "\W"
\Z Returns a match if the specified characters are at the end of the string "Spain\Z"
Sets:
A set is a set of characters inside a pair of square brackets [] with a special meaning:
Set Description
[arn] Returns a match where one of the specified characters (a, r, or n) is present
[a-n] Returns a match for any lower case character, alphabetically between a and n
[0123] Returns a match where any of the specified digits (0, 1, 2, or 3) are present
[a-zA-Z] Returns a match for any character alphabetically between a and z, lower case OR upper case
[+] In sets, +, *, ., |, (), $,{} has no special meaning, so [+] means: return a match for any + character in
the string
Example
Print a list of all matches:
import re
txt = "The rain in Spain"
x = [Link]("ai", txt)
print(x)------------------------------------------------- ['ai', 'ai']
The list contains the matches in the order they are found.
If no matches are found, an empty list is returned:
Example
Return an empty list if no match was found:
import re
txt = "The rain in Spain"
x = [Link]("Portugal", txt)
print(x) )------------------------------------------------- [ ]
Example
Search for the first white-space character in the string:
import re
txt = "The rain in Spain"
x = [Link]("\s", txt)
print("The first white-space character is located in position:", [Link]())-------------The first white-space
character is located in position: 3
import re
txt = "The rain in Spain"
x = [Link]("Portugal", txt)
print(x)-------------------------------------------None
Example
Split at each white-space character:
import re
txt = "The rain in Spain"
x = [Link]("\s", txt)
print(x)---------------------------- ['The', 'rain', 'in', 'Spain']
import re
txt = "The rain in Spain"
x = [Link]("\s", txt, 1)
print(x)----------------------------- ['The', 'rain in Spain']
The sub() Function:
The sub() function replaces the matches with the text of we choice:
Example
Replace every white-space character with the number 9:
import re
import re
txt = "The rain in Spain"
x = [Link]("\s", "9", txt, 2)
print(x)-------------------------------- The9rain9in Spain
Match Object:
A Match Object is an object containing information about the search and the result.
Note: If there is no match, the value None will be returned, instead of the Match Object.
Example
Do a search that will return a Match Object:
import re
txt = "The rain in Spain"
x = [Link]("ai", txt)
print(x) #this will print an object--------------------- <[Link] object; span=(5, 7), match='ai'>
The Match object has properties and methods used to retrieve information about the search, and the result:
.span() returns a tuple containing the start-, and end positions of the match.
.string returns the string passed into the function
.group() returns the part of the string where there was a match
Example
Print the position (start- and end-position) of the first match occurrence.
The regular expression looks for any words that starts with an upper case "S":
import re
txt = "The rain in Spain"
x = [Link](r"\bS\w+", txt)
print([Link]())------------------------------------(12, 17)
Example
Print the string passed into the function:
import re
txt = "The rain in Spain"
x = [Link](r"\bS\w+", txt)
print([Link])----------------------------------- The rain in Spain
Example
Print the part of the string where there was a match.
The regular expression looks for any words that starts with an upper case "S":
import re
txt = "The rain in Spain"
x = [Link](r"\bS\w+", txt)
print([Link]())------------------------------------Spain
Note: If there is no match, the value None will be returned, instead of the Match Object.