Python Unit I Notes-1
Python Unit I Notes-1
Unit I
What is Python?
Python is a high-level, general-purpose, and very popular programming language. Python programming
language is being used in web development, Machine Learning applications, along with all cutting-edge
technology in Software Industry.
Python language is being used by almost all tech-giant companies like – Google, Amazon, Facebook,
Instagram, Dropbox, Uber… etc.
The biggest strength of Python is huge collection of standard library which can be used for the following:
Machine Learning
GUI Applications (like Kivy, Tkinter, PyQt etc. )
Web frameworks like Django (used by YouTube, Instagram, Dropbox)
Image processing (like OpenCV, Pillow)
Web scraping (like Scrapy, BeautifulSoup, Selenium)
Test frameworks
Multimedia
Scientific computing
Text processing and many more..
History of python:
It was mainly developed for emphasis on code readability, and its syntax allows programmers to express
concepts in fewer lines of code.
In the late 1980s, history was about to be written. It was that time when working on Python started. Soon
after that, Guido Van Rossum began doing its application-based work in December of 1989 at Centrum
Wiskunde & Informatica (CWI) which is situated in the Netherlands.
The programming language in which Python is said to have succeeded is ABC Programming Language,
which had interfacing with the Amoeba Operating System and had the feature of exception handling.
He had already helped to create ABC earlier in his career and he had seen some issues with ABC but
liked most of the features.
He had taken the syntax of ABC, and some of its good features.
1
The inspiration for the name came from BBC’s TV Show – ‘Monty Python’s Flying Circus’, as he was a
big fan of the TV show and also he wanted a short, unique and slightly mysterious name for his invention
and hence he named it Python!
He was the “Benevolent dictator for life” (BDFL) until he stepped down from the position as the leader
on 12th July 2018.
For quite some time he used to work for Google, but currently, he is working at Dropbox.
The language was finally released in 1991.
When it was released, it used a lot fewer codes to express the concepts, when we compare it with Java,
C++ & C.
Its design philosophy was quite good too. Its main objective is to provide code readability and advanced
developer productivity.
When it was released it had more than enough capability to provide classes with inheritance, several core
data types exception handling and functions.
The two of the most used versions has to Python 2.x & 3.x. There is a lot of competition between the two
and both of them seem to have quite a number of different fanbases.
For various purposes such as developing, scripting, generation, and software testing, this language is
utilized. Due to its elegance and simplicity, top technology organizations like Dropbox, Google, Quora,
Mozilla, Hewlett-Packard, Qualcomm, IBM, and Cisco have implemented Python.
Python has come a long way to become the most popular coding language in the world. Python has just
turned 30 and just recently at pycon22(python conference) a new feature was released by Anaconda
foundation it’s known as pyscript with this now python can be written and run in the browser like
javascript which was previously not possible, but it still has that unknown charm & X factor which can be
clearly seen from the fact that Google users have consistently searched for
Python much more than they have searched for Kim Kardashian, Donald Trump, Tom Cruise, etc.
Python has been an inspiration for many other coding languages such as Ruby, Cobra, Boo, CoffeeScript
ECMAScript, Groovy, Swift Go, OCaml, Julia, etc.
There is a fact behind choosing the name Python. Guido van Rossum was reading the script of a popular
BBC comedy series "Monty Python's Flying Circus". It was late on-air 1970s.
Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So he decided to select
naming Python after the "Monty Python's Flying Circus" for their newly created programming
language.
2
The comedy series was creative and well random. It talks about everything. Thus it is slow and
unpredictable, which made it very interesting.
Python is also versatile and widely used in every technical field, such as Machine Learning, Artificial
Intelligence, Web Development, Mobile Application, Desktop Application, Scientific Calculation, etc.
Python programming language is being updated regularly with new features and supports. There are lots
of update in Python versions, started from 1994 to current release.
Python Features
Python provides many useful features which make it popular and valuable from the other programming
languages. It supports object-oriented programming, procedural programming approaches and provides
dynamic memory allocation. We have listed below a few essential features.
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.
3
2) 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.
3) Interpreted 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.
4) Cross-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.
Python is freely available for everyone. It is freely available on its official website www.python.org. The
open-source means, "Anyone can download its source code without paying any penny."
6) Object-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.
7) Extensible
It implies that other languages such as C/C++ can be used to compile the code and thus it can be used
further in our Python code. It converts the program into byte code, and any platform can use that byte
code.
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.
Graphical User Interface is used for the developing Desktop application. PyQT5, Tkinter, Kivy are the
libraries which are used for developing the web application.
10) Integrated
It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line by line like
C,C++ Java. It makes easy to debug the code.
4
11. Embeddable
The code of the other programming language can use in the Python source code
In Python, we don't need to specify the data-type of the variable. When we assign some value to the
variable, it automatically allocates the memory to the variable at run time. Suppose we are assigned
integer value 15 to x, then we don't need to write int x = 15. Just write x = 15.
Python Tokens
Tokens are the smallest units of code that have a specific purpose or meaning. Each token, like a
keyword, variable name, or number, has a role in telling the computer what to do.
1. Identifiers in Python
Identifiers is a user-defined name given to identify variables, functions, classes, modules, or any other
user-defined object in Python. They are case-sensitive and can consist of letters, digits, and underscores.
Yet, they cannot start with a digit.
5
1my_variable (starts with a number)
my-variable (contains a special character)
def (keyword)
2. Keywords in Python
Keywords are reserved words in Python that have a special meaning and are used to define the syntax and
structure of the language. These words cannot be used as identifiers for variables, functions, or other
objects. Python has a set of 35 keywords, each serving a specific purpose in the language.
There are 35 keywords in Python 3.11. They are:
3. Literals in Python
Literals are constant values that are directly specified in the source code of a program. They represent
fixed values that do not change during the execution of the program. Python supports various types of
literals, including string literals, numeric literals, boolean literals, and special literals such as None.
Numeric literals can be integers, floats, or complex numbers. Integers are whole numbers without a
fractional part, while floats are numbers with a decimal point. Complex numbers consist of a real part and
an imaginary part, represented as “x + yj“, where “x” is the real part and “y” is the imaginary part.
6
String literals are sequences of characters enclosed in single quotes (”) or double quotes (“”). They can
contain any printable characters, including letters, numbers, and special characters. Python also supports
triple-quoted strings, which can span multiple lines and are often used for docstrings, multi-line
comments, or multi-line strings
Boolean literals represent the truth values “True” and “False“. They are used in logical expressions and
control flow statements to make decisions based on certain conditions. Boolean literals are often the result
of comparison or logical operations.
Special literals include None, which represents the absence of a value or the null value. It is often used to
indicate that a variable has not been assigned a value yet or that a function does not return anything.
4. Operations in Python
Operators are symbols or special characters to carry out tasks on one or more operands. These include
arithmetic operators, assignments operator, comparison operators, logical operators, identity operators,
membership operators, and even those for handling bits.
Assignment Assign values to variables, including the equal sign and compound =, +=, -=,
Operators assignment operators. *=, /=, %=
Comparison Compare two values and return a boolean (True or False) based on the ==, !=, >, <,
Operators comparison. >=, <=
Logical Operators Combine conditions and perform logical operations like AND, OR, and and, or, not
NOT.
Identity Operators Compare the memory addresses of objects to check if they are the same is, is not
or different.
Membership Test if a value is present in a sequence (e.g., list, tuple, string). in, not in
Operators
7
Bitwise Operators Perform bit-level operations on binary numbers, allowing manipulation &
of individual bits.
5. Delimiters in Python
Delimiters are characters or symbols used to separate or mark the boundaries of different elements in
Python code. They are used to group statements, define function or class bodies, enclose string literals,
and more. Python uses various delimiters, including parentheses ‘()’, commas ‘,’, brackets ‘[]’, braces
‘{}’, colons ‘:’, and semicolons.
Punctuation Usage
Mark
Parentheses Define function arguments, control the order of operations, and create tuples.
Braces Define sets (unordered collections of unique elements) and dictionaries (key-value pairs).
Commas Separate elements in tuples, lists, sets, and dictionaries. It is also used to separate function
arguments and create multiple variable assignments.
Colons Define the body of control flow statements like if, else, for, while, and def.
Semicolons Separate multiple statements on a single line for brevity or to combine related statements.
Whitespace and indentation play an important role in Python’s syntax and structure. Python uses
indentation to define blocks of code and determine the scope of statements. The use of consistent
indentation is not only a matter of style but is required for the code to be valid and executable.
Concept Description
8
Indentation Indentation can be done using spaces or tabs, but it’s recommended to use spaces for
Methods better compatibility and readability. Mixing tabs and spaces can lead to syntax errors.
Indentation in Indentation is used to define the body of control flow statements like if, else, for, while,
Control Flow and def. The indented block of code following a colon (:) is executed when the control
flow condition is met. The indentation level must be the same for all statements within
the same block.
Whitespace Whitespace, including spaces, tabs, and newlines, is used to separate tokens and enhance
and Readability code readability. Excessive whitespace should be avoided, as it can hinder code
comprehension. Python ignores whitespace within parentheses, brackets, and braces,
allowing code formatting for improved readability.
Python Literals
1. String literals:
String literals can be formed by enclosing a text in the quotes. We can use both single as well as double
quotes to create a string.
Types of Strings:
a) Single-line String- Strings that are terminated within a single-line are known as Single line Strings.
Example:
1. text1='hello'
b) Multi-line String - A piece of text that is written in multiple lines is known as multiple lines string.
9
Example:
1. text1='hello\
2. user'
3. print(text1)
'hellouser'
Example:
1. str2='''''welcome
2. to
3. SSSIT'''
4. print str2
Output:
welcome
to
SSSIT
Numeric Literals are immutable. Numeric literals can belong to following four different numerical types.
Numbers( can be both Integers of unlimited Real numbers with In the form of a+bj where a forms
positive and negative) size followed by both integer and the real part and b forms the
with no fractional lowercase or uppercase fractional part eg: - imaginary part of the complex
part.eg: 100 L eg: 87032845L 26.2 number. eg: 3.14j
10
13. print(x, y, z, u)
14. print(float_1, float_2)
15. print(a, a.imag, a.real)
Output:
A Boolean literal can have any of the two values: True or False.
1. x = (1 == True)
2. y = (2 == False)
3. z = (3 == True)
4. a = True + 10
5. b = False + 10
6.
7. print("x is", x)
8. print("y is", y)
9. print("z is", z)
10. print("a:", a)
11. print("b:", b)
Output:
x is True
y is False
z is False
a: 11
b: 10
None is used to specify to that field that is not created. It is also used for the end of lists in Python.
1. val1=10
2. val2=None
3. print(val1)
4. print(val2)
Output:
11
10
None
V. Literal Collections.
Python provides the four types of literal collection such as List literals, Tuple literals, Dict literals, and
Set literals.
List:
List contains items of different data types. Lists are mutable i.e., modifiable.
The values stored in List are separated by comma(,) and enclosed within square brackets([]). We
can store different types of data in a List.
1. list=['John',678,20.4,'Peter']
2. list1=[456,'Andrew']
3. print(list)
4. print(list + list1)
Output:
Dictionary:
Example
Output:
Tuple:
Example
1. tup = (10,20,"Dev",[2,3,4])
12
2. print(tup)
Output:
Set:
1. set = {'apple','grapes','guava','papaya'}
2. print(set)
Output:
Developers often have a need to interact with users, either to get data or to provide some sort of result.
Python provides two inbuilt functions to read the input from the keyboard.
input ( prompt )
raw_input ( prompt )
input (): This function first takes the input from the user and converts it into a string. The type of the
returned object always will be <class ‘str’>. It does not evaluate the expression it just returns the complete
statement as String. For example, Python provides a built-in function called input which takes the input
from the user. When the input function is called it stops the program and waits for the user’s input. When
the user presses enter, the program resumes and returns what the user typed.
Syntax:
inp = input('STATEMENT')
Example:
1. >>> name = input('What is your name?\n'
2. >>> What is your name?
Ram
>>> print(name)
Ram
13
Output:
Output:
Output:
The primary prompt of the python console is the three greater than symbols
>>>
14
Accepting Input from Console User enters the values in the Console and that value is then used in the
program as it was required. To take input from the user we make use of a built-in function input().
# input
input1 = input()
# output
print(input1)
We can also typecast this input to integer, float, or string by specifying the input() function inside the
type.
1. Typecasting the input to Integer: There might be conditions when you might require integer input
from the user/Console, the following code takes two input(integer/float) from the console and typecasts
them to an integer then prints the sum.
# input
num1 = int(input())
num2 = int(input())
2. Typecasting the input to Float: To convert the input to float the following code will work out.
# input
num1 = float(input())
num2 = float(input())
3. Typecasting the input to String: All kinds of input can be converted to string type whether they are
float or integer. We make use of keyword str for typecasting.
we can also take input string by just writing input() function by default it makes the input string
# input
string = str(input())
# output
print(string)
# Or by default
string_default = input()
# output
print(string_default)
15
Python | Output using print() function
Python print() function prints the message to the screen or any other standard output device.
Example
In this example, we have created three variables integer, string and float and we are printing all the
variables with print() function in Python.
name = "John"
age = 30
print("Name:", name)
print("Age:", age)
Parameters:
In this code, we are passing two parameters name and age to the print function.
name = "Alice"
age = 25
String literals in Python’s print statement are primarily used to format or design how a specific string
appears when printed using the print() function.
16
\n: This string literal is used to add a new blank line while printing a statement.
Example
Output
GeeksforGeeks
is best for DSA Content.
The end keyword is used to specify the content that is to be printed at the end of the execution of the
print() function. By default, it is set to “\n”, which leads to the change of line after the execution of print()
statement.
Example
In this example, we are using print() with end and without end parameters.
# This print() function ends with "**" as set in the end argument.
print("Welcome to GFG")
Output
Python Constants
17
A Python Constant is a variable whose value cannot be changed throughout the program.
1. Python Constants and variable names should contain a combination of lowercase (a-z) or capital
(A-Z) characters, numbers (0-9), or an underscore ( ).
2. When using a Constant name, always use UPPERCASE, For example, CONSTANT = 50.
3. The Constant names should not begin with digits.
4. Except for underscore(_), no additional special character (!, #, ^, @, $) is utilized when declaring
a constant.
5. We should come up with a catchy name for the python constants. VALUE, for example, makes
more sense than V. It simplifies the coding process.
Example
Copy Code
Copy Code
# main.py file
import constant as const
Output
Python Variables
18
A Variable is a location that is named in order to store data while the program is being run.
In a programming language, Variables are words that are used to store values of any data type.
Syntax
1. A Variable’s name cannot begin with a number. Either an alphabet or the underscore character
should be used as the first character.
2. Variable names are case-sensitive and can include alphanumeric letters as well as the underscore
character.
3. Variable names cannot contain reserved terms.
4. The equal to sign ‘=’, followed by the variable’s value, is used to assign variables in Python.
There are few different methods to assign data elements to a Variable. The most common ones are
described below –
In this type, the data values are directly assigned to the Variables in the declaration statement.
Example
Copy Code
num = 10
numlist = [1, 3, 5, 7, 9]
str = 'Hello World'
print(num)
print(numlist)
print(str)
Output
10
[1, 3, 5, 7, 9]
Hello World
19
2. Changing the value of a Variable
Example
val = 50
print("Initial value:", val)
Output
Initial value: 50
Updated value: 100
In the above program, initially the value of Variable ‘val’ was 50. Later it was reassigned to a value of
100.
In Python, we can assign multiple values to multiple variables in the same declaration statement by using
the following method –
Example
Copy Code
print(name)
print(age)
print(city)
Output
20
David
27
New York
Example
Copy Code
a = b = 'Hello'
print('Value of a:', a)
print('Value of b:', b)
Output –
Value of a: Hello
Value of b: Hello
Python Keywords
Keywords are predefined, reserved words used in Python programming that have special meanings to the
compiler.
We cannot use a keyword as a variable name, function name, or any other identifier. They are used to
define the syntax and structure of the Python language.
All the keywords except True, False and None are in lowercase and they must be written as they are. The
list of all the keywords is given below.
21
as def from nonlocal while
Python Identifiers
Identifiers are the name given to variables, classes, methods, etc. For example,
language = 'Python'
Here, language is a variable (an identifier) which holds the value 'Python'.
We cannot use keywords as variable names as they are reserved names that are built-in to Python. For
example,
continue = 'Python'
score @core
return_value return
name1 1name
Things to Remember
22
Python is a case-sensitive language. This means, Variable and variable are
Consider the following illustration when defining and verifying the values of various data types.
1. a=10
2. b="Hi Python"
3. c = 10.5
4. print(type(a))
5. print(type(b))
6. print(type(c))
Output:
<type 'int'>
<type 'str'>
<type 'float'>
A variable can contain a variety of values. On the other hand, a person's id must be stored as an integer,
while their name must be stored as a string.
The storage method for each of the standard data types that Python provides is specified by Python. The
following is a list of the Python-defined data types.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
23
Numbers
Numeric values are stored in numbers. The whole number, float, and complex qualities have a place with
a Python Numbers datatype.
When a number is assigned to a variable, Python generates Number objects. For instance,
1. a=5
2. print("The type of a", type(a))
3.
4. b = 40.5
5. print("The type of b", type(b))
6.
7. c = 1+3j
8. print("The type of c", type(c))
9. print(" c is a complex number", isinstance(1+3j,complex))
Output:
24
Int: Whole number worth can be any length, like numbers 10, 2, 29, - 20, - 150, and so on. An
integer can be any length you want in Python. Its worth has a place with int.
Float: Float stores drifting point numbers like 1.9, 9.902, 15.2, etc. It can be accurate to within 15
decimal places.
Complex: An intricate number contains an arranged pair, i.e., x + iy, where x and y signify the
genuine and non-existent parts separately. The complex numbers like 2.14j, 2.0 + 2.3j, etc.
String
The sequence of characters in the quotation marks can be used to describe the string. A string can be
defined in Python using single, double, or triple quotes.
Example - 1
Output:
List
It is written inside [ ], and elements inside the list are separated by comma.
Example:
25
14. # List Concatenation using + operator
15. print (list1 + list1)
16.
17. # List repetation using * operator
18. print (list1 * 3)
Output:
Tuple
In many ways, a tuple is like a list. Tuples, like lists, also contain a collection of items from various data
types. A parenthetical space () separates the tuple's components from one another.
Because we cannot alter the size or value of the items in a tuple, it is a read-only data
structure(immutable).
Example:
Output:
<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
26
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)
Dictionary
A dictionary is a key-value pair set arranged in any order. It stores a specific value for each key, like an
associative array or a hash table. Value is any Python object, while the key can hold any primitive data
type.
The comma (,) and the curly braces are used to separate the items in the dictionary.
Output:
Boolean
True and False are the two default values for the Boolean type.
Ex:
Output:
27
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Set
The data type's unordered collection is Python Set. It is iterable, mutable(can change after creation), and
has remarkable components. The elements of a set have no set order; It might return the element's altered
sequence. Either a sequence of elements is passed through the curly braces and separated by a comma to
create the set or the built-in function set() is used to create the set. It can contain different kinds of values.
Ex:
Output:
Python Operators
Operators are special symbols that perform operations on variables and values. For example,
print(5 + 6) # 11
1. Arithmetic operators
2. Assignment Operators
3. Comparison Operators
4. Logical Operators
5. Bitwise Operators
28
6. Special Operators
Arithmetic operators are used to perform mathematical operations like addition, subtraction,
multiplication, etc. For example,
sub = 10 - 5 # 5
+ Addition 5+2=7
- Subtraction 4-2=2
* Multiplication 2 * 3 = 6
/ Division 4/2=2
// Floor Division 10 // 3 = 3
% Modulo 5%2=1
** Power 4 ** 2 = 16
# addition
print ('Sum: ', a + b)
# subtraction
print ('Subtraction: ', a - b)
# multiplication
print ('Multiplication: ', a * b)
# division
print ('Division: ', a / b)
# floor division
print ('Floor Division: ', a // b)
29
# modulo
print ('Modulo: ', a % b)
# a to the power b
print ('Power: ', a ** b)
Output
Sum: 9
Subtraction: 5
Multiplication: 14
Division: 3.5
Floor Division: 3
Modulo: 1
Power: 49
+ to add a and b
- to subtract b from a
* to multiply a and b
/ to divide a by b
// to floor divide a by b
% to get the remainder
** to get a to the power b
# assign 5 to x
var x = 5
+= Addition Assignment a += 1 # a = a + 1
-= Subtraction Assignment a -= 3 # a = a - 3
*= Multiplication Assignment a *= 4 # a = a * 4
30
/= Division Assignment a /= 3 # a = a / 3
%= Remainder Assignment a %= 10 # a = a % 10
# assign 5 to b
b=5
print(a)
# Output: 15
Similarly, we can use any other assignment operators according to the need.
Comparison operators compare two values/variables and return a boolean result: True or False. For
example,
a=5
b =2
Here, the > comparison operator is used to compare whether a is greater than b or not.
31
< Less Than 3 < 5 gives us True
b=2
# equal to operator
print('a == b =', a == b)
Output
a == b = False
a != b = True
a > b = True
a < b = False
a >= b = True
a <= b = False
Logical operators are used to check whether an expression is True or False. They are used in decision-
making. For example,
a=5
b=6
32
Here, and is the logical operator AND. Since both a > 2 and b >= 6 are True, the result is True.
Logical AND:
and a and b
True only if both the operands are True
Logical OR:
or a or b
True if at least one of the operands is True
Logical NOT:
not not a
True if the operand is False and vice-versa.
# logical OR
print(True or False) # True
# logical NOT
print(not True) # False
Bitwise operators act on operands as if they were strings of binary digits. They operate bit by bit, hence
the name.
In the table below: Let x = 10 (0000 1010 in binary) and y = 4 (0000 0100 in binary)
33
6. Python Special operators
Python language offers some special types of operators like the identity operator and the membership
operator. They are described below with examples.
Identity operators
In Python, is and is not are used to check if two values are located on the same part of the memory. Two
variables that are equal does not imply that they are identical.
is True if the operands are identical (refer to the same object) x is True
is not True if the operands are not identical (do not refer to the same object) x is not True
Here, we see that x1 and y1 are integers of the same values, so they are equal as well as identical. Same is
the case with x2 and y2 (strings).
But x3 and y3 are lists. They are equal but not identical. It is because the interpreter locates them
separately in memory although they are equal.
Membership operators
In Python, in and not in are the membership operators. They are used to test whether a value or variable is
found in a sequence (string, list, tuple, set and dictionary).
34
In a dictionary we can only test for presence of key, not the value.
Output
True
True
True
False
Here, 'H' is in x but 'hello' is not present in x (remember, Python is case sensitive).
Similarly,
1 is key and 'a' is the value in dictionary y. Hence, 'a' in y returns False.
Expressions in Python
An expression is a combination of operators and operands that is interpreted to produce some other value.
1. Constant Expressions: These are the expressions that have constant values only.
Example:
# Constant Expressions
35
x = 15 + 1.3
print(x)
Output
16.3
+ x+y Addition
– x–y Subtraction
* x*y Multiplication
/ x/y Division
// x // y Quotient
% x % y Remainder
** x ** y Exponentiation
Example:
# Arithmetic Expressions
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
36
3.3333333333333335
3. Integral Expressions: These are the kind of expressions that produce only integer results after all
computations and type conversions.
Example:
# 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:
# Floating Expressions
a = 13
b=5
c=a/b
print(c)
Output
2.6
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:
# Relational Expressions
a = 21
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)
Output
True
37
6. Logical Expressions: These are kinds of expressions that result in either True or False. It basically
specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal to 9. As we know it
is not correct, so it will return False. Studying logical expressions, we also come across some logical
operators which can be seen in logical expressions most often. Here are some logical operators in Python:
and P and Q It returns true if both P and Q are true otherwise returns false
Example:
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
7. Bitwise Expressions: These are the kind of expressions in which computations are performed at bit
level.
Example:
38
# 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
But when we combine different types of expressions or use multiple operators in a single expression,
operator precedence comes into play.
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:
# Multi-operator expression
a = 10 + 3 * 4
print(a)
39
b = (10 + 3) * 4
print(b)
c = 10 + (3 * 4)
print(c)
Output
22
52
22
Hence, operator precedence plays an important role in the evaluation of a Python expression.
In programming, type conversion is the process of converting data of one type to another. For example:
converting int data to str.
In certain situations, Python automatically converts one data type to another. This is known as implicit
type conversion.
integer_number = 123
float_number = 1.23
Output
Value: 124.23
40
Data Type: <class 'float'>
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("Sum:",num_sum)
print("Data type of num_sum:",type(num_sum))
Output
1. Type Conversion is the conversion of an object from one data type to another data type.
2. Implicit Type Conversion is automatically performed by the Python interpreter.
3. Python avoids the loss of data in Implicit Type Conversion.
4. Explicit Type Conversion is also called Type Casting, the data types of objects are converted
using predefined functions by the user.
5. In Type Casting, loss of data may occur as we enforce the object to a specific data type.
Arrays:
41
The Array is an idea of storing multiple items of the same type together, making it easier to calculate the
position of each element by simply adding an offset to the base value.
The Array can be handled in Python by a module named Array. It is useful when we must manipulate
only specific data values. The following are the terms to understand the concept of an array:
Index - The location of an element in an array has a numerical index, which is used to identify the
element's position. The index value is very much important in an Array.
Array Representation:
Array operations
The Array can be created in Python by importing the array module to the python program.
We can access the array elements using the respective indices of those elements.
Program code:
Here we give an example of how we access the elements of an array using its index value in Python. The
code is given below -
42
6. print("Forth element is:", a[3])
7. print("last element is:", a[-1])
8. print("Second last element is:", a[-2])
9. print("Third last element is:", a[-3])
10. print("Forth last element is:", a[-4])
11. print(a[0], a[1], a[2], a[3], a[-1],a[-2],a[-3],a[-4])
Output:
Arrays are mutable, and their elements can be changed similarly to lists.
Program code:
Here in this example, we can change or add or replace any element from the Array in Python. The code is
given below -
Output:
Now we compile the above code in python, and after successful compilation, we run it. Then the output is
given below -
43
array('i', [0, 2, 4, 6, 8, 8])
A combination of arrays saves a lot of time. The Array can reduce the overall size of the code. Using an
array, we can solve a problem quickly in any language. The Array is used for dynamic memory
allocation.
The elements can be deleted from an array using Python's del statement. If we want to delete any value
from the Array, we can use the indices of a particular element.
Output:
The length of an array is defined as the number of elements present in an array. It returns an integer value
that is equal to the total number of the elements present in that array.
Syntax
The syntax is -
1. len(array_name)
Array Concatenation
Example 1:
Output:
44
Example 2:
Output:
First element: 4
Second element: 7
Second last element: 22
45