UNIT -1
INTRODUCTION
Python is a general-purpose, dynamically typed, high-level, compiled and interpreted,
garbage-collected, and purely object-oriented programming language that supports procedural, object-oriented,
and functional programming.
Python is a widely used high-level, interpreted programming language. It was created by Guido van Rossum in
1991 and further developed by the Python Software Foundation. It was designed with an emphasis on code
readability, and its syntax allows programmers to express their concepts in fewer lines of code. python is a
programming language that lets you work quickly and integrate systems more efficiently.
Why Learn Python?
• Easy Syntax: Python syntax is like plain English, which allows you to focus on logic instead of
worrying about complex rules.
• Easy Career Transition: If you know any other programming language, moving to Python is super
easy.
• Project Oriented Learning: You can start making simple project while learning the python basics.
Python Syntax
To print a statement- print(“Hello World”)
Output: Hello World
• Advantages of Python:
• Easy to learn, read, and understand
• Versatile and open-source
• Improves productivity
• Supports libraries
• Huge library
• Strong community
• Interpreted language
• Disadvantages of Python:
• Restrictions in design
• Memory inefficient
• Weak mobile computing
• Runtime errors
• Slow execution speed
Python Features
[Link] to Learn and Use
Python is easy to learn as compared to other programming languages. Its syntax is straightforward and
much the same as the English language. There is no use of the semicolon or curly-bracket, the indentation
defines the code block. It is the recommended programming language for beginners.
[Link]-Oriented Language
Python supports object-oriented language and concepts of classes and objects come into existence. It
supports inheritance, polymorphism, and encapsulation, etc. The object-oriented procedure helps to
programmer to write reusable code and develop applications in less code.
[Link] Language
Python is an interpreted language; it means the Python program is executed one line at a time. The
advantage of being interpreted language, it makes debugging easy and portable.
[Link]-platform Language
Python can run equally on different platforms such as Windows, Linux, UNIX, and Macintosh, etc. So, we
can say that Python is a portable language. It enables programmers to develop the software for several
competing platforms by writing a program only once.
Free and Open Source
Python is freely available for everyone. It is freely available on its official. It has a large community across
the world that is dedicatedly working towards make new python modules and functions. Anyone can
contribute to the Python community. The open-source means, "Anyone can download its source code
without paying any penny."
Large Standard Library
It provides a vast range of libraries for the various fields such as machine learning, web developer, and also
for the scripting. There are various machine learning libraries, such as Tensor flow, Pandas, Numpy, Keras,
and Pytorch, etc. Django, flask, pyramids are the popular framework for Python web development.
Expressive Language
Python can perform complex tasks using a few lines of code. A simple example, the hello world program
you simply type print("Hello World"). It will take only one line to execute, while Java or C takes multiple
lines.
application
Web development
• Python is used to create web applications quickly using frameworks and libraries.
• The Django web framework is used to build Instagram.
Desktop GUI
• Python is used to create graphical user interfaces (GUIs) using built-in tools like PyQT, wxWidgets,
and kivy.
Audio and video applications
• Python is used to create audio and video applications using libraries like PyDub and OpenCV.
• Spotify is an example of an app built using Python.
Scientific and numeric computing
• Python is used for scientific and numeric computing.
• Game development Python is used for game development.
• Artificial intelligence and machine learning
• Python is used for artificial intelligence and machine learning.
Embedded systems
• Python is used to develop applications for embedded devices.
Web scraping
• Python is used to create scraping programs using libraries like Requests.
Version of python
Python has multiple versions, including Python 2.0, Python 3.0, Python 3.7, Python 3.10, and Python
3.12. The most recent version is Python 3.12.6.
Python 2.0
• Released in 2000, this version is still the basis for many Python programs
• Added new functionality to the original language
Python 3.0
• Released in late 2008, this version addressed design flaws in previous versions
• Considered the future of Python.
Python 3.7
• A major release with new features and improvements
• Provides developers with a more powerful and flexible programming environment.
Python 3.10
• Python 3.10.11 is the eleventh maintenance release of Python 3.10
• Python 3.10.10 is the newest major release of the Python programming language
• Python 3.12.6
• The latest Python version, which improves efficiency, developer experience, and performance
Other Python versions:
• Python 3.8.10 was the final regular maintenance release of the 3.8 branch
What is IDE?
Python IDEs (Integrated Development Platforms) are dedicated platforms to code, compile, run, test, and
debug python code. It is said that Python IDEs understand the code better than any text editors. They possess
an integrated build process.
• List of IDEs
• PyCharm
• IDLE
• Visual studio code
• Atom
• Sublime text
• Spyder
• PyDev
• Jupyter
• Thonny
• PyScripter
Command line mode
Python command-line mode can be used to run Python scripts, create tools, and automate tasks.
How to open Python command-line mode
• On macOS or Linux, open a terminal and type "python"
• On Windows, open the command prompt and type "py"
• Select "Python (command line)", "IDLE", or similar program from the task bar or app menu.
Interactive mode
• Interactive mode is a command line shell that runs statements immediately
• It's a good way to try out different syntax
• The >>> prompt indicates that you are in interactive mode
Script mode
• Script mode runs commands sequentially from a file
• It's useful for running a series of commands on a file or group of files.
Command-line tools
• Developers can create tools that execute actions with precision and speed by writing scripts that accept
command-line arguments and options.
• This automation saves time and reduces the likelihood of human error.
Simple python program example.
# Python3 program to add two numbers
num1 = 15
num2 = 12
#Adding two nos
sum = num1 + num2
# printing values
print("Sum of", num1, "and", num2 , "is", sum)
output
Sum of 15 and 12 is 27
PYTHON BASICS
Identifiers in Python
Identifier is a user-defined name given to a variable, function, class, module, etc. The identifier is a
combination of character digits and an underscore. They are case-sensitive i.e., ‘num’ and ‘Num’ and ‘NUM’
are three different identifiers in python. It is a good programming practice to give meaningful names to
identifiers to make the code understandable.
We can also use the Python string is identifier() to check whether a string is a valid identifier or not.
Rules for Naming Python Identifiers
• It cannot be a reserved python keyword.
• It should not contain white space.
• It can be a combination of A-Z, a-z, 0-9, or underscore.
• It should start with an alphabet character or an underscore ( _ ).
• It should not contain any special character other than an underscore ( _ ).
•
keyword
• Python keywords are unique words reserved with defined meanings and functions that we can only
apply for those functions. You'll never need to import any keyword into your program because they're
permanently present.
• Python has a set of keywords that are reserved words that cannot be used as variable names, function
names, or any other identifiers
• Rules
• Keyword cant be used as identifier.
• It should be in lower case except True and False.
Getting List of all Python keywords
We can also get all the keyword names using the below code.
import keyword
# printing all keywords at once using "kwlist()"
print("The list of keywords is : ")
print([Link])
Output:
The list of keywords are:
['False', 'None', 'True',"__peg_parser__ 'and', 'as', 'assert', 'async', 'await', 'break',
'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if',
'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
Statements
Statement is an instruction for the computer to do something. Based on the instruction given system will
execute.
Types
[Link] statement
Smallest unit of [Link] not contain any logical or conditional expression.
Ex: assigning value to variable, calling function ,print statement .
[Link]-line Statement in Python:
In Python, the statements are usually written in a single line and the last character of these lines is newline. To
extend the statement to one or more lines we can use braces {}, parentheses (), square [], semi-colon “;”, and
continuation character slash “\”. we can use any of these according to our requirement in the code. With the line
continuation character, we can explicitly divide a long statement into numerous lines (\).
Initialize the lines using continuation character
g = "welcome\
to\
college"
print(g)
Output:
Welcome to college
[Link] conditional and looping statement
[Link] if statement
b. python if else statement
c. python if elif else statement
d. python nested if statement
e. python for loop
f. python while loop
[Link] Expression statements
[Link] pass statement
b. Python return statement
c. Python break statement
[Link] continue statement
f. Python del statement
g. Python import statement
expressions
An expression is a combination of operators and operands that is interpreted to produce some other value. In
any programming language, an expression is evaluated as per the precedence of its operators. So that if there is
more than one operator in an expression, their precedence decides which operation will be performed first.
Types
1. Constant Expressions: These are the expressions that have constant values only.
Example:
x = 15 + 1.3
print(x)
Output
16.3
2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values,
operators, and sometimes parenthesis. The result of this type of expression is also a numeric
value. The operators used in these expressions are arithmetic operators like addition,
subtraction, etc.
Example:
x = 40
y = 12
add = x + y
sub = x - y
pro = x * y
div = x / y
print(add)
print(sub)
print(pro)
print(div)
Output
52
28
480
3.3333333333333335
3. Integral Expressions: These are the kind of expressions that produce only integer results
after all computations and type conversions.
Example:
Python3
# Integral Expressions
a = 13
b = 12.0
c = a + int(b)
print(c)
Output 25
4. Floating Expressions: These are the kind of expressions which produce floating point
numbers as result after all computations and type conversions.
Example:
a=15
b=4
c=a/b
Output
3.75
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.
Example:
a = 21
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)
Output
True
[Link] 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.
P = (10 == 9)
Q = (7 > 5)
# Logical Expressions
R = P and Q
S = P or Q
T = not P
print(R)
print(S)
print(T)
Output
False
True
True
[Link] Expressions: These are the kind of expressions in which computations are performed
at bit level.
Example:
# 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.
Example:
# Combinational Expressions
a = 16
b = 12
c = a + (b >> 1)
print(c)
Output
22
Multiple operators in expression (Operator Precedence)
It’s a quite simple process to get the result of an expression if there is only one operator in an
expression. But if there is more than one operator in an expression, it may give different results
on basis of the order of operators executed. To sort out these confusions, the operator
precedence is defined. Operator Precedence simply defines the priority of operators that which
operator is to be executed first. Here we see the operator precedence in Python, where the
operator higher in the list has more precedence or priority:
Precedence Name Operator
1 Parenthesis ()[]{}
2 Exponentiation **
Unary plus or minus,
3 -a , +a , ~a
complement
Multiply, Divide,
4 / * // %
Modulo
5 Addition & Subtraction + –
6 Shift Operators >> <<
7 Bitwise AND &
8 Bitwise XOR ^
9 Bitwise OR |
10 Comparison Operators >= <= > <
11 Equality Operators == !=
= += -
12 Assignment Operators
= /= *=
Identity and membership is, is not, in,
13
operators not in
Precedence Name Operator
14 Logical Operators and, or, not
a = 10 + 3 * 4
print(a)
b = (10 + 3) * 4
print(b)
c = 10 + (3 * 4)
print(c)
Output
22
52
22
result = 3 + 5 * (2 ** 3) - 8 / 4 + (6 - 2) * 3
Exponentiation (**) has the highest precedence:
2 ** 3 evaluates to 8
Now, the expression looks like this:
result = 3 + 5 * 8 - 8 / 4 + (6 - 2) * 3
Parentheses are evaluated next (they have higher precedence than addition, subtraction,
multiplication, and division):
(6 - 2) evaluates to 4
result = 3 + 5 * 8 - 8 / 4 + 4 * 3
Multiplication (*) and division (/) come next, evaluated from left to right:
5 * 8 evaluates to 40.
8 / 4 evaluates to 2.0 (since division results in a float in Python)
4 * 3 evaluates to 12.
result = 3 + 40 - 2.0 + 12
Finally, addition (+) and subtraction (-) are evaluated from left to right:
• 3 + 40 evaluates to 43.
• 43 - 2.0 evaluates to 41.0.
• 41.0 + 12 evaluates to 53.0.
Final result:
result = 53.0
Python Variables
In python , variables are used to store data that can be referenced and manipulated during program execution. A
variable is essentially a name that is assigned to a value. Unlike many other programming languages, Python
variables do not require explicit declaration of type. The type of the variable is inferred based on the value
assigned.
Variables act as placeholders for data. They allow us to store and reuse values in our program.
Example:
# Variable 'x' stores the integer value 10
x=5
# Variable 'name' stores the string "Samantha"
name = "Samantha"
print(x)
print(name)
Output
Samantha
Rules for Naming Variables
To use variables effectively, we must follow Python’s naming rules:
• Variable names can only contain letters, digits and underscores (_).
• A variable name cannot start with a digit.
• Variable names are case-sensitive (myVar and myvar are different).
• Avoid using keywords as variable names.
Assigning Values to Variables
[Link] Assignment
Variables in Python are assigned values using the = operator
x=5
y = 3.14
z = "Hi"
[Link] Assignments
Python allows multiple variables to be assigned values in a single line.
Assigning the Same Value
Python allows assigning the same value to multiple variables in a single line, which can be useful for
initializing variables with the same value.
a = b = c = 100
print(a, b, c)
• Output
100 100 100
Assigning Different Values
We can assign different values to multiple variables simultaneously, making the code concise and easier to
read.
x, y, z = 1, 2.5, "Python"
print(x, y, z)
Output
1 2.5 Python
Type Casting a Variable
Type casting refers to the process of converting the value of one data type into another. Python provides
several built-in functions to facilitate casting, including int(), float() and str() among others.
Examples of Casting:
# Casting variables
s = "10" # Initially a string
n = int(s) # Cast string to integer
cnt = 5
f = float(cnt) # Cast integer to float
age = 25
s2 = str(age) # Cast integer to string
# Display results
print(n)
print(f)
print(s2)
Output
10
5.0
25
Getting the Type of Variable
In Python, we can determine the type of a variable using the type() function. This built-in function returns the
type of the object passed to it.
# Define variables with different data types
n = 42
f = 3.14
s = "Hello, World!"
li = [1, 2, 3]
d = {'key': 'value'}
bool = True
# Get and print the type of each variable
print(type(n))
print(type(f))
print(type(s))
print(type(li))
print(type(d))
print(type(bool))
Output
• <class 'int'>
• <class 'float'>
• <class 'str'>
• <class 'list'>
• <class 'dict'>
• <class 'bool'>
Python Operators
Operators are used to perform operations on variables and values.
Python divides the operators in the following groups:
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
Arithmetic Operators in Python
Python arithmetic operator are used to perform basic mathematical operations like addition, subtraction,
multiplication and division.
In Python 3.x the result of division is a floating-point while in Python 2.x division of 2 integers was an integer.
To obtain an integer result in Python 3.x floored (// integer) is used.
Example
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)
Output
Addition: 19
Subtraction: 11
Multiplication: 60
Division: 3.75
Floor Division: 3
Modulus: 3
Exponentiation: 50625
Comparison of Python Operators
In Python comparison or relational operator compares the values. It either returns True or False according to
the condition.
Example
a = 13
b = 33
print(a > b)
print(a < b)
print(a == b)
print(a != b)
print(a >= b)
print(a <= b)
Output
False
True
False
True
False
True
Logical Operators in Python
Python logical operator perform Logical AND, Logical OR and Logical NOT operations. It is used to
combine conditional statements.
The precedence of Logical Operators in Python is as follows:
1. Logical not
2. logical and
3. logical or
Output
<class 'int'>
<class 'float'>
<class 'str'>
<class 'list'>
<class 'dict'>
<class 'bool'>
Bitwise Operators in Python
Python bitwise operator act on bits and perform bit-by-bit operations. These are used to operate on binary
numbers.
Bitwise Operators in Python are as follows:
1. Bitwise NOT
2. Bitwise Shift
3. Bitwise AND
4. Bitwise XOR
5. Bitwise OR
Example of Bitwise Operators in Python:
a = 10
b=4
print(a & b)
print(a | b)
print(~a)
print(a ^ b)
print(a >> 2)
print(a << 2)
Output
0
14
-11
14
2
40
Assignment Operators in Python
Python assignment operator are used to assign values to the variables. This operator is used to assign the
value of the right side of the expression to the left side operand.
Example of Assignment Operators in Python:
a = 10
b=a
print(b)
b += a
print(b)
b -= a
print(b)
b *= a
print(b)
b <<= a
print(b)
Output
10
20
10
100
102400
Identity Operators in Python
In Python, is and is not are the identity operators both are used to check if two values are located on the
same part of the memory. Two variables that are equal do not imply that they are identical.
is True if the operands are identical is not True if the operands are not identical .
Example of Identity Operators in Python:
a = 10
b = 20
c=a
print(a is not b)
print(a is c)
Output
True
True
Membership Operators in Python
In Python, in and not in are the membership operator that are used to test whether a value or variable is
in a sequence.
in True if value is found in the sequence not in True if value is not found in the sequence
Examples of Membership Operators in Python:
x = 24
y = 20
list = [10, 20, 30, 40, 50]
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")
if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
Output
x is NOT present in given list
y is present in given list
python data types
Python Data types are the classification or categorization of data items. It represents the kind of value
that tells what operations can be performed on a particular data. Since everything is an object in Python
programming, Python data types are classes and variables are instances (objects) of these classes. The
following are the standard or built-in data types in Python:
1. Numeric Data Types in Python
The numeric data type in Python represents the data that has a numeric value. A numeric value can be an
integer, a floating number, or even a complex number. These values are defined as python int ,python
float, python complex classes in python .
• Integers – This value is represented by int class. It contains positive or negative whole numbers
(without fractions or decimals). In Python, there is no limit to how long an integer value can be.
• Float – This value is represented by the float class. It is a real number with a floating-point
representation. It is specified by a decimal point. Optionally, the character e or E followed by a
positive or negative integer may be appended to specify scientific notation.
• Complex Numbers – A complex number is represented by a complex class. It is specified as (real
part) + (imaginary part)j . For example – 2+3j
a=5
print(type(a))
b = 5.0
print(type(b))
c = 2 + 4j
print(type(c))
Output
<class 'int'>
<class 'float'>
<class 'complex'>
2. Sequence Data Types in Python
The sequence Data Type in Python is the ordered collection of similar or different Python data types. Sequences
allow storing of multiple values in an organized and efficient fashion. There are several sequence data types of
Python:
• Python string
• Python list
• Python tuple
[Link] Data Type
Python strings are arrays of bytes representing Unicode characters. In Python, there is no character data type
Python, a character is a string of length one. It is represented by str class.
Strings in Python can be created using single quotes, double quotes, or even triple quotes. We can access
individual characters of a String using index.
s = 'Welcome to the python World'
print(s)
# check data type
print(type(s))
# access string with index
print(s[1])
print(s[2])
print(s[-1])
output
python to the Geeks World
<class 'str'>
e
l
d
[Link] Data Type
Lists are just like arrays, declared in other languages which is an ordered collection of data. It is very flexible
as the items in a list do not need to be of the same type.
Creating a List in Python
Lists in Python can be created by just placing the sequence inside the square brackets[].
# Empty list
a = []
# list with int values
a = [1, 2, 3]
print(a)
# list with mixed int and string
b = ["python", "programming", "py", 4, 5]
print(b)
Output
[1, 2, 3]
['python', 'programming', 'py', 4, 5]
Access List Items
In order to access the list items refer to the index number. In Python, negative sequence indexes represent
positions from the end of the array. Instead of having to compute the offset as in List[len(List)-3], it is
enough to just write List[-3]. Negative indexing means beginning from the end, -1 refers to the last item, -2
refers to the second-last item, etc.
a = ["abc", "xyz", "lmn"]
print("Accessing element from the list")
print(a[0])
print(a[2])
print("Accessing element using negative indexing")
print(a[-1])
print(a[-3])
Output
Accessing element from the list
abc
lmn
Accessing element using negative indexing
abc
lmn
[Link] Data Type
Just like a list,a tuple is also an ordered collection of Python objects. The only difference between a tuple
and a list is that tuples are immutable. Tuples cannot be modified after it is created.
Creating a Tuple in Python
In Python Data Types, tuples are created by placing a sequence of values separated by a ‘comma’ with or
without the use of parentheses for grouping the data sequence. Tuples can contain any number of elements
and of any datatype (like strings, integers, lists, etc.).
# initiate empty tuple
t1 = ()
t2 = ('Geeks', 'For')
print("\nTuple with the use of String: ", t2)
Output
Tuple with the use of String: ('Geeks', 'For')
Access Tuple Items
In order to access the tuple items refer to the index number. Use the index operator [ ] to access an item in a
tuple.
t1 = tuple([1, 2, 3, 4, 5])
# access tuple items
print(t1[0])
print(t1[-1])
print(t1[-3])
Output
6. Boolean Data Type in Python
Python Data type with one of the two built-in values, True or False. Boolean objects that are equal to True
are truthy (true), and those equal to False are falsy (false). However non-Boolean objects can be evaluated in
a Boolean context as well and determined to be true or false. It is denoted by the class bool.
Example: The first two lines will print the type of the boolean values True and False, which is <class
‘bool’>. The third line will cause an error, because true is not a valid keyword in Python. Python is case-
sensitive, which means it distinguishes between uppercase and lowercase letters.
print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
7. Set Data Type in Python
In Python Data Types, set is an unordered collection of data types that is iterable, mutable, and has no
duplicate elements. The order of elements in a set is undefined though it may consist of various elements.
Create a Set in Python
Sets can be created by using the built-in set() function with an iterable object or a sequence by placing the
sequence inside curly braces, separated by a ‘comma’. The type of elements in a set need not be the same,
various mixed-up data type values can also be passed to the set.
Example: The code is an example of how to create sets using different types of values, such
as strings , lists , and mixed values
# initializing empty set
s1 = set()
s1 = set("python")
print("Set with the use of String: ", s1)
s2 = set(["welcome", "to", "python"])
print("Set with the use of List: ", s2)
Output
Set with the use of String: {‘p’,’y’,’t’,’h’,’o’,’n’}
Set with the use of List: {'welcome', 'to',’python’}
5. Dictionary Data Type
A dictionary in Python is a collection of data values, used to store data values like a map, unlike other Python
Data Types that hold only a single value as an element, a Dictionary holds a key: value pair. Key-value is
provided in the dictionary to make it more optimized. Each key-value pair in a Dictionary is separated by a
colon : , whereas each key is separated by a ‘comma’.
Create a Dictionary in Python
Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must
be immutable. The dictionary can also be created by the built-in function dict().
# initialize empty dictionary
d = {}
d = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(d)
# creating dictionary using dict() constructor
d1 = dict({1: 'Geeks', 2: 'For', 3: 'Geeks'})
print(d1)
Output
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Accessing Key-value in Dictionary
In order to access the items of a dictionary refer to its key name. Key can be used inside square brackets.
Using get() method we can access the dictionary elements.
d = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
# Accessing an element using key
print(d['name'])
# Accessing a element using get
print([Link](3))
Output
For
Geeks
Indentation in Python
In Python, indentation is used to define blocks of code. It tells the python interpreter that a group of
statements belongs to a specific block. All statements with the same level of indentation are considered part
of the same block. this is achieved using whitespace (spaces or tabs) at the beginning of each line.
For Example:
if 10 > 5:
print("This is true!")
print("I am tab indentation")
print("I have no indentation")
Output
This is true!
I am tab indentation
I have no indentation
Comments
Comments can be used to explain Python code.
Comments can be used to make the code more readable.
Comments starts with a #, and Python will ignore them:
#This is a comment
print("Hello, World!")
Multi-Line Comments
Python does not provide the facility for multi-line comments. However, there are indeed many ways to create
multi-line comments.
With Multiple Hashtags (#)
In Python, we may use hashtags (#) multiple times to construct multiple lines of comments. Every line with a
(#) before it will be regarded as a single-line comment.
Code
1. # it is a
2. # comment
3. # extending to multiple lines
In this case, each line is considered a comment, and they are all omitted.
Console input() and output()
In Python, the input() function allows you to capture user input from the keyboard, while you can use the
print() function to display output to the console. These built-in functions allow for basic user interaction in
Python scripts, enabling you to gather data and provide feedback.
Example:
name=input(“enter your name”)
print(“My Name is“, name)
o/p enter your name
Rahul
My Name is Rahul
Type Conversion in Python
The act of changing an object’s data type is known as type conversion.
There are two types of Type Conversion.
Implicit Type Conversion in Python
In Implicit type conversion of data types in Python, the Python interpreter automatically converts one data
type to another without any user involvement.
x = 10
print("x is of type:",type(x))
y = 10.6
print("y is of type:",type(y))
z=x+y
print(z)
print("z is of type:",type(z))
o/p
x is of type: <class 'int'>
y is of type: <class 'float'>
20.6
z is of type: <class 'float'>
Explicit Type Conversion in Python
In Explicit Type Conversion, users convert the data type of an object to required data type.
We use the built-in functions like int(),float(),str() etc to perform explicit type conversion.
This type of conversion is also called typecasting because the user casts (changes) the data type of the
objects.
num_string = '12'
num_integer = 23
print("Data type of num_string before Type Casting:",type(num_string))
# explicit type conversion
num_string = int(num_string)
print("Data type of num_string after Type Casting:",type(num_string))
num_sum = num_integer + num_string
print("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))
o/p
Data type of num_string before Type Casting: <class 'str'>
Data type of num_string after Type Casting: <class 'int'>
Sum: 35
Data type of num_sum: <class 'int'>
Libraries in Python
A Python library is a collection of related modules. It contains bundles of code that can be used repeatedly in
different programs. It makes Python Programming simpler and convenient for the programmer. As we don’t
need to write the same code again and again for different programs.
some of the commonly used libraries:
1. TensorFlow: This library was developed by Google in collaboration with the Brain Team. It is an
open-source library used for high-level computations. It is also used in machine learning and deep
learning algorithms. It contains a large number of tensor operations. Researchers also use this Python
library to solve complex computations in Mathematics and Physics.
2. Matplotlib: This library is responsible for plotting numerical data. And that’s why it is used in data
analysis. It is also an open-source library and plots high-defined figures like pie charts, histograms,
scatterplots, graphs, etc.
3. Pandas: Pandas are an important library for data scientists. It is an open-source machine learning
library that provides flexible high-level data structures and a variety of analysis tools. It eases data
analysis, data manipulation, and cleaning of data. Pandas support operations like Sorting, Re-
indexing, Iteration, Concatenation, Conversion of data, Visualizations, Aggregations, etc.
4. Numpy: The name “Numpy” stands for “Numerical Python”. It is the commonly used library. It is a
popular machine learning library that supports large matrices and multi-dimensional data. It consists
of in-built mathematical functions for easy computations. Even libraries like TensorFlow use Numpy
internally to perform several operations on tensors. Array Interface is one of the key features of this
library.
5. SciPy: The name “SciPy” stands for “Scientific Python”. It is an open-source library used for high-
level scientific computations. This library is built over an extension of Numpy. It works with Numpy
to handle complex computations. While Numpy allows sorting and indexing of array data, the
numerical data code is stored in SciPy. It is also widely used by application developers and engineers.
6. Scrapy: It is an open-source library that is used for extracting data from websites. It provides very
fast web crawling and high-level screen scraping. It can also be used for data mining and automated
testing of data.
7. Scikit-learn: It is a famous Python library to work with complex data. Scikit-learn is an open-source
library that supports machine learning. It supports variously supervised and unsupervised algorithms
like linear regression, classification, clustering, etc. This library works in association with Numpy
and SciPy.
8. PyGame: This library provides an easy interface to the Standard Directmedia Library (SDL)
platform-independent graphics, audio, and input libraries. It is used for developing video games u
[Link]: PyTorch is the largest machine learning library that optimizes tensor computations. It has
rich APIs to perform tensor computations with strong GPU acceleration. It also helps to solve application
issues related to neural networks.
10. PyBrain: The name “PyBrain” stands for Python Based Reinforcement Learning, Artificial
Intelligence, and Neural Networks library. It is an open-source library built for beginners in the
field of Machine Learning. It provides fast and easy-to-use algorithms for machine learning tasks.
It is so flexible and easily understandable and that’s why is really helpful for developers that are
new in research fields.
# Importing math library
import math
A = 16
print([Link](A))
Output
4.0
# Importing specific items
from math import sqrt, sin
A = 16
B = 3.14
print(sqrt(A))
print(sin(B))
Output
4.0
0.0015926529164868282
Python control flow
Python control flow. Control flow is the order in which individual statements, instructions, or
function calls are executed or evaluated.
Types
[Link]:By default line by line will execute.
[Link]:used for making decision and branching.
Ex: conditional statement
[Link]:used to perform repeated piece of code multiple times. Ex: looping statement
Conditional Statements in Python
If Conditional Statement in Python
is the simplest form of a conditional statement. It executes a block of code if the given condition is true.
Example:
age = 20
if age >= 18:
print("Eligible to vote.")
Output Eligible to vote.
If else Conditional Statements in Python
It allows us to specify a block of code that will execute if the condition(s) associated with an if or elif
statement evaluates to False. Else block provides a way to handle all other cases that don't meet the specified
conditions.
Example:
age = 10
if age <= 12:
print("Travel for free.")
else:
print("Pay for ticket.")
Output
Travel for free.
elif Statement
elif statement in Python stands for "else if." It allows us to check multiple conditions , providing a way to
execute different blocks of code based on which condition is true. Using elif statements makes our code more
readable and efficient by eliminating the need for multiple nested if statements.
Example:
age = 25
if age <= 12:
print("Child.")
elif age <= 19:
print("Teenager.")
elif age <= 35:
print("Young adult.")
else:
print("Adult.")
Output
Young adult.
Nested if..else Conditional Statements in Python
age = 70
is_member = True
if age >= 60:
if is_member:
print("30% senior discount!")
else:
print("20% senior discount.")
else:
print("Not eligible for a senior discount.")
Output
30% senior discount!
Loops in Python
While Loop in Python
It is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition
becomes false, the line immediately after the loop in the program is executed.
Python While Loop Syntax:
while expression:
statement(s)
Example of Python While Loop:
cnt = 0
while (cnt < 3):
cnt = cnt + 1
print("Hello world")
Output
Hello Geek
Hello Geek
Hello Geek
For Loop in Python
used for sequential traversalFor example: traversing a list or string or array etc.
For Loop Syntax:
for iterator_var in sequence:
statements(s)
n=4
for i in range(0, n):
print(i)
Output
Nested Loops in Python
Python programming language allows to use one loop inside another loop which is called nested loop.
2 typers: 1. Nested while loop
2. Nested for loop
Python Nested Loops Syntax:
Outer_loop Expression:
Inner_loop Expression:
Statement inside inner_loop
Statement inside Outer_loop
Example 1: Basic Example of Python Nested Loops
x = [1, 2]
y = [4, 5]
for i in x:
for j in y:
print(i, j)
Output:
14
15
24
25
Control Statements in Loops
Control statements modify the loop’s execution flow. Python provides three primary control
statements: continue, break, and pass.
break Statement
The is used to exit the loop prematurely when a certain condition is met.
# Using break to exit the loop
for i in range(10):
if i == 5:
break
print(i)
Output
continue Statement
for i in range(10):
if i % 2 == 0:
continue
print(i)
Output
pass Statement
for i in range(5):
if i == 3:
pass
print(i)
Output
Python range() Function
The range() function returns a sequence of numbers, starting from 0 by default, and increments
by 1 (by default), and stops before a specified number.
Syntax
range(start, stop, step)
Parameter Description
start Optional. An integer number specifying at which position to
start. Default is 0
stop Required. An integer number specifying at which position to
stop (not included).
step Optional. An integer number specifying the incrementation.
Default is 1
Example
Create a sequence of numbers from 3 to 5, and print each item in the sequence:
x = range(3, 6)
for n in x:
print(n)
o/p
3
4
5
x = range(3, 20, 2)
for n in x:
print(n)
o/p
3
5
7
9
11
13
15
19
exit() Function
exit() terminates the program [Link] tell to stop execution of loop.
Ex:
1. for x in range(3,10)
print(x+20)
exit()
o/p 23
2. print(“python programming”)
exit()
print(“basic version ”)
o/p python programming
Python function
Python Functions is a block of statements that return the specific task. The idea is to put some commonly or
repeatedly done tasks together and make a function so that instead of writing the same code again and again for
different inputs, we can do the function calls to reuse code contained in it over and over again.
Some Benefits of Using Functions
• Increase Code Readability
• Increase Code Reusability
Python Function Declaration
The syntax to declare a function is:
Types of Functions in Python
• Built-in library function: These are standard function in Python that are available to use.
• User-defined function: We can create our own functions based on our requirements.
Creating a Function in Python
We can define a function in Python, using the def keyword. We can add any type of functionalities and
properties to it as we require.
# A simple Python function
def fun():
print("Welcome to GFG")
Calling a Function in Python
After creating a function in Python we can call it by using the name of the functions Python followed by
parenthesis containing parameters of that particular function.
# A simple Python function
def fun():
print("Welcome to GFG")
# Driver code to call a function
fun()
Output:
Welcome to GFG
Parameter: In Python, a parameter is a variable that receives data passed into a function.
Arguments: In Python, an argument is a value that's passed to a function when it's called.
Function with parameter
Syntax
def function_name(parameter1, parameter2….)
Ex:
def abc( name=”Raman”)
print(“Hello,{name}! welcome to python world”)
abc()
o/p Hello,Raman! welcome to python world
Python Function Arguments
Arguments are the values passed inside the parenthesis of the function call. A function can have any number of
arguments separated by a comma.
# A simple Python function to check
# whether x is even or odd
def evenOdd(x):
if (x % 2 == 0):
print("even")
else:
print("odd")
# Driver code to call the function
evenOdd(2)
evenOdd(3)
Output:
even
odd
Default Parameter Value
If we call the function without argument, it uses the default value:
def my_function(country = "Norway"):
print("I am from " + country)
my_function("Sweden")
my_function("India")
my_function()
my_function("Brazil")
o/p:
I am from Sweden
I am from India
I am from Norway
I am from Brazil
Types of Python Function Arguments
• Default argument
• Keyword arguments (named arguments)
Default Arguments
A default argument is a parameter that assumes a default value if a value is not provided in the function call
for that argument. The following example illustrates Default arguments to write functions in Python.
# Python program to demonstrate
# default arguments
def myFun(x, y=50):
print("x: ", x)
print("y: ", y)
# Driver code (We call myFun() with only
# argument)
myFun(10)
Output:
x: 10
y: 50
Keyword Arguments
The idea is to allow the caller to specify the argument name with values so that the caller does not need to
remember the order of parameters.
# Python program to demonstrate Keyword Arguments
def student(firstname, lastname):
print(firstname, lastname)
# Keyword arguments
student(firstname='Geeks', lastname='Practice')
student(lastname='Practice', firstname='Geeks')
Output:
Geeks Practice
Geeks Practice
Recursion function.
Recursive functions are functions that calls itself. It is always made up of 2 portions, the base case and the
recursive case.
• The base case is the condition to stop the recursion.
• The recursive case is the part where the function calls on itself.
Basic Structure of Recursive Function
def recursive_function(parameters):
if base_case_condition:
return base_result
else:
return recursive_function(modified_parameters)
Example:
def fibonacci(n):
# Base cases
if n == 0:
return 0
elif n == 1:
return 1
# Recursive case
else:
return fibonacci(n-1) + fibonacci(n-2)
# Example usage
print(fibonacci(10))
Output
55
Python return statement
A return statement is used to end the execution of the function call and it “returns” the value of the expression
following the return keyword to the caller. The statements after the return statements are not executed
Example:
def add(a, b):
# returning sum of a and b
return a + b
def is_true(a):
# returning boolean of a
return bool(a)
# calling function
res = add(2, 3)
print(res)
res = is_true(2<5)
print(res)
Output
True
Python Exception Handling
Errors are problems in a program that causes the program to stop its execution. On the other hand, exceptions
are raised when some internal events change the program’s normal flow.
Types of error
[Link] error in python
[Link] logical error(exception)
Syntax Errors in Python
When the proper syntax of the language is not followed then a syntax error is thrown.
# initialize the amount variable
amount = 10000
# check that You are eligible to
# purchase Dsa Self Paced or not
if(amount>2999)
print("You are eligible to purchase Dsa Self Paced")
Output:
Example 2: When indentation is not correct.
if(a<3):
print("gfg")
Output
Python Logical Errors (Exception)
A logical error in Python, or in any programming language, is a type of bug that occurs when a program runs
without crashing but produces incorrect or unintended results. Logical errors are mistakes in the program’s logic
that lead to incorrect behavior or output, despite the syntax being correct.
Characteristics of Logical Errors
1. No Syntax Error: The code runs successfully without any syntax errors.
2. Unexpected Output: The program produces output that is different from what is expected.
3. Difficult to Detect: Logical errors can be subtle and are often harder to identify and fix compared to
syntax errors because the program appears to run correctly.
4. Varied Causes: They can arise from incorrect assumptions, faulty logic, improper use of operators, or
incorrect sequence of instructions.
Example of a Logical Error
numbers = [10, 20, 30, 40, 50]
total = 0
# Calculate the sum of the numbers
for number in numbers:
total += number
# Calculate the average (this has a logical error)
average = total / len(numbers) - 1
print("The average is:", average)
Analysis
• Expected Output: The average of the numbers [10, 20, 30, 40, 50] should be 30.
• Actual Output: The program will output The average is: 29.0.
Common Builtin Exceptions
Exception Description
IndexError When the wrong index of a list is retrieved.
AssertionError It occurs when the assert statement fails
AttributeError It occurs when an attribute assignment is failed.
ImportError It occurs when an imported module is not found.
KeyError It occurs when the key of the dictionary is not found.
NameError It occurs when the variable is not defined.
MemoryError It occurs when a program runs out of memory.
TypeError It occurs when a function and operation are applied in an incorrect type.
Python Exception Handling
Python Exception Handling handles errors that occur during the execution of a program. Exception handling
allows to respond to the error, instead of crashing the running program.
Syntax and Usage
try:
# Code that might raise an exception
except SomeException:
# Code to handle the exception
else:
# Code to run if no exception occurs
finally:
# Code to run regardless of whether an exception occurs
try, except, else and finally Blocks
• try Block: try block lets us test a block of code for errors. Python will “try” to execute the code in this
block. If an exception occurs, execution will immediately jump to the except block.
• except Block: except block enables us to handle the error or exception. If the code inside the try block
throws an error, Python jumps to the except block and executes it. We can handle specific exceptions or
use a general except to catch all exceptions.
• else Block: else block is optional and if included, must follow all except blocks. The else block runs
only if no exceptions are raised in the try block. This is useful for code that should execute if the try
block succeeds.
• finally Block: finally block always runs, regardless of whether an exception occurred or not. It is
typically used for cleanup operations (closing files, releasing resources).
Example:
try:
n=0
res = 100 / n
except ZeroDivisionError:
print("You can't divide by zero!")
except ValueError:
print("Enter a valid number!")
else:
print("Result is", res)
finally:
print("Execution complete.")
Output
You can't divide by zero!
Execution complete.
Explanation:
try block asks for user input and tries to divide 100 by the input number.
except blocks handle ZeroDivisionError and ValueError.
else block runs if no exception occurs, displaying the result.
finally block runs regardless of the outcome, indicating the completion of execution.
Example:
try:
x = int("str") # This will cause ValueError
#inverse
inv = 1 / x
except ValueError:
print("Not Valid!")
except ZeroDivisionError:
print("Zero has no inverse!")
Output
Not Valid!