0% found this document useful (0 votes)
2 views25 pages

UNIT 1 Python

Python is a high-level, interpreted programming language created by Guido van Rossum in the late 1980s, known for its readability and versatility. Key milestones include the release of Python 1.0 in 1994, Python 2.0 in 2000, and Python 3.0 in 2008, with applications in web development, machine learning, data science, and more. The document also covers Python's features, installation, execution modes, keywords, identifiers, variables, comments, data types, and its object-oriented nature.

Uploaded by

soumya says
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views25 pages

UNIT 1 Python

Python is a high-level, interpreted programming language created by Guido van Rossum in the late 1980s, known for its readability and versatility. Key milestones include the release of Python 1.0 in 1994, Python 2.0 in 2000, and Python 3.0 in 2008, with applications in web development, machine learning, data science, and more. The document also covers Python's features, installation, execution modes, keywords, identifiers, variables, comments, data types, and its object-oriented nature.

Uploaded by

soumya says
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

UNIT 1:

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.

Key milestones in Python's history include:


1989:
Guido van Rossum begins the implementation of Python as a successor to the ABC language, aiming
for better exception handling and interaction with the Amoeba operating system. The name "Python"
was inspired by the British comedy show "Monty Python's Flying Circus."
1991:
Python 0.9.0 is released, featuring classes, inheritance, exception handling, and core data types.
1994:
Python 1.0 is released, introducing features like lambda, map, filter, and reduce.
2000:
Python 2.0 is released, bringing significant enhancements such as list comprehensions, garbage
collection, and improved Unicode support. The Python Enhancement Proposal (PEP) process is also
introduced to manage and propose new language features.
2008:
Python 3.0 (also known as Python 3000 or Py3k) is released. This version introduced backward-
incompatible changes, primarily to address design flaws and improve consistency, leading to a
lengthy transition period for the community.
2018:
Guido van Rossum steps down from his role as the Benevolent Dictator For Life (BDFL) of Python, a
position he held since the language's inception.
2020:
Python 2 reaches its official end-of-life, with no further support or updates provided. This marked a
significant push for the community to fully transition to Python 3.
Since its inception, Python has grown to become one of the most popular programming languages
globally, widely used in web development, data science, artificial intelligence, machine learning, and
automation due to its extensive libraries, frameworks, and active community.

Features of Python

 Python is a high level language. It is a free and open source language.


 It is an interpreted language, as Python programs are executed by an interpreter.
 Python programs are easy to understand as they have a clearly defined syntax and relatively
simple structure.
 Python is case-sensitive. For example, NUMBER and number are not same in Python.
 Python is portable and platform independent, means it can run on various operating systems
and hardware platforms.
 Python has a rich library of predefined functions.
 Python is also helpful in web development. Many popular web services and applications are
built using Python.
 Python uses indentation for blocks and nested blocks.

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

Python Command Line Mode:


Python Command Line Mode Python's command line mode, also known as the interactive interpreter or REPL (Read-Eval-
Print Loop), allows you to execute Python code directly in the terminal or command prompt.
To work in interactive mode, we can simply type a python statement on the >>> prompt directly. As soon as we press
enter, the interpreter executes the statement and display the result.
Working in the interactive mode is convenient for testing a single line code for instant execution. But in interactive mode
we cannot save the statements to run them again

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.

It can be of any length. (However, it is preferred to keep it short and meaningful).

It should not be a keyword or reserved word given in Table 5.1.

We cannot use special symbols like !, @, #, $, %, etc., in identifiers.

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

Program to display values of variables


Message=”Keep Smiling”
Print(Message)
userNo=666
print(userNo)

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

>>> num2 -1210


>>> type (num2)
<class 'int'>

>>> varl = True


>>> type (varl)
<class 'bool'>

>>> floatl -1921.9


>>> type (floatl)
<class 'float'>

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'

>>> str2 = "452"


We cannot perform numerical operations on strings, even when the string contains a numeric value, as in str2.

(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

>>> dict1 ('Fruit': 'Apple','Climate': 'Cold', 'Price (kg)’::120)


>>> print (dict1)
{'Fruit': 'Apple', 'Climate': 'Cold','Price (kg)’: 120}
>>> print (dict1['Price (kg)'])
120

Mutable and Immutable Data Types


In Python, Every variable in Python holds an instance of an object. There are two types of objects in Python
i.e. Mutable and Immutable objects. Whenever an object is instantiated, it is assigned a unique object id. The type of the
object is defined at the runtime and it can't be changed afterward. However, its state can be changed if it is a mutable
object.
Mutable and Immutable Objects in Python
Immutable Objects in Python
Variables whose values can be changed after they are created and assigned are called mutable. When an attempt is made
to update the value of an immutable variables, the old variable is destroyed and a new variable is created by the same
name in memory
Immutable data types: Integers, float, Boolean, Complex, Strings, Tuples
Example 1: In this example, we will take a tuple and try to modify its value at a particular index and print it. As a tuple is
an immutable object, it will throw an error when we try to modify it.
tuple1 = (0, 1, 2, 3)
tuple1[0] = 4
print(tuple1)
#TypeError: 'tuple' object does not support item assignment

Mutable Objects in Python


Variables whose values cannot be changed after they are created and assigned are called immutable
Mutable data types: Lists, Sets, Dictionary
Example
my_list = [1, 2, 3]
my_list.append(4)
print(my_list)
my_list.insert(1, 5)
print(my_list)
my_list.remove(2)
print(my_list)
popped_element = my_list.pop(0)
print(my_list)
print(popped_element)

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

// Floor division 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

> Returns True if x is greater than y x>y

< Returns True if x is less than y x<y

== Returns True if both x,y are equal x==y

!= Returns True if x and y not equal x!=y

>= Returns True if x is greater than or equal to y x>=y

<= Returns True if x is less than or equal to the y x<=y


Example:
a=5
b=2
print('a == b :', (a == b)) #Comparison Equal to
print('a != b :', (a != b)) #Comparison Not Equal to
print('a > b :', (a > b)) #Comparison Greater than
print('a < b :', (a < b)) #Comparison Less than
print('a >= b :', (a >= b)) #Comparison Greater than or Equal to
print('a <= b :', (a <= b)) #Comparison Less than or Equal to

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

and Returns True if both the x and y are equal x and y


or Returns True if either of one condition is true x or y

not True if not the whole operator is false not x

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

& Bitwise AND x & y = 0 (0000 0000)

| Bitwise OR x | y = 14 (0000 1110)

~ Bitwise NOT ~x = -11 (1111 0101)

^ Bitwise XOR x ^ y = 14 (0000 1110)

>> Bitwise right shift x >> 2 = 2 (0000 0010)

<< Bitwise left shift x << 2 = 40 (0010 1000)

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

^= x ^= 1 x=x^1

>>= x >>= 1 x = x >> 1


Example:
a = 10
b=a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)

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.

6. Bitwise Shift Operators


 <<, >>: Left and right bitwise shifts.

7. Bitwise AND
 &

8. Bitwise XOR
 ^

9. Bitwise OR
 |

10. Comparison Operators


 ==, !=, >, <, >=, <=, is, is not, in, not in

11. Logical NOT


 not

12. Logical AND


 and

13. Logical OR
 or

14. Assignment Operators


 =, +=, -=, *=, /=, //=, %=, **=, &=, |=, ^=, >>=, <<=

15. Expression Separators


 ,

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

result = (2 + 3) * 4 # Parentheses override precedence


print(result) # Output: 20

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.

Printing Output using print() in Python


At its core, printing output in Python is straightforward, thanks to the print() function. This function allows us to display
text, variables and expressions on the console. Let's begin with the basic usage of the print() function:
In this example, "Hello, World!" is a string literal enclosed within double quotes. When executed, this statement will
output the text to the console.
The print() outputs a complete line and then move to the next line for subsequent output. The syntax for print() is:
Print(value[,…,sep=’ ‘, end=’\n’])
sep: The optional parameter sep is a separator between the output values. We can use a character, integer or a string as a
separator. The default separator is space
end: This is also optional and it allows us to specify any string to be appended after the last value. The default is a new
line.
Example:
print("Hello, World!")

Take Multiple Input in Python


We are taking multiple input from the user in a single line, splitting the values entered by the user into separate variables
for each value using the split() method. Then, it prints the values with corresponding labels, either two or three, based on
the number of inputs provided by the user. The split() method is specifically designed for strings, not integers. However,
you can convert the integer to a string first and then manipulate it as needed.
Example:
x, y = input("Enter two values: ").split()
print("Number of boys: ", x)
print("Number of girls: ", y)

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:

num1 = input("Enter a number and I'll double it: ").


num1=int (num1) #convert string input to
num1= num1* 2 #integer
print(num1)

Now, the program will display the expected output as follows:

Enter a number and I'll double it: 2


4
Let us now understand what is type conversion and how it works. As and when required, we can change in the data type
of a variable in Python from one type to another. Such data type conversion can happen in two ways: either explicitly
(forced) when the programmer specifies for the interpreter to convert a data type to another type; or implicitly, when the
interpreter understands such a need by itself and does the type conversion automatically.

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.

Table :Explicit type conversion functions in Python


Function Description
int(x) Converts x to an integer
float(x) Converts x to a floating-point number
str(x) Converts x to a string representation
chr(x) Converts ASCII value of x to character
ord(x) Returns the character associated with the ASCII code x

Program of explicit type conversion from int to float.


num1 = 10
num2 = 20
num3 num1 + num2
print (num3)
print (type (num3))
num4= float (num1+ num2)
print (num4)
print(type (num4))

Output:
30
<class 'int'> >
30.0
<class 'float'>>

Program of explicit type conversion from float to int.


num1=10.2
num2=20.6
num3 =(num1 + num2)
print(num3)
print (type (num3)
num4=int (num1 + num2)
print(num4)
print (type (num4))

Output:
30.8
<class 'float'>
30
<class 'int'>

Example of type conversion between numbers and strings.


priceIcecream = 25
priceBrownie = 45
totalPrice = priceIcecream + priceBrownie
print("The total is Rs." + totalPrice ) #Typeerror

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:

Program to show explicit type casting.


pricelcecream = 25
priceBrownie = 45
totalPrice =pricelcecream + priceBrownie
print("The total in Rs." + str(totalPrice))

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.

Program to show implicit conversion from int to float.


num1=10 #num1 is integer
num2= 20.0 #num2 is float
sum1= num1+num2
print(sum1)
print (type (sum1))

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.

PYTHON STANDARD LIBRARY:


Python has a very extensive standard library. It is a collection of many built in functions that can be called in the program
as and when required, thus saving programmer's time of creating those commonly used functions everytime.

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:

#Program to calculate square of a number


a=int (input ("Enter a number: ")
b=a*a
print(" The square of ",a, "is", b)
In the above program input(), int() and print() are the built in functions. The set of instruction to be executed for these
built-in functions are already defined in the python interpreter.

BUILT-IN FUNCTIONS

Input or Output Datatype Conversion Mathematical Functions Other functions


input() bool() , chr() abs() len()
Output() dict() , float() divmod() range()
int() , list() max() type()
ord() , set() min()
str() , tuple() pow()
sum()
Module:
Other than the built-in functions, the Python standard library also consists of a number of modules. While is a grouping of
functions. As we know that when a a function is a grouping of instructions, a module and to avoid repetition. For a
complex problem, it may program grows, function is used to simplify the code not be feasible to manage the code in one
single file different levels, called modules. Also, suppose we have Then, the program is divided into different parts under
created some functions in a program and we want to reuse them in another program. In that case, we can save those
functions under a module and reuse them. A module is created as a python (.py) file containing a collection of function
definitions.
To use a module, we need to import the module. Once we import a module, we can directly use all the functions of that
module. The syntax of import statement is as follows:
import modulename1,[modulename2,….]

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.

The syntax is as shown below:


[Link]()

(A) Built-in Modules


Python library has many built-in modules that are really handy to programmers. Let us explore some commonly used
modules and the frequently used functions that are found in those modules:
 Math
 Random
 statistics
EX: import math

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:

>>> from random import random


>>> random () #Function called without the module name

Output:
0.9796352504608387
Example
>>> from math import ceil, sqrt
>>> value = ceil(624.7)
>>>> sqrt (value)

Output:
25.0

PYTHON CONTROL FLOW:


The order of execution of the statements in a program is known as flow of control. The flow of control can be
implemented using control structures. Python supports two types of control structures-----selection and repetition

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.

The ‘For’ Loop


The for statement is used to iterate over a range of values or a sequence. The for loop is executed for each of the
items in the range.
With every iteration of the loop, the control variable checks whether each of the values in the range have been
traversed or not
Syntax :
for <control-variable> in <sequence/items in range>:
<statements inside body of the loop>
Program to print the characters in the string ‘PYTHON’ using for loop
for letter in ‘PYTHON’:
print(letter)

OUTPUT:
P
Y
T
H
O
N

Program to print the numbers in a given sequence using for loop


Count=[10,20,30,40,50]
For num in Count:
print(num)

OUTPUT:
10
20
30
40
50

li = ["geeks", "for", "geeks"]


for i in li:
print(i)

tup = ("geeks", "for", "geeks")


for i in tup:
print(i)

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)

THE Range() FUNCTION:


The range() is a built-in function in Python.

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

Some Important points to remember about the Python range() function


 The range() function only works with integers, i.e. whole numbers.
 All arguments must be integers. Users can not pass a string or float number or any other type in
a start, stop, and step argument of a range().
 All three arguments can be positive or negative.
 The step value must not be zero. If a step is zero, python raises a ValueError exception.
 range() is a type in Python.
 Users can access items in a range() by index, just as users do with a list.

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.

for i in range(0, 10, 2):


print(i, end=" ")
print()
Output:
02468

Incrementing the Range using a Positive Step


If a user wants to increment, then the user needs steps to be a positive number.
# incremented by 4
for i in range(0, 30, 4):
print(i, end=" ")
print()
Output :
0 4 8 12 16 20 24 28

Python range() using Negative Step


If a user wants to decrement, then the user needs steps to be a negative number.
# incremented by -2
for i in range(25, 2, -2):
print(i, end=" ")
print()
Output :
25 23 21 19 17 15 13 11 9 7 5 3

Python range() with Float Values


Python range() function doesn’t support float numbers. i.e. user cannot use floating-point or non-integer numbers in any
of its arguments. Users can use only integer numbers.
for i in range(3.3):
print(i)

Output:
TypeError: 'float' object cannot be interpreted as an integer

Accessing range() with an Index Value


A sequence of numbers is returned by the range() function as its object that can be accessed by its index value.
Both positive and negative indexing is supported by its object.
ele = range(10)[0]
print("First element:", ele)

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

THE While Loop


The while statement executes a block of code repeatedly as long as the control condition of the loop is true.
After each iteration, the control condition is tested again and the loop continues as long as the condition remains
true.
When this condition becomes false, the statements in the body of loop are not executed and the control is
transferred to the statement immediately
If the condition of the while loop is initially false, the body is not executed even once.
while loop Syntax
while expression:
statement(s)

 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

Loop Control Statements


Loop control statements in Python are special statements that help control the execution of loops (for or while).
They let you modify the default behavior of the loop, such as stopping it early, skipping an iteration, or doing
nothing temporarily. . Python supports the following control statements:
 Break statement
 Continue statement

Break Statement in Python


The break statement in Python is used to exit or “break” out of a loop (either a for or while loop) prematurely,
before the loop has iterated through all its items or reached its condition. When the break statement is
executed, the program immediately exits the loop, and the control moves to the next line of code after the loop.
Example:
# Using For Loop
for i in range(5):
if i == 3:
break # Exit the loop when i is 3
print(i)

# Using While Loop


i=0
while i < 5:
if i == 3:
break # Exit the loop when i is 3
print(i)
i += 1

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:

Example 1: Using exit() to terminate the program

import sys # Required for [Link]()


for i in range(5):
print(f"Current value: {i}")
if i == 3:
print("Exiting the program...")
exit() # Terminates the entire program
print("This will not be printed because exit() stops the program.")

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

You might also like