UNIT 1 Python
UNIT 1 Python
Introduction:
Python is a high-level, interpreted programming language known for its readability and versatility. Its
history can be traced back to the late 1980s when Guido van Rossum, a Dutch programmer, began
working on it as a hobby project during the Christmas holidays at the Centrum Wiskunde &
Informatica (CWI) in the Netherlands.
Features of Python
Python Applications
Python has been at the forefront of Machine learning, Data Science, and Artificial Intelligence innovation. Further,
Python applications offers provides ease in building a plethora of apps, web development processes, and a lot more. In
this blog, we will discuss the top 10 Python applications in the real world in a detailed manner. So let's get started:
1. Web Development
It is one of the most astonishing applications of Python. This is because Python comes up with a wide range of
frameworks like Django, Flask, Bottle, and a lot more that provide ease to developers. Furthermore, Python has inbuilt
libraries and tools which make the web development process completely effortless.
2. Machine Learning and Artificial Intelligence
Machine Learning and Artificial Intelligence are the hottest subjects right now. Python along with its inbuilt libraries and
tools facilitate the development of AI and ML algorithms. Further, it offers simple, concise, and readable code which
makes it easier for developers to write complex algorithms and provide a versatile flow. Some of the inbuilt libraries and
tools that enhance AI and ML processes are Numpy, Keras ,SciPy ,Seaborn
3. Data Science
Data science involves data collection, data sorting, data analysis, and data visualization. Python provides amazing
functionality to tackle statistics and complex mathematical calculations. The presence of in-built libraries provides
convenience to data science professionals. Some of the popular libraries that provide ease in the data science process
are TensorFlow, Pandas, and Socket Learning.
4. Game Development
With the rapidly growing gaming industry, Python has proved to be an exceptional option for game development. Popular
games like Pirates of the Caribbean, Bridge Commander, and Battlefield 2 use Python programming for a wide range of
functionalities and add-ons. The presence of popular 2D and 3D gaming libraries like pygame, panda3D, and
Cocos2D makes the game development process completely effortless.
5. Audio and Visual Applications
Audio and video applications are undoubtedly the most amazing feature of Python. Python is equipped with a lot of tools
and libraries to accomplish your task flawlessly. Applications that are coded in Python include popular ones like Netflix,
Spotify, and YouTube. This can be handled by libraries like
Dejavu
Pyo
Mingus
SciPy
OpenCV
6. Software Development
Python is just the perfect option for software development. Popular applications like Google, Netflix, and Reddit all use
Python. This language offers amazing features like:
Platform independence
Inbuilt libraries and frameworks to provide ease of development.
Enhanced code reusability and readability
High compatibility
Apart from these Python offers enhanced features to work with rapidly growing technologies like Machine learning and
Artificial intelligence. All these embedded features make it a popular choice for software development.
7. Desktop GUI
Python is an interactive programming language that helps developers to create GUIs easily and efficiently. It has a huge
list of inbuilt tools for Python usage are PyQT, kivy, wxWidgets, and many other libraries like them to build a fully
functional GUI in an extremely secure and efficient manner.
Installation of Python:
Python source code is available under the GNU General Public License (GPL). Python interpreter is free, and downloads
are available for all major platforms (Windows, Mac OS, and Linux ) in the form of source and binary. You can download it
from the Python Website: [Link].
On Windows machines, a Python installation is usually placed in C:\Users\UserName\AppData\Local\Programs\
Python\Python(Version), although you can change this while running the installer.
To install Python on a Windows machine, follow these steps:
Download Python for Windows.
Run the Python installer.
Here, you will see the Python wizard, which is very easy to use. Just accept the default recommended settings
and click on the Next button, wait until the installation is complete, and you are done.
EXECUTION MODES:
There are two ways to use the python interpreter:
a) Interactive mode
b) Script mode
Script Mode:
In the script mode, we can write a Python program in a file, save it and then use the interpreter to execute it. Python
scripts are saved as files where file name has extension ".py". By default, the Python scripts are saved in the Python
installation folder.
Python Keywords
Python keywords are reserved words that have predefined meanings and purposes in the Python programming language.
These cannot be used as identifiers (e.g., variable names, function names, etc.) because they are part of the language's
syntax and structure.
Here’s a list of commonly used Python keywords (as of Python 3.10+):
False await else import pass
None break except in raise
True class finally is return
and continue for lambda try
as def from nonlocal while
assert del global not with
async elif if or yield
Key Points About Python Keywords
1. Case-Sensitive: Keywords are case-sensitive. For example, True is valid, but true is not.
2. Cannot Be Used as Identifiers: You cannot name variables, functions, or classes using these keywords.
3. Soft Keywords: Python also has "soft keywords" like match and case (introduced in Python 3.10) that act as
keywords in specific contexts but can be used as identifiers elsewhere.
If you're learning Python, understanding these keywords is essential for writing syntactically correct code!
IDENTIFIERS:
In programming languages, identifiers are names used to identify a variable, function, or other entities in a program. The
rules for naming an identifier in Python are as follows:
The name should begin with an uppercase or a lowercase alphabet or an underscore sign (). This may be followed by any
combination of characters a-z, A-Z, 0-9 or underscore (). Thus, an identifier cannot start with a digit.
For example, to find the average of marks obtained by a student in three subjects, we can choose the identifiers as
marksl, marks2, marks3 and avg rather than a, b, c, ог А, В, С.
Avg =(marks1+ marks2+ marks3)/3
Similarly, to calculate the area of a rectangle, we can use identifier names, such as area, length, breadth instead of single
alphabets as identifiers for clarity and more readability.
Area=length+breadth
VARIABLES:
variables are containers that store data in memory. A variable in a program is uniquely identified by a name. Variable in
python refers to an object – an item or element that is stored in the memory. Value of a variable can be string, numeric or
any combination of alphanumeric characters. In python we can use an assignment statement to create new variables and
assign specific values to them.
Ex :
gender=’M’
message=”Keep smiling”
price=687.9
Python Comments
Comments in Python are the lines in the code that are ignored by the interpreter during the execution of the program.
In simple comments are non executable statements.
Comments enhance the readability of the code.
Comment can be used to identify functionality or structure the code-base.
Comment can help understanding unusual or tricky scenarios handled by the code to prevent accidental removal
or changes.
Comments can be used to prevent executing any specific part of your code, while making changes or testing.
# I am single line comment
Multi-Line Comments
Python does not have a dedicated syntax for multi-line comments. However, you can achieve this by using
multiple # symbols.
Using Multiple # Symbols:
# This is a multi-line comment
# explaining the following block of code
x = 10
y = 20
print(x + y)
Docstrings for Documentation
For documenting functions, classes, or modules, Python uses docstrings, which are enclosed in triple quotes (""" or ''').
These are accessible via the __doc__ attribute.
Example of a Docstring:
def greet(name):
"""This function greets the person whose name is passed as an argument."""
print(f"Hello, {name}!")
greet("Alice")
print(greet.__doc__)
EVERYTHING IS AN OBJECT
Python treats every value or data item whether numeric, string, or other type as an object in the sense that it can be
assigned to some variable or can be passed to a function as an argument.
Every object in Python is assigned a unique identity (ID) which remains the same for the lifetime of that object. This ID is
akin to the memory address of the object. The function id () returns the identity of an object
Example:
>>> Num1=20
>>> print(id(num1))
143356776 #identity of num1
>>> num2=30-10
>>> print(id(num2))
143328375 #identity of num2
DATA TYPES
Every value belongs to a specific data type in Python. Data type identifies the type of data values a variable can hold and
the operations that can be performed on that data. Figure enlists the data types available in Python.
1. Number
Number data type stores numerical values only. It is further classified into three different types: int, float and
complex.
Type Description Examples
Int Integer numbers 12 , -45, 0, 125
Float Real or floating point numbers -2.67, 4.0, 37.8
complex Complex numbers 4+2j, 2-6j
Boolean data type (bool) is a subtype of integer. It is a unique data type, consisting of two constants, True and
False. Boolean True value is non-zero, non-null and non-empty. Boolean False is the value zero.
Let us now try to execute few statements in interactive mode to determine the data type of the variable using built-
in function type ().
>>> num1 = 10
>>> type (numl)
<class 'int'>
Variables of simple data types like integers, float, boolean, etc., hold single values. But such variables are not
useful to hold a long list of information, for example, names of the months in a year, names of students in a
class, names and numbers in a phone book or the list of artefacts in a museum. For this, Python provides data
types like tuples, lists, dictionaries and sets.
2 Sequence
A Python sequence is an ordered collection of items, where each item is indexed by an integer. The three types of
sequence data types available in Python are Strings, Lists and Tuples. We will learn about each of them in detail in later
chapters. A brief introduction to these data types is as follows:
(A) String
String is a group of characters. These characters may be alphabets, digits or special characters including spaces.
String values are enclosed either in single quotation marks (e.g., 'Hello') or in double quotation marks (e.g.,
"Hello"). The quotes are not a part of the string, they are used to mark the beginning and end of the string for
the interpreter. For example,
>>>>> str1 = 'Hello Friend'
(B) List
List is a sequence of items separated by commas and the items are enclosed in square brackets [].
Example 5.4
#To create a list
>>> list = [5, 3.4, "New Delhi", "20C", 45]
#print the elements of the list
>>> print (list)
[5, 3.4, 'New Delhi', '200', 45]
(C) Tuple
Tuple is a sequence of items separated by commas and items are enclosed in parenthesis (). This is unlike list, where
values are enclosed in brackets []. Once created, we cannot change the tuple.
Example 5.5
#create a tuple tuple1
>>>tuplel1(10, 20, "Apple", 3.4, 'a')
#print the elements of the tuple tuple1
>>> print (tuple1)
(10, 20, "Apple", 3.4, 'a')
3 Set
Set is an unordered collection of items separated by commas and the items are enclosed in curly brackets { ). A set is
similar to list, except that it cannot have duplicate entries. Once created, elements of a set cannot be changed.
Example
Create a set
>>> set1 (10,20,3.14,"New Delhi")
>>> print (type (set1))
<class 'set1'>
>>>print(set1)
(10, 20, 3.14, "New Delhi")
#duplicate elements are not included in set
>>>set2={1,2,1,3}
>>> print(set2)
{1,2,3}
4 None
None is a special data type with a single value. It is used to signify the absence of value in a situation. None supports no
special operations, and it is neither same as False nor 0 (zero).
Example
> >> myVar= None
>>> print (type (myVar))
<class 'NoneType'>
>>> print (myVar)
None
5 Mapping
Mapping is an unordered data type in Python. Currently, there is only one standard mapping data type in Python called
dictionary.
(A) Dictionary
Dictionary in Python holds data items in key-value pairs. Items in a dictionary are enclosed in curly brackets {1.
Dictionaries permit faster access to data. Every key is separated from its value using a colon (:) sign. The key : value pairs
of a dictionary can be accessed using the key. The keys are usually strings and their values can be any data type. In order
to access any value in the dictionary, we have to specify its key in square brackets
Example
#create a dictionary
o/p:
[1, 2, 3, 4]
[1, 5, 2, 3, 4]
[1, 5, 3, 4]
[5, 3, 4]
1
INDENTATION:
In most programming languages, the statements within a block are put inside curly brackets. However, python uses
indentation for block as well as for nested block structures. Leading whitespace(spaces and tabs) at the beginning of a
statement is called indentation.
In python the same level of indentation associates statements in to a single block of code. The interpreter checks
indentation levels very strictly and throws up syntax error if indentation not correct
For example:
if 10 > 5:
print("This is true!")
print("Inside the block")
print("Outside the block")
Here, the first two print statements are part of the if block due to their indentation, while the last print is outside the
block.
Python Operators
In Python programming, Operators in general are used to perform operations on values and variables. These are standard
symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators.
OPERATORS: These are the special symbols. Eg- + , * , /, etc.
OPERAND: It is the value on which the operator is applied.
Arithmetic Operator:
These are the basic mathematical operators. They perform basic functions like addition, subtraction, etc in any code. They
are considered the building blocks of the code.
Operator Meaning Example
+ Addition a+b
– subtraction a-b
* multiplication a*b
/ division a/b
% modulus a%b
** Exponential a**b
EX:
a = 15
b=4
print("Addition:", a + b)
print("Subtraction:", a - b)
print("Multiplication:", a * b)
print("Division:", a / b)
print("Floor Division:", a // b)
print("Modulus:", a % b)
print("Exponentiation:", a ** b)
Relational operators:
These operators are for comparing any two significant values in a python code. They take two values in them and then
compare them with each other. And accordingly, they display the result.
Operator Meaning Example
Logical Operator:
These operators work on logic, i.e., they check the conditions and give a straight logical output to it. A logical operator is a
must use in a one-way code, where the coder has no idea of what the user is going to give as input.
Operator Meaning Example
Example:
a = True
b = False
print(a and b)
print(a or b)
print(not a)
Bitwise Operator:
They act on alphanumeric operators in the form of bits. They only give raw output in the form of 0 and 1. They are easily
interpreted by the code as they work on the language of on and off, i.e., 0 and 1 only.
Operator Meaning Example
Example:
a = 10
b=4
print(a & b) #0
print(a | b) #14
print(~a) #-11
print(a ^ b) #14
print(a >> 2) #2
print(a << 2) #40
Assignment Operator:
They are the mathematical operators, which perform two functions at the same time. They easily interpret the difficult
codes by breaking them in small lines.
Operator Example Equivalent to
= X=1 X=1
+= X += 1 X=x+1
-= x -= 1 x=x–1
*= x *= 1 x=x*1
/= x /= 1 x=x/1
%= x %= 1 x=x%1
//= x /= 1 x=x/1
**= x **= 1 x = x ** 1
|= x |= 1 x=x|1
^= x ^= 1 x=x^1
EXPRESSIONS
An expression is defined as a combination of constants, variables, and operators. An expression always evaluates to a
value. A value or a standalone variable is also considered as an expression but a standalone operator is not an expression.
Some examples of valid expressions are given below.
(i) 100
(ii) num
(iii) num-20.4
(iv) 3.0+ 3.14
(ν) 23/3 -5*7 (14-2)
(vi) "Global" + "Citizen"
Precedence of Operators
In Python, operator precedence determines the order in which operations are performed in an expression. Operators
with higher precedence are evaluated before those with lower precedence. If operators have the same precedence, their
associativity (left-to-right or right-to-left) decides the evaluation order.
Here’s a summary of Python's operator precedence (from highest to lowest):
1. Parentheses
(): Used to override precedence or group expressions.
2. Exponentiation
**: Right-to-left associativity.
3. Unary Operators
+, -, ~: Unary plus, minus, and bitwise NOT.
4. Multiplicative Operators
*, /, //, %: Multiplication, division, floor division, and modulus.
5. Additive Operators
+, -: Addition and subtraction.
7. Bitwise AND
&
8. Bitwise XOR
^
9. Bitwise OR
|
13. Logical OR
or
Key Notes:
Associativity: Most operators are left-to-right associative, except for exponentiation (**) and assignment
operators, which are right-to-left associative.
Parentheses: Always use parentheses to make expressions clearer and avoid ambiguity.
For example:
Python
result = 2 + 3 * 4 # Multiplication (*) has higher precedence than addition (+)
print(result) # Output: 14
Statement
In python, a statement is a unit of code that the python interpreter can execute
Example:
X=4 #assignment statement
cube=x**3 #assignment statement
print(x,cube) #print statement
Built-in functions
Input and Output in Python
Understanding input and output operations is fundamental to Python programming. With the print() function, we can
display output in various formats, while the input() function enables interaction with users by gathering input during
program execution.
Taking input in Python
Python's input() function is used to take user input. By default, it returns the user input in form of a string.
Example:
name = input("Enter your name: ")
print("Hello,", name, " Welcome")
The code prompts the user to input their name, stores it in the variable "name" and then prints a greeting message
addressing the user by their entered name.
TYPE CONVERSION:
Consider the following program
num1= input ("Enter a number and I'll double it: ")
num1 = num1*2
print (num1)
The program was expected to display double the value of the number received and store in variable num1. So if a user
enters 2 and expects the program to display 4 as the output, the program displays the following result:
Enter a number and I'll double it: 2
22
This is because the value returned by the input function is a string ("2") by default. As a result, in statement
num1=num1*2, num1 has string value and acts as repetition operator which results in output as "22". To get 4 as output,
we need to convert the data type of the value entered by the user to integer. Thus,
we modify the program as follows:
1. Explicit Conversion
Explicit conversion, also called type casting happens when data type conversion takes place because the programmer
forced it in the program. The general form of an explicit data type conversion is:
(new_data_type) (expression)
With explicit type conversion, there is a risk of loss of information since we are forcing an expression to be of a specific
type. For example, converting a floating value of x = 20.67 into an integer type, i.e., int(x) will discard the fractional part
67. Following are some of the functions in Python that are used for explicitly converting an expression or a variable to a
different type.
Output:
30
<class 'int'> >
30.0
<class 'float'>>
Output:
30.8
<class 'float'>
30
<class 'int'>
On execution, above program gives an error as shown convert an integer value to string implicitly. It may in Figure 5.11.
informing that the interpreter cannot appear quite intuitive that the program should convert the integer value to a string
depending upon the usage. However, the interpreter may not decide on its own when to convert as there is a risk of loss
of information. Python provides the mechanism of the explicit type conversion so that one can clearly state the desired
outcome. Program 5-8 works perfectly using explicit type casting:
Output:
The total in Rs.70
Similarly, type casting is needed to convert float to string. In Python, one can convert string to integer or float values
whenever required.
Program to show explicit type conversion.
icecream ='25'
brownie ='45'
price=icecream + brownie
print("Total Price Rs." + price)
#Explicit type conversion string to integer
price =int(icecream)+ int(brownie)
print("Total Price:"+ str(price))
Output:
Total Price Rs.2545
Total Price Rs.70.
[Link] Conversion
Implicit conversion, also known as coercion, happens when data type conversion is done automatically by Python and is
not instructed by the programmer.
Output:
30.0
<class 'float'>
In the above example, an integer value stored in variable num1 is added to a float value stored in variable num2, and the
result was automatically converted to a float value stored in variable sum1 without explicitly telling the interpreter. This is
an example of implicit data conversion. One may wonder why was the float value not converted to an integer instead?
This is due to type promotion that allows performing operations (whenever possible) by converting data into a wider-
sized data type without any loss of information.
Built-in functions
Built-in functions are the ready-made functions in python that are frequently used in programs. Let us inspect the
following Python program:
BUILT-IN FUNCTIONS
This gives us access to all the functions in the module(s). To call a function of a module, the function name should be
preceded with the name of the module with a dot(.) as a separator.
Note:
import statement can be written anywhere in the program
Module must be imported only once
In order to get a list of modules available in Python, we can use the following statement:
>>> help("module")
To view the content of a module say math, type the following: .
>>> help ("math")
From Statement:
Instead of loading all the functions into memory by importing a module, from statement can be used to access only the
required functions from a module. It loads only the specified function(s) instead of all the functions in a module.
Its syntax is
>>> from modulename import functionname [, functionname,...]
To use the function when imported using "from statement" we do not need to precede it with the module name. Rather
we can directly call the function as shown in the following examples:
Output:
0.9796352504608387
Example
>>> from math import ceil, sqrt
>>> value = ceil(624.7)
>>>> sqrt (value)
Output:
25.0
1. Selection
A decision involves selecting from one of the two or more possible options> In programming, this concept of
decision making or selection is implemented with the help of if…..else statement
Types of selection :
a. If statement
b. If..else statement
c. If..elif statement
a. If statement: if statement is the most simple decision-making statement. If the condition evaluates to True, the
block of code inside the if statement is executed.
The syntax:
If condition:
Statement(s)
Example:
i = 10
# Checking if i is greater than 15
if i > 15:
print("10 is less than 15")
print("I am Not in if")
b. If…else Statement
if...else statement is a control statement that helps in decision-making based on specific conditions. When the if
condition is False. If the condition in the if statement is not true, the else block will be executed.
Syntax:
if condition:
Statement(s)
else:
Statement(s)
Example:
i = 20
# Checking if i is greater than 0
if i > 0:
print("i is positive")
else:
print("i is 0 or Negative")
c. If…elif Statement
The elif condition is used to include multiple conditional expressions after the if condition
if-elif-else statement in Python is used for multi-way decision-making. This allows us to check multiple conditions
sequentially and execute a specific block of code when a condition is True. If none of the conditions are true,
the else block is executed.
Syntax:
if condition:
statement(s)
elif condition:
statement(s)
elif condition:
statement(s)
else:
statement(s)
Example:
i = 25
# Checking if i is equal to 10
if i == 10:
print("i is 10")
# Checking if i is equal to 15
elif i == 15:
print("i is 15")
# Checking if i is equal to 20
elif i == 20:
print("i is 20")
# If none of the above conditions are true
else:
print("i is not present")
2. Repetition
Repetition is also called iteration. Repetition of a set of statements in a program is made possible using looping
constructs.
Looping constructs provide the facility to execute a set of statements in a program repetitively, based on a
condition. The statements in a loop are executed again and again as long as particular logical condition remains
true.
This condition is checked based on the value of a variable called the loop’s control variable.
There are two looping constructs in python for and while.
OUTPUT:
P
Y
T
H
O
N
OUTPUT:
10
20
30
40
50
s = "Geeks"
for i in s:
print(i)
d = dict({'x':123, 'y':354})
for i in d:
print("%s %d" % (i, d[i]))
set1 = {1, 2, 3, 4, 5, 6}
for i in set1:
print(i)
Syntax:
range(start,stop,step)
The Python range() function returns a sequence of numbers, in a given range. The most common use of it is to
iterate sequences on a sequence of numbers using Python loops.
It is used to create a list containing a sequence of integers from the given start value upto stop value(excluding
stop value), with a difference of the given step value.
The start and step parameters are optional. If start value is not specified, by default the list starts from 0. If step
is also not specified, by default the value increases by 1 in each iteration. All parameters of range() function must
be integers. The step parameter can be a positive or a negative integer excluding zero
In this example, we are printing the number from 0 to 9 with the jump of 2. We are using the range function in which we
are passing the starting and stopping points with the jump of the iterator.
Output:
TypeError: 'float' object cannot be interpreted as an integer
ele = range(10)[-1]
print("\nLast element:", ele)
ele = range(10)[4]
print("\nFifth element:", ele)
Output :
First element: 0
Last element: 9
Fifth element: 4
condition: This is a boolean expression. If it evaluates to True, the code inside the loop will execute.
statement(s): These are the statements that will be executed during each iteration of the loop.
In this example, the condition for while will be True as long as the counter variable (count) is less than 3.
count = 0
while count < 3:
count = count + 1
print("Hello Geek")
Output
Hello Geek
Hello Geek
Hello Geek
Output
0
1
2
0
1
2
Find the sum of all positive numbers entered by the user. As soon as the user enteres a negative number, stop
taking in any further input from the user and display the sum
sum1=0
print(“Enter numbers to find their sum, negative number ends the loop:”)
while True: #an infinite loop that keeps running until it is explicitly broken
entry=int(input())
if (entry<0):
break
sum1+=entry
print(“sum=”,sum1)
Output:
Enter numbers to find their sum, negative number ends the loop:
3
4
6
7
-3
Sum = 20
Continue Statement in Python
Python Continue statement is a loop control statement that forces to execute the next iteration of the loop while
skipping the rest of the code inside the loop for the current iteration only, i.e. when the continue statement is
executed in the loop, the code inside the loop following the continue statement will be skipped for the current
iteration and the next iteration of the loop will begin.
Example:
for i in range(5):
if i == 3:
continue # Skip the rest of the code for i = 3
print(i)
Output
0
1
2
4
Exit() in python
In Python, the exit() function can be used to terminate the entire program, including exiting a for loop. However,
this is not the typical way to exit a loop. If you only want to exit the loop and continue with the rest of the
program, you should use the break statement instead.
Below is an example demonstrating the use of exit() in a for loop, along with a comparison to break:
exit():
Terminates the entire program.
Typically used in scripts or when you want to stop execution completely.
Can be replaced with [Link]() for better control (e.g., returning an exit code).