SlideShare a Scribd company logo
PYTHON PROGRAMMING
2 April 2022 2
What is Python?
• Python is a popular programming language.
• It was created by Guido van Rossum, and released in 1991.
It is used for:
• Web development (server-side),
• Software development,
• Mathematics,
• System scripting.
2 April 2022 3
What is Python
• Python is a general purpose, dynamic, high-level, and interpreted programming language.
• It supports Object Oriented programming approach to develop applications.
• It is simple and easy to learn and provides lots of high-level data structures.
• Python is easy to learn yet powerful and versatile scripting language, which makes it attractive
for Application Development.
• Python's syntax and dynamic typing with its interpreted nature make it an ideal language for
scripting and rapid application development.
2 April 2022 4
What can Python do?
• Python can be used on a server to create web applications.
• Python can be used alongside software to create workflows.
• Python can connect to database systems.
• It can also read and modify files.
• Python can be used to handle big data and perform complex mathematics.
• Python can be used for rapid prototyping, or for production-ready software development.
2 April 2022 5
Why Python?
• Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc).
• Python has a simple syntax similar to the English language.
• Python has syntax that allows developers to write programs with fewer lines than some other
programming languages.
• Python runs on an interpreter system, meaning that code can be executed as soon as it is
written. This means that prototyping can be very quick.
• Python can be treated in a procedural way, an object-oriented way or a functional way.
2 April 2022 6
Why learn Python?
• Easy to use and Learn
• Expressive Language
• Interpreted Language
• Object-Oriented Language
• Open Source Language
• Extensible
• Learn Standard Library
• GUI Programming Support
• Integrated
• Embeddable
• Dynamic Memory Allocation
• Wide Range of Libraries and Frameworks
2 April 2022 7
Python Features
1) Easy 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.
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.
2 April 2022 8
Python Features
4) Cross-platform Language
•Python can run equallyon different platforms such as
Windows, Linux, UNIX, and Macintosh, etc. So, we can say that Python is a portable
language.
5) Free and Open Source
•Python is freely available for everyone. It is freely
available on its official website www.python.org
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.
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.
2 April 2022 9
Python Features
8) Large Standard Library
•It provides a vast range oflibraries for the various fields such as machine learning, web developer, and also for the
scripting. Django, flask, pyramids are the popular framework for Python web development.
9) GUI Programming Support
•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.
11. Embeddable
•The code of the other programming language can use in the Python source code.
12. Dynamic Memory Allocation
•In Python, we don't need to specify the data-type of the variable.
2 April 2022 10
Why the Name Python?
• 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.
• 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 Version List
Python Version Released Date Python Version Released Date
Python 1.0 January 1994 Python 2.7 July 3, 2010
Python 1.5 December 31, 1997 Python 3.0 December 3, 2008
Python 1.6 September 5, 2000 Python 3.1 June 27, 2009
Python 2.0 October 16, 2000 Python 3.2 February 20, 2011
Python 2.1 April 17, 2001 Python 3.3 September 29, 2012
Python 2.2 December 21, 2001 Python 3.4 March 16, 2014
Python 2.3 July 29, 2003 Python 3.5 September 13, 2015
Python 2.4 November 30, 2004 Python 3.6 December 23, 2016
Python 2.5 September 19, 2006 Python 3.7 June 27, 2018
Python 2.6 October 1, 2008 Python 3.8 October 14, 2019
2 April 2022 11
2 April 2022 12
Python Libraries and Frameworks
Python consists of vast libraries and various frameworks.
•TensorFlow - It is an artificial intelligence library which allows us to create large scale AI based
projects.
•Django - It is an open source framework that allows us to develop web applications. It is easy,
flexible, and simple to manage.
•Flask - It is also an open source web framework. It
is used to develop lightweight web
applications.
•Pandas - It is a Python library which is used to perform scientific computations.
•Keras - It is an open source library, which is used to work around the neural network.
2 April 2022 13
2 April 2022 14
1) Web Applications
• We can use Python to develop web applications. It provides libraries to handle internet
protocols such as HTML and XML, JSON, Email processing, request, beautifulSoup,
Feedparser, etc. One of Python web-framework named Django is used on Instagram.
• Django and Pyramid framework(Use for heavy applications)
• Flask and Bottle (Micro-framework)
• Plone and Django CMS (Advance Content management)
2 April 2022 15
2) Desktop GUI Applications
The GUI stands for the Graphical User Interface, which provides a smooth interaction to any
application. Python provides a Tk GUI library to develop a user interface.
•Tkinter or Tk
•wxWidgetM
•Kivy (used for writing multitouch applications )
•PyQt or Pyside
2 April 2022 16
3) Console-based Application
• Console-based applications run from the command-line or shell.
• These applications are computer program which are used commands to execute.
• This kind of application was more popular in the old generation of computers.
• Python can develop this kind of application very effectively. .
2 April 2022 17
4) Software Development
• Python is useful for the software development process. It works as a support language and can
be used to build control and management, testing, etc.
• SCons is used to build control.
• Buildbot and Apache Gumps are used for automated continuous compilation and testing.
• Round or Trac for bug tracking and project management.
2 April 2022 18
5) Scientific and Numeric
• This is the era of Artificial intelligence where the machine can perform the task the same as
the human.
• Python language is the most suitable language for Artificial intelligence or machine learning.
• Implementing machine learning algorithms require complex mathematical calculation.
• Python has many libraries for scientific and numeric such as Numpy, Pandas, Scipy, Scikit-
learn, etc.
• Few popular frameworks ofmachine libraries are given below.
• SciPy
• Scikit-learn
• NumPy
• Pandas
• Matplotlib
2 April 2022 19
6) Business Applications
• Business Applications differ from standard applications.
• E-commerce and ERP are an example of a business application.
• This kind of application requires extensively, scalability and readability, and Python provides
all these features.
• Python provides a Tryton platform which is used to develop the business application.
2 April 2022 20
7) Audio or Video-based Applications
• Python is flexible to perform multiple tasks and can be used to create multimedia applications.
• Some multimedia applications which are made by using Python are TimPlayer, cplay, etc.
• The few multimedia libraries are given below.
• Gstreamer
• Pyglet
• QT Phonon
2 April 2022 21
8) 3D CAD Applications
• The CAD (Computer-aided design) is used to design engineering related architecture.
• It is used to develop the 3D representation of a part of a system.
• Python can create a 3D CAD application by using the following functionalities.
• Fandango (Popular )
• CAMVOX
• HeeksCNC
• AnyCAD
• RCAM
2 April 2022 22
9) Enterprise Applications
• Python can be used to create applications that can be used within an Enterprise or an
Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.
2 April 2022 23
10) Image Processing Application
• Python contains many libraries that are used to work with the image. The image can be
manipulated according to our requirements.
• OpenCV
• Pillow
• SimpleITK
2 April 2022 24
How to Install Python (Environment Set-up)
Installation on Windows
•Visit the link https://www.python.org/downloads/
•to download the latest release of Python
•In this process, we will install Python 3.8.6 on our Windows operating system
•When we click on the above link, it will bring us the following page.
Step - 1: Select the Python's version to download.
Step - 2: Click on the Install Now Step - 3 Installation in Process
Step - 1: Select the Python's version to download.
2 April 2022 25
Step - 2: Click on the Install Now
• Double-click the executable file,
which is downloaded; the following
window will open. Select Customize
installation and proceed. Click on the
Add Path check box, it will set the
Python path automatically.
2 April 2022 26
Step - 3 Installation in Process
2 April 2022 27
Cont….
• Now, try to run python on the command prompt. Type the command python -
version in case of python3.
2 April 2022 28
Python
Developme
nt Cycle
2 April 2022 29
2 April 2022 30
Python Development Cycle
• Python's development cycle is dramatically shorter than that of traditional tools.
• In Python, there are no compile or link steps -- Python programs simply import modules at
runtime and use the objects they contain.
• Because of this, Python programs run
immediately after changes are made.
• And in cases where dynamic module reloading can be used, it's even possible to change and
reload parts of a running program without
stopping it at all.
2 April 2022 31
Python Syntax
Execute Python Syntax
•Python syntax can be executed by writing directly in the Command Line:
>>> print("Hello, World!") Hello, World!
•by creating a python file on the server, using the .py file extension, and running it
in the Command Line:
C:UsersYour Name>python myfile.py
Python Indentation
• Indentation refers to the spaces at the beginning of a code line.
• Where in other programming languages the indentation in code is for
readability only, the indentation in Python is very important.
• Python uses indentation to indicate a block of code.
Example
if5 > 2:
print("Five is greater than two!")
Note: Python will give you an error if you skip the
indentation:
2 April 2022 32
Input and Output in Python
How to Take Input from User in Python
•To do this Python provides an input() function.
Syntax:
input('prompt')
where prompt is an optional string that is displayed on the string at the
time of taking input.
2 April 2022 33
2 April 2022 34
Example 1: Python get user input with a message
# Taking input from the user name
= input("Enter your name: ")
# Output
print("Hello, " + name)
print(type(name))
Output:
Enter your name: GFG Hello,
GFG
<class 'str'>
2 April 2022 35
Example 2: Integer input in Python
# Taking input from the user as integer
num = int(input("Enter a number: "))
add = num + 1
# Output print(add)
Output:
Enter a number: 25 26
2 April 2022 36
Output using print() function
Syntax: print(value(s), sep= ‘ ‘, end = ‘n’, file=file, flush=flush)
Parameters:
•value(s) : Any value, and as many as you like. Will be converted to string
before printed
•sep=’separator’ : (Optional) Specify how to separate the objects, if there
is more
than one. Default :’ ‘
•end=’end’: (Optional) Specify what to print at the end. Default : ‘n’
•file : (Optional) An object with a write method. Default :sys.stdout
•flush : (Optional) A Boolean, specifying if the output is flushed (True) or
buffered (False). Default: False
•Returns: It returns output to the screen.
2 April 2022 37
String Literals
• 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.
• n : This string literal is used to add a new blank line while printing a statement.
• “” :An empty quote (“”) is used to print an empty line.
Example:
print(“ComputerScience n is best for DSA Content.")
Output:
ComputerScience
is best for DSA Content.
2 April 2022 38
end= ” ” statement
• 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: Python print() without new line.
# This line will automatically add a new line before the # next print statement
print (“St Martins is the best platform for DSA content")
# This print() function ends with "**" as set in the end argument.
print (" St Martins is the best platform for DSA content", end= "**") print("Welcome to
GFG")
Output:
St Martins is the best platform for DSA content
St Martins is the best platform for DSA content**Welcome to GFG
2 April 2022 39
Separator
• The print() function can accept any number of positional arguments.
• These arguments can be separated from each other using a “,” separator.
• These are primarily used for formatting multiple statements in a single print()
function.
Example:
b = "Engineering" print("St.Martin's", b , "College")
Output:
St.Martin's Engineering College
2 April 2022 40
Example: Python Print Output
# Python program to demonstrate #
print() method
print("GFG")
# code for disabling the softspace feature
print('G', 'F', 'G’)
Output
GFG G F G
2 April 2022 41
Formatting Output
Using formatted string literals
•We can use formatted string literals, by starting a string with f or
F before opening quotation marks or triple quotation marks.
•In this string, we can write Python expressions between { and } that
can refer to a variable or any literal value.
2 April 2022 42
Example: Python String formatting using F string
# Declaring a variable name = "Gfg"
# Output
print(f'Hello {name}! How are
you?’)
Output:
Hello Gfg! How are you?
2 April 2022 43
Using format()
• We can also use format() function to format our output to make it look
presentable.
• The curly braces { } work as placeholders.
• We can specify the order in which variables occur in the output.
2 April 2022 44
Example: Python string formatting using format() function
# Initializing variables a = 20
b = 10
# addition sum = a + b
# subtraction sub = a- b
# Output
print('The value of a is {} and b is {}'.format(a,b)) print('{2} is
the sum of {0} and {1}'.format(a,b,sum)) print('{sub_value} is
the subtraction of {value_a} and
{value_b}'.format(value_a = a , value_b = b, sub_value = sub))
Output:
The value of a is 20 and b is 10
30 is the sum of 20 and 10
10 is the subtraction of 20 and 10
2 April 2022 45
Using %Operator
• We can use ‘%’ operator. % values are replaced with zero or more value
of elements.
• Theformatting using% is similar to that of ‘printf ’
in the C programming language.
%d – integer
%f – float
%s – string
%x – hexadecimal
%o – octal
2 April 2022 46
Example:
# Taking input from the user
num = int(input("Enter a value: "))
add = num + 5
# Output
print("The sum is %d" %add)
Output:
Enter a value: 50 The sum is 55
2 April 2022 47
Python Comments
• Comments can be used to explain Python code.
• Comments can be used to make the code more readable.
• Comments can be used to prevent execution when testing code.
2 April 2022 48
Creating a Comment
• Comments starts with a #, and Python will ignore them:
Example
#This is a comment print("Hello, World!")
• Comments can be placed at the end of a line, and Python will ignore the
rest of the line:
Example
print("Hello, World!") #This is a comment
2 April 2022 49
Multi Line Comments
• Python does not really have a syntax for multi line comments.
• To add a multiline comment you could insert a # for each line:
Example
#This is a comment #written in
#more than just one line print("Hello, World!")
2 April 2022 50
Python Variables
Variables
•Variables are containers for storing data values.
Creating Variables
•Python has no command for declaring a variable.
•A variable is created the moment you first assign a value to it.
Example
x = 5
y = "Rajalingam" print(x)
print(y) Output
5
Rajalingam
2 April 2022 51
Cont…
• Variables do not need to be declared with any particular type, and can
even change type after they have been set.
Example
x = 4 # x is of type int
x = "Computer Science" # x is now of type str print(x)
Output:
4
Computer Science
2 April 2022 52
Casting Variable
• If you want to specify the data type of a variable, this can be done with
casting.
Example:
x = str(3) # x will be '3' y = int(3) # y will be 3
z = float(3) # z will be 3.0
Output:
3
3
3.0
2 April 2022 53
Get the Type
• You can get the data type of a variable with the type() function.
Example
x = 5
y = "Dr. B.Rajalingam" print(type(x)) print(type(y))
Output:
<class 'int'>
<class 'str'>
2 April 2022 54
Single or Double Quotes?
• String variables can be declared either by using single or double
quotes:
Example
x = “Rajalingam" # is the same as x = 'Rajalingam’
Print(x)
Output:
Rajalingam
2 April 2022 55
Case-Sensitive
• Variable names are case-sensitive.
Example
This will create two variables: a =
4
A = “Rajalingam"
#A will not overwrite a
Output:
4
Rajalingam
2 April 2022 56
Python Data Types
• In programming, data type is an important concept.
• Variables can store data of different types, and different types can do different things.
• Python has the following data types built-in by default, in these categories:
Text Type: str
Numeric Types: int, float, complex
Sequence Types: list, tuple, range
Mapping Type: dict
Set Types: set, frozenset
Boolean Type: bool
Binary Types: bytes, bytearray, memoryview
2 April 2022 57
Getting the Data Type
• You can get the data type of any object by using the type() function:
Example
Print the data type of the variable x: x = 5
print(type(x))
Output:
<class 'int'>
2 April 2022 58
Setting the Data Type
• In Python, the data type is set when you assign a value to a variable:
Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
2 April 2022 59
Example
Example 1
x = "Hello World" #display x:
print(x)
#display the data type of x:
print(type(x))
Output:
Hello World
<class 'str'>
2 April 2022 60
Example
Example 2
x = 20
#display x:
print(x)
#display the data type of x:
print(type(x))
Output:
20
<class 'int'>
2 April 2022 61
Example
Example 3
x = 20.5
#display x:
print(x)
#display the data type of x:
print(type(x))
Output:
20.5
<class 'float'>
2 April 2022 62
Example
Example 4
x = 1j #display x:
print(x)
#display the data type of x:
print(type(x))
Output:
lj
<class 'complex'>
2 April 2022 63
Example
Example 5
x = ["apple", "banana", "cherry"]
#display x:
print(x)
#display the data type of x:
print(type(x))
Output:
['apple', 'banana', 'cherry’]
<class 'list'>
2 April 2022 64
Example
Example 6
x = ("apple", "banana", "cherry")
#display x:
print(x)
#display the data type of x:
print(type(x))
Output:
('apple', 'banana', 'cherry’)
<class 'tuple'>
2 April 2022 65
Example
Example 7
x = range(6) #display x:
print(x)
#display the data type of x:
print(type(x))
Output:
range(0, 6)
<class 'range'>
2 April 2022 66
Example
Example 8
x = {"name" : "John", "age" : 36}
#display x:
print(x)
#display the data type of x:
print(type(x))
Output:
{'name': 'John', 'age': 36}
<class 'dict'>
2 April 2022 67
Example
Example 9
x = {"apple", "banana", "cherry"}
#display x:
print(x)
#display the data type of x:
print(type(x))
Output:
{'cherry', 'banana', 'apple’}
<class 'set'>
2 April 2022 68
Example
Example 10
x = frozenset({"apple", "banana", "cherry"})
#display x:
print(x)
#display the data type of x: print(type(x))
Output:
frozenset({'apple', 'cherry', 'banana’})
<class 'frozenset'>
2 April 2022 69
Example
Example 11 x = True
#display x:
print(x)
#display the data type of x:
print(type(x))
Output:
True
<class 'bool'>
2 April 2022 70
Example
Example 12
x = b"Hello" #display x:
print(x)
#display the data type of x:
print(type(x))
Output:
b'Hello’
<class 'bytes'>
2 April 2022 71
Example
Example 13
x = bytearray(5) #display x:
print(x)
#display the data type of x: print(type(x))
Output:
bytearray(b'x00x00x00x00x00’)
<class 'bytearray'>
2 April 2022 72
Example
Example 14
x = memoryview(bytes(5)) #display
x:
print(x)
#display the data type of x:
print(type(x))
Output:
<memory at 0x14cff7cd9a00>
<class 'memoryview'>
2 April 2022 73
Setting the Specific Data Type
Example Data Type
x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = range(6) range
x = dict(name="John", age=36) dict
x = set(("apple", "banana", "cherry")) set
x = frozenset(("apple", "banana", "cherry")) frozenset
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
2 April 2022 74
Python Numbers
There are three numeric types in Python:
• int
• float
• complex
Variables of numeric types are created when you assign a value to them:
Example
x = 1 # int
y = 2.8 # float
z = 1j # complex
2 April 2022 75
Python Numbers
• To verify the type of any object in Python, use the type() function:
Example
x = 1
y = 2.8
z = 1j print(type(x)) print(type(y))
print(type(z))
Output:
<class 'int'>
<class 'float'>
<class 'complex'>
2 April 2022 76
Int
•Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length.
Example
Integers:
x = 1
y = 35656222554887711
z = -3255522
print(type(x)) print(type(y)) print(type(z))
Output
<class 'int'>
<class 'int'>
<class 'int'>
2 April 2022 77
Float
• Float, or "floating point number" is a number, positive or negative, containing one or more
decimals.
Example Floats:
x = 1.10
y = 1.0
z = -35.59
print(type(x)) print(type(y)) print(type(z))
Output
<class 'float'>
<class 'float'>
<class 'float'>
2 April 2022 78
Complex
•Complex numbers are written with a "j" as the imaginary part:
Example
Complex:
x = 3+5j
y = 5j z = -5j
print(type(x)) print(type(y)) print(type(z))
Output
<class 'complex'>
<class 'complex'>
<class 'complex'>
2 April 2022 79
Type Conversion
• You can convert from one type to another with the int(), float(), and
complex() methods:
Example
Convert from one type to another:
x = 1 # int
y = 2.8 # float
z = 1j # complex #convert
from int to float: a = float(x)
#convert from float to int: b =
int(y)
#convert from int to complex:
c = complex(x)
print(a) print(b) print(c)
print(type(a)) print(type(b))
print(type(c))
Output
1.0
2 (1+0j)
<class 'float'>
<class 'int'>
<class 'complex'>
2 April 2022 80
Random Number
• Python does not have a random() function to make a random number, but Python has a built-
in module called random that can be used to make random numbers:
Example
Import the random module, and display a random number between 1 and 9: import random
print(random.randrange(1, 10))
Output: 7
2 April 2022 81
Python Casting
Specify a Variable Type:
•There may be times when you want to specify a type on to a variable. This can be done with
casting.
Casting in python is therefore done using constructor functions:
•int() - constructs an integer number from an integer literal, a float literal (by removing all
decimals), or a string literal (providing the string represents a whole number)
•float()- constructs a float number from an integer literal, a
float literal or a string literal
(providing the string represents a float or an integer)
•str() - constructs a string from a wide variety of data types, including strings, integer literals
and float literals.
2 April 2022 82
Example: Integers
x = int(1)
y = int(2.8)
z = int("3")
print(x)
print(y)
print(z)
Output:
1
2
3
2 April 2022 83
Example: Floats
x = float(1) y
= float(2.8) z =
float("3")
w = float("4.2")
print(x)
print(y)
print(z)
print(w)
Output:
1.0
2.8
3.0
4.2
2 April 2022 84
Example: Strings
x = str("s1")
y = str(2)
z = str(3.0)
print(x)
print(y)
print(z)
Output
s1 2
3.0
2 April 2022 85
Python Operators
• Operators are used to perform operations on variables and values.
• In the example below, we use the + operator to add together two values:
Example
• print(10 + 5)
2 April 2022 86
Python divides the operators
• Arithmetic operators
• Assignment operators
• Comparison operators
• Logical operators
• Identity operators
• Membership operators
• Bitwise operators
2 April 2022 87
Python Arithmetic Operators
• Arithmetic operators are used with numeric values to perform common mathematical
operations:
Operator Name Example
+ Addition x + y
- Subtraction x - y
* Multiplication x * y
/ Division x / y
% Modulus x % y
** Exponentiation x ** y
/ / Floor division x / / y
2 April 2022 88
Python Assignment Operators
• Assignment operators are used to assign values to variables:
Operator Example Same As
= x = 5 x = 5
+= x += 3 x = x + 3
-= x -= 3 x = x - 3
*= x *= 3 x = x * 3
/ = x / = 3 x = x / 3
%= x %= 3 x = x % 3
/ / = x / / = 3 x = x / / 3
**= x **= 3 x = x ** 3
&= x &= 3 x = x & 3
| = x | = 3 x = x | 3
^= x ^= 3 x = x ^ 3
>>= x >>= 3 x = x >> 3
<<= x <<= 3 x = x << 3
2 April 2022 89
Python Comparison Operators
• Comparison operators are used to compare two values:
Operator Name Example
== Equal x == y
!= Not equal x != y
> Greater than x > y
< Less than x < y
>= Greater than or equal
to
x >= y
<= Less than or equal to x <= y
2 April 2022 90
Python Logical Operators
• Logical operators are used to combine conditional statements:
Operator Description Example
and Returns True if both statements are
true
x < 5 and x < 10
or Returns True if one of the statements
is true
x < 5 or x < 4
not Reverse the result, returns False if the
result is true
not(x < 5 and x < 10)
2 April 2022 91
Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are actually
the same object, with the same memory location:
Operator Description Example
is
Returns True if both variables are the
same object
x is y
is not
Returns True if both variables are not
the same object
x is not y
2 April 2022 92
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object:
Operator Description Example
in
Returns True if a sequence with the specified
value is present in the object
x in y
not in
Returns True if a sequence with the specified
value is not present in the object
x not in y
2 April 2022 93
Python Bitwise Operators
• Bitwise operators are used to compare (binary) numbers:
Operator Name Description
& AND Sets each bit to 1 if both bits are 1
| OR Sets each bit to 1 if one of two bits is 1
^ XOR Sets each bit to 1 if only one of two bits is 1
~ NOT Inverts all the bits
<< Zero fill left
shift
Shift left by pushing zeros in from the right and let the leftmost
bits fall off
>> Signed right
shift
Shift right by pushing copies of the leftmost bit in from the left,
and let the rightmost bits fall off
2 April 2022 94
Expressions in Python
• 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.
• We have many different types of expressions in Python.
2 April 2022 95
1. Constant Expressions
• These are the expressions that have constant values only.
Example:
# Constant Expressions x = 15 + 1.3
print(x)
Output
16.3
2 April 2022 96
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.
2 April 2022 97
Cont…
Operators Syntax Functioning
+ x + y Addition
– x – y Subtraction
* x * y Multiplication
/ x / y Division
/ / x / / y Quotient
% x % y Remainder
** x ** y Exponentiation
2 April 2022 98
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
3.3333333333333335
2 April 2022 99
3. Integral Expressions
• These are the kind of expressions that produce only integer results after all
computations and type conversions.
# Integral Expressions a = 13
b = 12.0
c = a + int(b) print(c)
Output
25
2 April 2022 100
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
2 April 2022 101
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.
2 April 2022 102
Example
# Relational Expressions
a = 21
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)
Output
True
2 April 2022 103
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.
2 April 2022 104
Cont…
Operator Syntax Functioning
and P and Q
It returns true if both P and Q are true otherwise returns
false
or P or Q It returns true if at least one of P and Q is true
not not P It returns true if condition P is false
2 April 2022 105
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
2 April 2022 106
7. Bitwise 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
2 April 2022 107
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
2 April 2022 108
Decision Structures in Python
• There comes a point in your life where you need to decide what steps should
be taken and based on that you decide your next decisions.
Python has the following decision-making statements:
• if statements
• if-else statements
• if-elif ladder
• Nested statements
2 April 2022 109
Python Conditions and If statements
• Python supports the usual logical conditions from mathematics:
• Equals: a == b
• Not Equals: a != b
• Less than: a < b
• Less than or equal to: a <= b
• Greater than: a > b
• Greater than or equal to: a >= b
• These conditions can be used in several ways, most commonly in "if statements" and loops.
• An "if statement" is written by using the if keyword.
2 April 2022 110
Python if statement
• if statement is the most simple form of decision-making statement.
• It takes an expression and checks if the expression evaluates to True then the block of
code in if statement will be executed.
• If the expression evaluates to False, then the block of code is skipped.
Syntax:
if( expression ): Statement 1
Statement 2
…
Statement n
2 April 2022 111
2 April 2022 112
if statement
Example 1:
a = 20 ; b = 20
if ( a == b ):
print( “a and b are equal”)
print(“If block ended”)
Output:
a and b are equal If
block ended
Example 2:
num = 5
if ( num >= 10):
print(“num is greater than 10”)
print(“if block ended”)
Output:
If block ended
2 April 2022 113
Python if-else statement
• From the name itself, we get the clue that the if-else statement checks the
expression and executes the if block when the expression is True otherwise it
will execute the else block of code.
• The else block should be right after if block and it is executed when the
expression is False.
Syntax:
if( expression ):
Statement else: Statement
2 April 2022 114
2 April 2022 115
if-else statement
Example 1:
number1 = 20 ; number2 = 30 if(number1 >
number2 ):
print(“number 1 is greater than number 2”)
else:
print(“number 2 is greater than number 1”)
Output:
number 2 is greater than number 1
Example 1:
if (5>10):
print(5) else:
print(10)
else:
print(“End”)
Output:
SyntaxError: invalid syntax
Python if-elif ladder
Syntax:
if( expression1 ):
statement
elif (expression2 ) :
statement
elif(expression3 ):
statement
.
.
else:
stat2eAmpriel 2n0t22 116
• You might have heard of the else-if statements in other languages like C/C++ or Java.
• In Python, we have an elif keyword to chain multiple conditions one after another.
With elif ladder, we can make complex decision-making statements.
• The elif statement helps you to check multiple expressions and it executes
the code as soon
as one of the conditions evaluates to True.
2 April 2022 117
2 April 2022 118
Python if-elif ladder
Example: 1
print(“Select your ride:”) print(“1.
Bike”)
print(“2. Car”)
print(“3. SUV”) choice = int( input()
) if( choice == 1 ):
print( “You have selected Bike” )
elif( choice == 2 ):
print( “You have selected Car” )
elif( choice == 3 ):
print( “You have selected SUV” )
else:
print(“Wrong choice!“)
Output 1:
Select your ride:
1.Bike
2.Car
3.SUV 3
You have selected SUV
Output 2:
Select your ride:
1.Bike
2.Car
3.SUV 10
Wrong choice!
2 April 2022 119
Python Nested if statement
• In very simple words, Nested if statements is an if statement inside another if statement.
• Python allows us to stack any number of if
statements inside the block of another if
statements.
• They are useful when we need to make a series of decisions.
Syntax:
if (expression): if(expression): Statement of nested if
else:
Statement of nested if else Statement of outer if Statement outside if block
2 April 2022 120
2 April 2022 121
Nested if statement
Example :
num1 = int( input()) num2 = int( input())
if( num1>= num2): if(num1 == num2):
print(f'{num1} and {num2} are equal') else:
print(f'{num1} is greater than
{num2}')
else:
print(f'{num1} is smaller than {num2}')
Output 1:
10
20
10 is smaller than 20
Output 2:
5
5
5 and 5 are equal
2 April 2022 122
If Statement
Example
a = 33
b = 200
if b > a:
print("b is greater than a")
Output:
b is greater than a
2 April 2022 123
Indentation
• Python relies on indentation (whitespace at the beginning of a line) to define scope in the
code. Other programming languages often use curly-brackets for this purpose.
Example
• If statement, without
indentation (will raise an error):
a = 33
b = 200
if b > a:
print("b is greater than a")
Output:
File "demo_if_error.py", line 4 print("b is greater than a")
^
IndentationError: expected an indented block
2 April 2022 124
Elif
The elif keyword is pythons way of saying "if the previous conditions were not true, then try
this condition".
Example
a = 33
b = 33
if b > a:
print("b is greater than a") elif a == b:
print("a and b are equal")
Output:
a and b are equal
2 April 2022 125
Else
• The else keyword catches anything which isn't caught by the preceding conditions.
Example
a = 200
b = 33
ifb > a:
print("b is greater than a") elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
Output:
a is greater than b
2 April 2022 126
Example
You can also have an else without the elif:
Example
a = 200
b = 33
if b > a:
print("b is greater than a") else:
print("b is not greater than a")
Output:
b is not greater than a
2 April 2022 127
Short Hand If
• If you have only one statement to execute, you can put it on the same line as the if statement.
Example
• One line if statement:
a = 200
b = 33
if a > b: print("a is greater than b")
Output:
"a is greater than b"
2 April 2022 128
Short Hand If ... Else
If you have only one statement to execute, one for if, and one for else, you can put it all on the
same line:
Example
One line if else statement: a = 2
b = 330
print("A") if a > b else print("B")
Output
B
2 April 2022 129
Cont…
• You can also have multiple else statements on the same line:
Example
• One line if else statement, with 3 conditions:
a = 330
b = 350
print("A") if a > b else print("=") if a == b else print("B")
Output:
B
2 April 2022 130
And
• The and keyword is a logical operator, and is used to combine conditional statements:
Example
• Test if a is greater than b, AND if c is greater than a:
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are True")
Output:
Both conditions are True
2 April 2022 131
Or
• The or keyword is a logical operator, and is used to combine conditional statements:
Example
• Test if a is greater than b, OR if a is greater than c:
a = 200
b = 33
c = 500
if a > b or a > c:
print("At least one of the conditions is True")
Output
At least one of the conditions is True
2 April 2022 132
Nested If
• You can have if statements inside if statements, this is called nested if statements.
Example
x = 41
if x > 10: print("Above ten,") if x > 20:
print("and also above 20!") else:
print("but not above 20.")
Output
Above ten,
and also above 20!
2 April 2022 133
The pass Statement
• if statements cannot be empty, but if you for some reason have an if statement with no
content, put in the pass statement to avoid getting an error.
a = 33
b = 10
ifb > a: pass
# having an empty if statement like this, would raise an error without
the pass statement
2 April 2022 134
Python Strings
Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks.
'hello' is the same as "hello".
You can display a string literal with the print() function: #You can use double or single quotes:
print("Hello") print('Hello')
2 April 2022 135
Assign String to a Variable
• Assigning a string to a variable is done with the variable name
followed by an equal sign and the string:
Example
a = "Hello" print(a)
Output:
Hello
2 April 2022 136
Multiline Strings
• You can assign a multiline string to a
variable by using three quotes:
Example
• You can use three double quotes:
Program:
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua."""
print(a)
Output:
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut
labore et dolore magna aliqua.
Or three single quotes: Program:
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
Output:
Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.
2 April 2022 137
Strings are Arrays
• Like many other popular programming languages, strings in Python are arrays of bytes
representing unicode characters.
• However, Python does not have a character data type, a single character is simply a string with
a length of 1.
• Square brackets can be used to access elements of the string.
Example:
Note: Get the character at position 1 (remember that the first character has the position 0): a =
"Hello, World!"
print(a[1])
Output:
e
2 April 2022 138
Looping Through a String
• Since strings are arrays, we can loop through the characters in a string, with a
for loop.
Example
• Loop through the letters in the word "banana": for x in "banana":
print(x)
Output:
b a n a n a
2 April 2022 139
String Length
• To get the length of a string, use the len() function.
Example
• The len() function returns the length of a string:
a = "Hello, World!" print(len(a))
Output:
13
2 April 2022 140
Check String
To check if a certain phrase or character is present in a string, we can use the
keyword in.
Example
Check if "free" is present in the following text:
txt = "The best things in life are free!" print("free" in txt)
Output:
True
2 April 2022 141
Cont…
Use it in an if statement: Example
Print only if "free" is present:
Example:
txt = "The best things in life are
free!" if "free" in txt:
print("Yes, 'free' is present.")
Output:
Yes, 'free' is present.
2 April 2022 142
Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use
the keyword not in.
Example
Check if "expensive" is NOT present in the following text: txt = "The best things in life
are free!"
print("expensive" not in txt)
Output:
True
2 April 2022 143
String Comparison in Python
Method 1: Using Relational Operators
Method 2: Using is and is not
Method 3: Creating a user-defined function
2 April 2022 144
Method 1: Using Relational Operators
• The relational operators compare the Unicode values of the characters of the strings from the
zeroth index till the end of the string.
• It then returns a boolean value according to the operator used.
Example:
“Geek” == “Geek” will return True as the Unicode of all the characters are equal In case
of “Geek” and “geek” as the unicode of G is u0047 and of
g is u0067
“Geek” < “geek” will return True and
“Geek” > “geek” will return False
2 April 2022 145
Example
print("Geek" == "Geek")
print("Geek" < "geek")
print("Geek" > "geek")
print("Geek" != "Geek")
Output
True True False False
2 April 2022 146
Method 2: Using is and is not
• The same is the case for != and is not.
Example:
str1 = "Geek" str2 = "Geek"
str3 = str1
print("ID of str1 =", hex(id(str1)))
print("ID of str2 =", hex(id(str2)))
print("ID of str3 =", hex(id(str3)))
print(str1 is str1)
print(str1 is str2) print(str1 is str3)
str1 += "s“
str4 = "Geeks"
• The == operator compares the values of both the operands and checks for value equality.
• Whereas is operator checks whether both the operands refer to the same object or not.
print("nID of changed str1 =", hex(id(str1)))
print("ID of str4 =", hex(id(str4)))
print(str1 is str4)
Output
ID of str1 = 0x7f6037051570 ID of
str2 = 0x7f6037051570 ID of str3 =
0x7f6037051570 True
True True
ID of changed str1 = 0x7f60356137d8
ID of str4 = 0x7f60356137a0
False
2 April 2022 147
Method 3: Creating a user-defined function.
• By using relational operators we can only compare the strings by their unicodes.
• In order to compare two strings according to some other parameters, we can make user-defined functions.
• In the following code, our user-defined function will compare the strings based upon the number of digits.
Example:
# function to compare string
# based on the number of digits
def compare_strings(str1, str2):
count1 = 0
count2 = 0
for i in range(len(str1)):
if str1[i] >= "0" and str1[i] <= "9":
count1 += 1
for i in range(len(str2)):
if str2[i] >= "0" and str2[i] <= "9": count2 += 1
return count1 == count2 print(compare_strings("123",
"12345")) print(compare_strings("12345", "geeks"))
print(compare_strings("12geeks", "geeks12"))
Output
False
False
True
2 April 2022 148
Python Logical Operators
Python has three logical operators:
• and
• or
• not
2 April 2022 149
The and operator
The and operator checks whether two conditions are both True simultaneously: Example:
a and b
It returns True if both conditions are True. And it returns False if either the condition a
or b is
False.
>>> price = 9.99
>>> price > 9 and price < 10 True
The result is True because the price is greater than 9 and less than 10.
>>> price > 10 and price < 20 False
In this example, the condition price > 10 returns False while the second condition price < 20
returns True.
2 April 2022 150
Cont…
a b a and b
True True True
True False False
False False False
False True False
The following table illustrates the result of the and operator when combining two conditions:
2 April 2022 151
The or operator
Similar to the and operator, the or operator checks multiple conditions. But it returns True
when either or both of individual conditions are True:
Example:
a or b
The following table illustrates the result of the or operator when combining two conditions:
The or operator returns False only when both conditions are False.
a b a or b
True True True
True False True
False True True
False False False
2 April 2022 152
Cont…
The following example shows how to use the or operator:
>>> price = 9.99
>>> price > 10 or price < 20
>>> True
In this example, the price < 20 returns True, therefore, the whole expression returns True.
The following example returns False because both conditions evaluate to False:
>>> price = 9.99
>>> price > 10 or price < 5 False
2 April 2022 153
The not operator
The not operator applies to one condition.
And it reverses the result of that condition, True becomes False and False becomes True.
Example
not a
If the condition is True, the not operator returns False and vice versa. The following
table illustrates the result of the not operator:
a not a
True False
False True
2 April 2022 154
Cont…
The following example uses the not operator.
Since the price > 10 returns False, the not price > 10 returns True:
>>> price = 9.99
>>> not price > 10
O/P
True
Here is another example that combines the not and the and operators:
>>> not (price > 5 and price < 10) O/P
False
2 April 2022 155
Boolean Variables
• In programming you often need to know if an expression is True or False.
• You can evaluate any expression in Python, and get one of two answers, True or False.
• When you compare two values, the expression is evaluated and Python returns the Boolean
answer:
Example
print(10 > 9)
print(10 == 9)
print(10 < 9)
Output
True False False
2 April 2022 156
Example
Print a message based on whether the condition is True or False:
Example
a = 200
b = 33
if b > a:
print("b is greater than a") else:
print("b is not greater than a")
Output
b is not greater than a
2 April 2022 157
Evaluate Values and Variables
•The bool() function allows you to evaluate any value, and give you True or False in return,
Example
•Evaluate a string and a number: print(bool("Hello")) print(bool(15))
Output
True True
Example
Evaluate two variables:
x = "Hello" y = 15
print(bool(x))
print(bool(y))
Output
True
True
2 April 2022 158
Repetition Structures in Python
• Repetition statements are called loops and are used to repeat the same code multiple times in
succession or allowing a set of statements to repeat until stopped!.
Python has two types of loops: Condition-Controlled and Count-Controlled.
• Condition-Controlled loop uses a true/false condition to control the number of times that it
repeats.
• While is Condition-Controlled loop.
• 'for' loop is known as a Count-Controlled loop.
• It repeats a specific number of times.
• We can use 'range' function to simplifies count-controlled for loops.
2 April 2022 159
Repetition Statements
• Repetition statements are called loops, and are used to repeat the same code multiple times in
succession.
• Basic syntax:
while condition:
statement(s) # notice the indent from of this line relative to the while Count-Controlled
loop repeats a specific number of times - for.
• Basic syntax:
for variable in [value1, value2, etc.]:
statement(s) # notice the indent from of this line relative to the for
2 April 2022 160
Repetition Structures
• Python provides three ways for executing the loops.
• While all the ways provide similar basic functionality, they differ in their syntax and condition
checking time.
While Loop:
•In python, while loop is used to
execute a block of condition is
satisfied.
statements repeatedly until a given
Syntax :
while expression:
statement(s)
2 April 2022 161
Cont…
• All the statements indented by the same number of character spaces after a programming
construct are considered to be part of a single block of code.
• Python uses indentation as its method of grouping statements.
Example:
# Python program to illustrate
# while loop
count = 0
while (count < 3):
count = count + 1 print("Hello
Geek")
Output:
Hello Geek
Hello Geek
Hello Geek
2 April 2022 162
Using else statement with while loops
• while loop executes the block until a condition is satisfied.
• When the condition becomes false, the statement immediately after the loop is executed.
• The else clause is only executed when your while condition becomes false.
• If you break out of the loop, or if an exception is raised, it won’t be executed.
while loop like this are similar
while condition:
# execute these statements
else:
# execute these statements
#Python program to illustrate
# combining else with while
count = 0
while (count < 3):
count = count + 1
print("Hello Geek")
else:
print("In Else Block")
Output:
Hello Geek
Hello Geek
Hello Geek
In Else Block
2 April 2022 163
Examples:
Condition-Controlled (while) loop:
x=1
while x<=5:
print ('I will repeat 5 times')
x=x+1
Outputs:
I will repeat 5 times
I will repeat 5 times
I will repeat 5 times
I will repeat 5 times
I will repeat 5 times
2 April 2022 164
For loops:
syntax:
for variable in [value1, value2, value
3etc.]: statement(s)
Example1:
for x in (1,2,3): print(x)
Output:
1
2
3
2 April 2022 165
Python Loops
• Python has two primitive loop commands:
• while loops
• for loops
The while Loop
• With the while loop we can execute a set of statements as long as a condition is true.
Example
Print i as long as i is less than 6: i = 1
while i < 6: print(i)
i += 1
Output
1
2
3
4
5
2 April 2022 166
The break Statement
•With the break statement we can stop the loop even if the while condition is true:
Example
•Exit the loop when i is 3: i = 1
while i < 6: print(i)
if(i == 3): break
i += 1
Output
1
2
3
2 April 2022 167
The continue Statement
• With the continue statement we can stop the current iteration, and continue with the next:
Example
• Continue to the next iteration if i is 3:
i = 0
while i < 6: i += 1
ifi == 3:
continue print(i)
# Note that number 3 is missing in the result
2 April 2022 168
The else Statement
while i < 6: print(i)
i += 1
else:
print("i is no longer less than 6")
•With the else statement we can run a block of code once when the condition no longer is true:
Example
•Print a message once the condition is false: i = 1
Output
1
2
3
4
5
i is no longer less than 6
2 April 2022 169
Python For Loops
• A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set,
or a string).
• This is less like the for keyword in other programming languages, and works more like an
iterator method as found in other object-orientated programming languages.
• With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc.
Example
• Print each fruit in a fruit list:
fruits = ["apple", "banana", "cherry"]
for x in fruits: print(x)
Output
apple banana cherry
2 April 2022 170
Looping Through a String
•Even strings are iterable objects, they contain a sequence of characters:
Example
•Loop through the letters in the word "banana": for x in "banana":
print(x)
Output
b
a n a n a
2 April 2022 171
The break Statement
With the break statement we can stop the loop before it has looped through all the items:
Example
Exit the loop when x is "banana": fruits = ["apple", "banana", "cherry"] for x in fruits:
print(x)
if x == "banana":
break
Output
apple banana
2 April 2022 172
The continue Statement
• With the continue statement we can stop the current iteration of the loop, and
continue with the next:
Example
#Do not print banana:
fruits = ["apple", "banana", "cherry"] for x in fruits:
if x == "banana":
continue
print(x)
Output
apple
cherry
2 April 2022 173
The range() Function
• To loop through a set of code a specified number of times, we can use the range() function,
• The range() function returns a sequence of numbers, starting from 0 by default, and
increments by 1 (by default), and ends at a specified number.
Example
• Using the range() function:
for x in range(6):
print(x)
Output:
0
1
2
3
4
5
2 April 2022 174
Cont…
Example
•Using the start parameter:
for x in range(2, 6): print(x)
Output
2
3
4
5
2 April 2022 175
Cont…
Example
•Increment the sequence with 3 (default is 1):
for x in range(2, 30, 3):
print(x)
Output
2
5
8
11
14
17
20
23
26
29
2 April 2022 176
Else in For Loop
The else keyword in a for loop specifies a block of code to be executed when the loop is finished:
Example
•Print all numbers from 0 to 5, and print a message when the loop has ended:
for x in range(6): print(x)
else:
print("Finally finished!")
Output
0
1
2
3
4
5
Finally finished!
2 April 2022 177
Nested Loops
• A nested loop is a loop inside a loop.
• The "inner loop" will be executed one time for each iteration of the "outer loop":
Example
Print each adjective for every fruit: adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"] for x in adj:
for y in fruits:
print(x, y)
Output
red apple red banana
red cherry
big apple big banana big cherry tasty apple tasty banana tasty cherry
2 April 2022 178
The pass Statement
• for loops cannot be empty, but if you for some reason have a for loop with no
content, put in the pass statement to avoid getting an error.
Example
for x in [0, 1, 2]: pass
# having an empty for loop like this, would raise an error without the pass statement
2 April 2022 179
Python Data Types
• 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, data types
are actually classes and variables are instance (object) of these classes.
Following are the standard or built-in data type of Python:
• Numeric
• Sequence Type
• Boolean
• Set
• Dictionary
2 April 2022 180
Python Data Types
• In programming, data type is an important concept.
• Variables can store data of different types, and different types can do different things.
• Python has the following data types built-in by default, in these categories:
Text Type str
Numeric Types int, float, complex
Sequence Types list, tuple, range
Mapping Type dict
Set Types set, frozenset
Boolean Type bool
Binary Types bytes, bytearray, memoryview
2 April 2022 181
Setting the Data Type
• In Python, the data type is set when you assign a value to a variable:
Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex
x = ["apple", "banana", "cherry"] list
x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
2 April 2022 182
2 April 2022 183
Numeric
• In Python, numeric data type represent the data which has numeric value.
• Numeric value can be integer, floating number or even complex numbers.
• These values are defined as int, float and complex class in Python.
Integers –
• This value is represented by int class.
• It contains positive or negative whole numbers (without fraction or decimal).
• In Python there is no limit to how long an integer value can be.
Float –
• This value is represented by float class.
• It is a real number with 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 –
• Complex number is represented by complex class.
• It is specified as (real part) + (imaginary part)j. For example – 2+3j
2 April 2022 184
Example
# Python program to
# demonstrate numeric value
a = 5
print("Type of a: ", type(a)) b =
5.0
print("nType of b: ", type(b))
c = 2 + 4j
print("nType of c: ", type(c))
Output:
Type of a: <class 'int'>
Type of b: <class 'float'>
Type of c: <class
'complex'>
2 April 2022 185
Sequence Type
• In Python, sequence is the ordered collection of similar or different data types.
• Sequences allows to store multiple values in an organized and efficient fashion.
• There are several sequence types in Python –
• String
• List
• Tuple
2 April 2022 186
1) String
• In Python, Strings are arrays of bytes representing Unicode characters.
• A string is a collection of one or more characters put in a single quote, double-
quote or triple quote.
• In python there is no character data type, a character is a string of length one.
• It is represented by str class.
Creating String
• Strings in Python can be created using single quotes or double quotes or even
triple quotes.
2 April 2022 187
Example
# Python Program for # Creation of String #
Creating a String
# with single Quotes
String1 = 'Welcome to the CSE World' print("String
with the use of Single Quotes: ") print(String1)
# Creating a String # with double Quotes
String1 = "I'm a Professor"
print("nString with the use of Double Quotes: ")
print(String1)
print(type(String1))
# Creating a String # with triple Quotes
String1 = '''I'm a Professor and I live in a world of “CSE"'''
print("nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))
# Creating String with triple # Quotes allows
multiple lines
String1 = ‘‘’CSE
For Life'''
print("nCreating a multiline
String: ")
print(String1)
Output:
String with the use of Single
Quotes: Welcome to the CSE
World
String with the use of Double
Quotes: I'm a Professor
<class 'str'>
String with the use of Triple
Quotes:
I'm a Professor and I live in a world of “CSE"
<class 'str'>
Creating a multiline String:
CSE
For Life
2 April 2022 188
2) List
• Lists are just like the arrays, declared in other languages which is a ordered
collection of data.
• It is very flexible as the items in a list do not need to be of the same type.
Creating List
•Lists in Python can be created by just placing the sequence inside the square
brackets [ ].
2 April 2022 189
Example
# Python program to demonstrate
# Creation of List
# Creating a List
List = []
print("Initial blank List: ")
print(List)
# Creating a List with
# the use of a String
List = [‘ComputerScienceEngineering']
print("nList with the use of String: ")
print(List)
# Creating a List with
# the use of multiple values
List = [“Computer", “Science", “Computer"]
print("nList containing multiple values: ")
print(List[0])
print(List[2])
# Creating a Multi-Dimensional List # (By Nesting a
list inside a List)
List = [[‘Computer', ‘Science'], [‘Engineering']]
print("nMulti-Dimensional List: ")
print(List)
2 April 2022 190
Output
Initial blank List:
[]
List with the use of String:
[‘ComputerScienceEngineering’]
List containing multiple values:
Computer Computer
Multi-Dimensional List:
[[‘Computer', ‘Science'], [‘Engineering']]
2 April 2022 191
3) Tuple
• Just like list, tuple is also an ordered collection of Python objects.
• The only difference between tuple and list is that tuples are immutable i.e. tuples
cannot be modified after it is created.
• It is represented by tuple class.
Creating Tuple
• In Python, tuples are created by placing a sequence of values separated by
‘comma’ with or without the use of parentheses for grouping of the data
sequence.
• Tuples can contain any number of elements and of any datatype (like strings,
integers, list, etc.).
2 April 2022 192
Example
# Python program to demonstrate
# creation of Set
# Creating an empty tuple
Tuple1 = ()
print("Initial empty Tuple: ")
print (Tuple1)
# Creating a Tuple with # the use of
Strings
Tuple1 = (‘CSE’, ‘Second Year')
print("nTuple with the use of
String: ")
print(Tuple1)
# Creating a Tuple with # the use of list
list1 = [1, 2, 4, 5, 6]
print("nTuple using List: ")
print(tuple(list1))
# Creating a Tuple with the
# use of built-in function
Tuple1 = tuple(‘CSE')
print("nTuple with the use of function: ")
print(Tuple1)
# Creating a Tuple # with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', ‘cse') Tuple3 = (Tuple1,
Tuple2)
print("nTuple with nested tuples: ")
print(Tuple3)
2 April 2022 193
Output
Initial empty Tuple:
()
Tuple with the use of String:
(‘CSE', ‘Second Year')
Tuple using List:
(1, 2, 4, 5, 6)
Tuple with the use of function:
(‘C', ‘S', ‘E')
Tuple with nested tuples:
((0, 1, 2, 3), ('python', ‘cse'))
2 April 2022 194
Boolean
• 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).
• But non-Boolean objects can be evaluated in Boolean
context as well and determined to be true or false.
• It is denoted by the class bool.
Note – True and False with capital ‘T’ and ‘F’ are valid
booleans otherwise python will throw an error.
2 April 2022 195
Cont…
# Python program to
# demonstrate boolean type
print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
2 April 2022 196
Set
• In Python, Set is an unordered collection of data type 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.
Creating Sets
• 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 ‘comma’.
• Type of elements in a set need not be the same, various mixed-up data type values
can also be passed to the set.
2 April 2022 197
Example
# Python program to demonstrate
# Creation of Set in Python
# Creating a Set
set1 = set()
print("Initial blank Set: ") print(set1)
# Creating a Set with # the use of
a String
set1 = set("GeeksForGeeks")
print("nSet with the use of String: ")
print(set1)
# Creating a Set with # the use of a List
set1 = set(["Geeks", "For", "Geeks"])
print("nSet with the use of List: ") print(set1)
# Creating a Set with
# a mixed type of values
# (Having numbers and strings)
set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])
print("nSet with the use of Mixed Values")
print(set1)
Output:
Initial blank Set:
set()
Set with the use of String:
{'F', 'o', 'G', 's', 'r', 'k', 'e'}
Set with the use of List:
{'Geeks', 'For'}
Set with the use of Mixed Values
{1, 2, 4, 6, 'Geeks', 'For'}
2 April 2022 198
Dictionary
• Dictionary in Python is an unordered collection of data values, used to store data values like a
map, which unlike other Data Types that hold only single value as an element, Dictionary holds
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’.
Creating Dictionary
• In Python, a Dictionary can be created by placing a sequence of elements within
curly {} braces, separated by ‘comma’.
• Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be
repeated and must be immutable.
• Dictionary can also be created by the built-in function dict().
• An empty dictionary can be created by just placing it to curly braces{}.
2 April 2022 199
Example
# Creating an empty Dictionary
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary # with
Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print(Dict)
# Creating a Dictionary # with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("nDictionary with the use of Mixed Keys: ")
print(Dict)
print("nDictionary with the use of Integer Keys: ") Dict = dict([(1, 'Geeks'), (2, 'For')])
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})
print("nDictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
print("nDictionary with each item as a
pair: ")
print(Dict)
2 April 2022 200
Output
Empty Dictionary:
{}
Dictionary with the use of Integer Keys:
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with the use of Mixed Keys:
{1: [1, 2, 3, 4], 'Name': 'Geeks'}
Dictionary with the use of dict():
{1: 'Geeks', 2: 'For', 3: 'Geeks'}
Dictionary with each item as a pair:
{1: 'Geeks', 2: 'For’}
2 April 2022 201
Different Forms of Assignment Statements in Python
• We use Python assignment statements to assign objects to names.
• The target of an assignment statement is written on the left side of the equal sign (=), and the
object on the right can be an arbitrary expression that computes an object.
There are some important properties of assignment in Python :-
• Assignment creates object references instead of copying the objects.
• Python creates a variable name the first time when they are assigned a value.
• Names must be assigned before being referenced.
• There are some operations that perform assignments implicitly.
2 April 2022 202
1. Basic form:
student = ‘CSE'
print(student)
Output
CSE
2 April 2022 203
2. Tuple assignment:
# equivalent to: (x, y) = (50, 100)
x, y = 50, 100
print('x = ', x)
print('y = ', y)
Output
x = 50
y = 100
2 April 2022 204
3. List assignment:
[x, y] = [2, 4]
print('x = ', x)
print('y = ', y)
Output
x = 2
y = 4
2 April 2022 205
4. Sequence assignment:
• In recent version of Python, tuple and list assignment have been
generalized into instances of what we now call sequence assignment
– any sequence of names can be assigned to any sequence of values,
and Python assigns the items one at a time by position.
a, b, c = 'HEY'
print('a = ', a)
print('b = ', b)
print('c = ', c)
Output
a = H b = E c = Y
2 April 2022 206
5. Extended Sequence unpacking:
p, *q = 'Hello'
print('p = ', p)
print('q = ', q)
OUTPUT
p = H
q = ['e', 'l', 'l', 'o']
2 April 2022 207
6. Multiple- target assignment:
x = y = 75
print(x, y)
Output
75 75
2 April 2022 208
7. Augmented assignment :
x = 2
# equivalent to: x = x + 1 x += 1
print(x)
Output
3
There are several other augmented assignment forms:
-=, **=, &=, etc.
Thank You
2 April 2022 209

More Related Content

PDF
Python quick guide1
PPTX
introduction to Python (for beginners)
PPTX
Introduction to Python Programming Basics
PPTX
Introduction-to-Python-Programming-Language (1).pptx
PPTX
Introduction of python programming
PPTX
Python.pptx
PPTX
Introduction to python
PPTX
Python programming ppt.pptx
Python quick guide1
introduction to Python (for beginners)
Introduction to Python Programming Basics
Introduction-to-Python-Programming-Language (1).pptx
Introduction of python programming
Python.pptx
Introduction to python
Python programming ppt.pptx

Similar to Python_basics_tuples_sets_lists_control_loops.ppt (20)

PPTX
Introduction to python
PPTX
PYTHON UNIT 1
PPTX
Introduction to python for dummies
PDF
python training in chandigarh
PPTX
Python programming
PDF
Python GUI Programming Tkinter and.pdf
PDF
Research paper on python by Rj
PPTX
PYTHON TUTORIALS.pptx
PPTX
Why Python in required in Civil Engineering
PDF
Migration of Applications to Python is the most prudent Decision
PDF
Python_final_print_batch_II_vision_academy.pdf
PDF
Python_final_print_batch_II_vision_academy.pdf
PDF
Python_vision_academy notes
PDF
Python_final_print_batch_II_vision_academy.pdf
PDF
Python_final_print_batch_II_vision_academy (1).pdf
PPTX
PPTX
Simple calulator using GUI tkinter.pptx
PPTX
Python games
PDF
report on internshala python training
PDF
IRJET- Python: Simple though an Important Programming Language
Introduction to python
PYTHON UNIT 1
Introduction to python for dummies
python training in chandigarh
Python programming
Python GUI Programming Tkinter and.pdf
Research paper on python by Rj
PYTHON TUTORIALS.pptx
Why Python in required in Civil Engineering
Migration of Applications to Python is the most prudent Decision
Python_final_print_batch_II_vision_academy.pdf
Python_final_print_batch_II_vision_academy.pdf
Python_vision_academy notes
Python_final_print_batch_II_vision_academy.pdf
Python_final_print_batch_II_vision_academy (1).pdf
Simple calulator using GUI tkinter.pptx
Python games
report on internshala python training
IRJET- Python: Simple though an Important Programming Language
Ad

More from VGaneshKarthikeyan (20)

PPT
1.3 Basic coding skills_fundamentals .ppt
PPT
5_Model for Predictions_Machine_Learning.ppt
PPT
2_Errors in Experimental Observations_ML.ppt
PDF
FINAL_DAY11_INTERFACES_Roles_and_Responsibility.pdf
PPTX
FINAL_DAY10_INTERFACES_roles and benefits.pptx
PPTX
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
PPTX
FINAL_DAY9_METHOD_OVERRIDING_Role and benefits .pptx
PPT
JAVA_BASICS_Data_abstraction_encapsulation.ppt
PPT
Java ppt-class_Introduction_class_Objects.ppt
PPT
INT104 DBMS - Introduction_Atomicity.ppt
PDF
6. Implementation of classes_and_its_advantages.pdf
PPT
Operators_in_C++_advantages_applications.ppt
PPT
1_Standard error Experimental Data_ML.ppt
PPTX
Unit III Part I_Opertaor_Overloading.pptx
PPTX
Linear_discriminat_analysis_in_Machine_Learning.pptx
PPTX
K-Mean clustering_Introduction_Applications.pptx
PPTX
Numpy_defintion_description_usage_examples.pptx
PPT
Refined_Lecture-14-Linear Algebra-Review.ppt
PPT
randomwalks_states_figures_events_happenings.ppt
PPT
stochasticmodellinganditsapplications.ppt
1.3 Basic coding skills_fundamentals .ppt
5_Model for Predictions_Machine_Learning.ppt
2_Errors in Experimental Observations_ML.ppt
FINAL_DAY11_INTERFACES_Roles_and_Responsibility.pdf
FINAL_DAY10_INTERFACES_roles and benefits.pptx
FINAL_DAY8_VISIBILITY_LABELS_Roles and.pptx
FINAL_DAY9_METHOD_OVERRIDING_Role and benefits .pptx
JAVA_BASICS_Data_abstraction_encapsulation.ppt
Java ppt-class_Introduction_class_Objects.ppt
INT104 DBMS - Introduction_Atomicity.ppt
6. Implementation of classes_and_its_advantages.pdf
Operators_in_C++_advantages_applications.ppt
1_Standard error Experimental Data_ML.ppt
Unit III Part I_Opertaor_Overloading.pptx
Linear_discriminat_analysis_in_Machine_Learning.pptx
K-Mean clustering_Introduction_Applications.pptx
Numpy_defintion_description_usage_examples.pptx
Refined_Lecture-14-Linear Algebra-Review.ppt
randomwalks_states_figures_events_happenings.ppt
stochasticmodellinganditsapplications.ppt
Ad

Recently uploaded (20)

PPT
Project quality management in manufacturing
PPTX
Lesson 3_Tessellation.pptx finite Mathematics
PPTX
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
PPTX
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
DOCX
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
PPTX
Lecture Notes Electrical Wiring System Components
PDF
Arduino robotics embedded978-1-4302-3184-4.pdf
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
PPTX
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
PPTX
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
PPTX
Internet of Things (IOT) - A guide to understanding
PDF
Operating System & Kernel Study Guide-1 - converted.pdf
PPTX
OOP with Java - Java Introduction (Basics)
PPTX
bas. eng. economics group 4 presentation 1.pptx
PPTX
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
PPTX
Welding lecture in detail for understanding
PDF
Digital Logic Computer Design lecture notes
PDF
Well-logging-methods_new................
PPTX
UNIT 4 Total Quality Management .pptx
Project quality management in manufacturing
Lesson 3_Tessellation.pptx finite Mathematics
MCN 401 KTU-2019-PPE KITS-MODULE 2.pptx
Recipes for Real Time Voice AI WebRTC, SLMs and Open Source Software.pptx
ASol_English-Language-Literature-Set-1-27-02-2023-converted.docx
Lecture Notes Electrical Wiring System Components
Arduino robotics embedded978-1-4302-3184-4.pdf
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
July 2025 - Top 10 Read Articles in International Journal of Software Enginee...
Infosys Presentation by1.Riyan Bagwan 2.Samadhan Naiknavare 3.Gaurav Shinde 4...
CARTOGRAPHY AND GEOINFORMATION VISUALIZATION chapter1 NPTE (2).pptx
Internet of Things (IOT) - A guide to understanding
Operating System & Kernel Study Guide-1 - converted.pdf
OOP with Java - Java Introduction (Basics)
bas. eng. economics group 4 presentation 1.pptx
KTU 2019 -S7-MCN 401 MODULE 2-VINAY.pptx
Welding lecture in detail for understanding
Digital Logic Computer Design lecture notes
Well-logging-methods_new................
UNIT 4 Total Quality Management .pptx

Python_basics_tuples_sets_lists_control_loops.ppt

  • 2. 2 April 2022 2 What is Python? • Python is a popular programming language. • It was created by Guido van Rossum, and released in 1991. It is used for: • Web development (server-side), • Software development, • Mathematics, • System scripting.
  • 3. 2 April 2022 3 What is Python • Python is a general purpose, dynamic, high-level, and interpreted programming language. • It supports Object Oriented programming approach to develop applications. • It is simple and easy to learn and provides lots of high-level data structures. • Python is easy to learn yet powerful and versatile scripting language, which makes it attractive for Application Development. • Python's syntax and dynamic typing with its interpreted nature make it an ideal language for scripting and rapid application development.
  • 4. 2 April 2022 4 What can Python do? • Python can be used on a server to create web applications. • Python can be used alongside software to create workflows. • Python can connect to database systems. • It can also read and modify files. • Python can be used to handle big data and perform complex mathematics. • Python can be used for rapid prototyping, or for production-ready software development.
  • 5. 2 April 2022 5 Why Python? • Python works on different platforms (Windows, Mac, Linux, Raspberry Pi, etc). • Python has a simple syntax similar to the English language. • Python has syntax that allows developers to write programs with fewer lines than some other programming languages. • Python runs on an interpreter system, meaning that code can be executed as soon as it is written. This means that prototyping can be very quick. • Python can be treated in a procedural way, an object-oriented way or a functional way.
  • 6. 2 April 2022 6 Why learn Python? • Easy to use and Learn • Expressive Language • Interpreted Language • Object-Oriented Language • Open Source Language • Extensible • Learn Standard Library • GUI Programming Support • Integrated • Embeddable • Dynamic Memory Allocation • Wide Range of Libraries and Frameworks
  • 7. 2 April 2022 7 Python Features 1) Easy 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. 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.
  • 8. 2 April 2022 8 Python Features 4) Cross-platform Language •Python can run equallyon different platforms such as Windows, Linux, UNIX, and Macintosh, etc. So, we can say that Python is a portable language. 5) Free and Open Source •Python is freely available for everyone. It is freely available on its official website www.python.org 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. 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.
  • 9. 2 April 2022 9 Python Features 8) Large Standard Library •It provides a vast range oflibraries for the various fields such as machine learning, web developer, and also for the scripting. Django, flask, pyramids are the popular framework for Python web development. 9) GUI Programming Support •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. 11. Embeddable •The code of the other programming language can use in the Python source code. 12. Dynamic Memory Allocation •In Python, we don't need to specify the data-type of the variable.
  • 10. 2 April 2022 10 Why the Name Python? • 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. • 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.
  • 11. Python Version List Python Version Released Date Python Version Released Date Python 1.0 January 1994 Python 2.7 July 3, 2010 Python 1.5 December 31, 1997 Python 3.0 December 3, 2008 Python 1.6 September 5, 2000 Python 3.1 June 27, 2009 Python 2.0 October 16, 2000 Python 3.2 February 20, 2011 Python 2.1 April 17, 2001 Python 3.3 September 29, 2012 Python 2.2 December 21, 2001 Python 3.4 March 16, 2014 Python 2.3 July 29, 2003 Python 3.5 September 13, 2015 Python 2.4 November 30, 2004 Python 3.6 December 23, 2016 Python 2.5 September 19, 2006 Python 3.7 June 27, 2018 Python 2.6 October 1, 2008 Python 3.8 October 14, 2019 2 April 2022 11
  • 12. 2 April 2022 12 Python Libraries and Frameworks Python consists of vast libraries and various frameworks. •TensorFlow - It is an artificial intelligence library which allows us to create large scale AI based projects. •Django - It is an open source framework that allows us to develop web applications. It is easy, flexible, and simple to manage. •Flask - It is also an open source web framework. It is used to develop lightweight web applications. •Pandas - It is a Python library which is used to perform scientific computations. •Keras - It is an open source library, which is used to work around the neural network.
  • 14. 2 April 2022 14 1) Web Applications • We can use Python to develop web applications. It provides libraries to handle internet protocols such as HTML and XML, JSON, Email processing, request, beautifulSoup, Feedparser, etc. One of Python web-framework named Django is used on Instagram. • Django and Pyramid framework(Use for heavy applications) • Flask and Bottle (Micro-framework) • Plone and Django CMS (Advance Content management)
  • 15. 2 April 2022 15 2) Desktop GUI Applications The GUI stands for the Graphical User Interface, which provides a smooth interaction to any application. Python provides a Tk GUI library to develop a user interface. •Tkinter or Tk •wxWidgetM •Kivy (used for writing multitouch applications ) •PyQt or Pyside
  • 16. 2 April 2022 16 3) Console-based Application • Console-based applications run from the command-line or shell. • These applications are computer program which are used commands to execute. • This kind of application was more popular in the old generation of computers. • Python can develop this kind of application very effectively. .
  • 17. 2 April 2022 17 4) Software Development • Python is useful for the software development process. It works as a support language and can be used to build control and management, testing, etc. • SCons is used to build control. • Buildbot and Apache Gumps are used for automated continuous compilation and testing. • Round or Trac for bug tracking and project management.
  • 18. 2 April 2022 18 5) Scientific and Numeric • This is the era of Artificial intelligence where the machine can perform the task the same as the human. • Python language is the most suitable language for Artificial intelligence or machine learning. • Implementing machine learning algorithms require complex mathematical calculation. • Python has many libraries for scientific and numeric such as Numpy, Pandas, Scipy, Scikit- learn, etc. • Few popular frameworks ofmachine libraries are given below. • SciPy • Scikit-learn • NumPy • Pandas • Matplotlib
  • 19. 2 April 2022 19 6) Business Applications • Business Applications differ from standard applications. • E-commerce and ERP are an example of a business application. • This kind of application requires extensively, scalability and readability, and Python provides all these features. • Python provides a Tryton platform which is used to develop the business application.
  • 20. 2 April 2022 20 7) Audio or Video-based Applications • Python is flexible to perform multiple tasks and can be used to create multimedia applications. • Some multimedia applications which are made by using Python are TimPlayer, cplay, etc. • The few multimedia libraries are given below. • Gstreamer • Pyglet • QT Phonon
  • 21. 2 April 2022 21 8) 3D CAD Applications • The CAD (Computer-aided design) is used to design engineering related architecture. • It is used to develop the 3D representation of a part of a system. • Python can create a 3D CAD application by using the following functionalities. • Fandango (Popular ) • CAMVOX • HeeksCNC • AnyCAD • RCAM
  • 22. 2 April 2022 22 9) Enterprise Applications • Python can be used to create applications that can be used within an Enterprise or an Organization. Some real-time applications are OpenERP, Tryton, Picalo, etc.
  • 23. 2 April 2022 23 10) Image Processing Application • Python contains many libraries that are used to work with the image. The image can be manipulated according to our requirements. • OpenCV • Pillow • SimpleITK
  • 24. 2 April 2022 24 How to Install Python (Environment Set-up) Installation on Windows •Visit the link https://www.python.org/downloads/ •to download the latest release of Python •In this process, we will install Python 3.8.6 on our Windows operating system •When we click on the above link, it will bring us the following page. Step - 1: Select the Python's version to download. Step - 2: Click on the Install Now Step - 3 Installation in Process
  • 25. Step - 1: Select the Python's version to download. 2 April 2022 25
  • 26. Step - 2: Click on the Install Now • Double-click the executable file, which is downloaded; the following window will open. Select Customize installation and proceed. Click on the Add Path check box, it will set the Python path automatically. 2 April 2022 26
  • 27. Step - 3 Installation in Process 2 April 2022 27
  • 28. Cont…. • Now, try to run python on the command prompt. Type the command python - version in case of python3. 2 April 2022 28
  • 30. 2 April 2022 30 Python Development Cycle • Python's development cycle is dramatically shorter than that of traditional tools. • In Python, there are no compile or link steps -- Python programs simply import modules at runtime and use the objects they contain. • Because of this, Python programs run immediately after changes are made. • And in cases where dynamic module reloading can be used, it's even possible to change and reload parts of a running program without stopping it at all.
  • 31. 2 April 2022 31 Python Syntax Execute Python Syntax •Python syntax can be executed by writing directly in the Command Line: >>> print("Hello, World!") Hello, World! •by creating a python file on the server, using the .py file extension, and running it in the Command Line: C:UsersYour Name>python myfile.py
  • 32. Python Indentation • Indentation refers to the spaces at the beginning of a code line. • Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important. • Python uses indentation to indicate a block of code. Example if5 > 2: print("Five is greater than two!") Note: Python will give you an error if you skip the indentation: 2 April 2022 32
  • 33. Input and Output in Python How to Take Input from User in Python •To do this Python provides an input() function. Syntax: input('prompt') where prompt is an optional string that is displayed on the string at the time of taking input. 2 April 2022 33
  • 34. 2 April 2022 34 Example 1: Python get user input with a message # Taking input from the user name = input("Enter your name: ") # Output print("Hello, " + name) print(type(name)) Output: Enter your name: GFG Hello, GFG <class 'str'>
  • 35. 2 April 2022 35 Example 2: Integer input in Python # Taking input from the user as integer num = int(input("Enter a number: ")) add = num + 1 # Output print(add) Output: Enter a number: 25 26
  • 36. 2 April 2022 36 Output using print() function Syntax: print(value(s), sep= ‘ ‘, end = ‘n’, file=file, flush=flush) Parameters: •value(s) : Any value, and as many as you like. Will be converted to string before printed •sep=’separator’ : (Optional) Specify how to separate the objects, if there is more than one. Default :’ ‘ •end=’end’: (Optional) Specify what to print at the end. Default : ‘n’ •file : (Optional) An object with a write method. Default :sys.stdout •flush : (Optional) A Boolean, specifying if the output is flushed (True) or buffered (False). Default: False •Returns: It returns output to the screen.
  • 37. 2 April 2022 37 String Literals • 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. • n : This string literal is used to add a new blank line while printing a statement. • “” :An empty quote (“”) is used to print an empty line. Example: print(“ComputerScience n is best for DSA Content.") Output: ComputerScience is best for DSA Content.
  • 38. 2 April 2022 38 end= ” ” statement • 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: Python print() without new line. # This line will automatically add a new line before the # next print statement print (“St Martins is the best platform for DSA content") # This print() function ends with "**" as set in the end argument. print (" St Martins is the best platform for DSA content", end= "**") print("Welcome to GFG") Output: St Martins is the best platform for DSA content St Martins is the best platform for DSA content**Welcome to GFG
  • 39. 2 April 2022 39 Separator • The print() function can accept any number of positional arguments. • These arguments can be separated from each other using a “,” separator. • These are primarily used for formatting multiple statements in a single print() function. Example: b = "Engineering" print("St.Martin's", b , "College") Output: St.Martin's Engineering College
  • 40. 2 April 2022 40 Example: Python Print Output # Python program to demonstrate # print() method print("GFG") # code for disabling the softspace feature print('G', 'F', 'G’) Output GFG G F G
  • 41. 2 April 2022 41 Formatting Output Using formatted string literals •We can use formatted string literals, by starting a string with f or F before opening quotation marks or triple quotation marks. •In this string, we can write Python expressions between { and } that can refer to a variable or any literal value.
  • 42. 2 April 2022 42 Example: Python String formatting using F string # Declaring a variable name = "Gfg" # Output print(f'Hello {name}! How are you?’) Output: Hello Gfg! How are you?
  • 43. 2 April 2022 43 Using format() • We can also use format() function to format our output to make it look presentable. • The curly braces { } work as placeholders. • We can specify the order in which variables occur in the output.
  • 44. 2 April 2022 44 Example: Python string formatting using format() function # Initializing variables a = 20 b = 10 # addition sum = a + b # subtraction sub = a- b # Output print('The value of a is {} and b is {}'.format(a,b)) print('{2} is the sum of {0} and {1}'.format(a,b,sum)) print('{sub_value} is the subtraction of {value_a} and {value_b}'.format(value_a = a , value_b = b, sub_value = sub)) Output: The value of a is 20 and b is 10 30 is the sum of 20 and 10 10 is the subtraction of 20 and 10
  • 45. 2 April 2022 45 Using %Operator • We can use ‘%’ operator. % values are replaced with zero or more value of elements. • Theformatting using% is similar to that of ‘printf ’ in the C programming language. %d – integer %f – float %s – string %x – hexadecimal %o – octal
  • 46. 2 April 2022 46 Example: # Taking input from the user num = int(input("Enter a value: ")) add = num + 5 # Output print("The sum is %d" %add) Output: Enter a value: 50 The sum is 55
  • 47. 2 April 2022 47 Python Comments • Comments can be used to explain Python code. • Comments can be used to make the code more readable. • Comments can be used to prevent execution when testing code.
  • 48. 2 April 2022 48 Creating a Comment • Comments starts with a #, and Python will ignore them: Example #This is a comment print("Hello, World!") • Comments can be placed at the end of a line, and Python will ignore the rest of the line: Example print("Hello, World!") #This is a comment
  • 49. 2 April 2022 49 Multi Line Comments • Python does not really have a syntax for multi line comments. • To add a multiline comment you could insert a # for each line: Example #This is a comment #written in #more than just one line print("Hello, World!")
  • 50. 2 April 2022 50 Python Variables Variables •Variables are containers for storing data values. Creating Variables •Python has no command for declaring a variable. •A variable is created the moment you first assign a value to it. Example x = 5 y = "Rajalingam" print(x) print(y) Output 5 Rajalingam
  • 51. 2 April 2022 51 Cont… • Variables do not need to be declared with any particular type, and can even change type after they have been set. Example x = 4 # x is of type int x = "Computer Science" # x is now of type str print(x) Output: 4 Computer Science
  • 52. 2 April 2022 52 Casting Variable • If you want to specify the data type of a variable, this can be done with casting. Example: x = str(3) # x will be '3' y = int(3) # y will be 3 z = float(3) # z will be 3.0 Output: 3 3 3.0
  • 53. 2 April 2022 53 Get the Type • You can get the data type of a variable with the type() function. Example x = 5 y = "Dr. B.Rajalingam" print(type(x)) print(type(y)) Output: <class 'int'> <class 'str'>
  • 54. 2 April 2022 54 Single or Double Quotes? • String variables can be declared either by using single or double quotes: Example x = “Rajalingam" # is the same as x = 'Rajalingam’ Print(x) Output: Rajalingam
  • 55. 2 April 2022 55 Case-Sensitive • Variable names are case-sensitive. Example This will create two variables: a = 4 A = “Rajalingam" #A will not overwrite a Output: 4 Rajalingam
  • 56. 2 April 2022 56 Python Data Types • In programming, data type is an important concept. • Variables can store data of different types, and different types can do different things. • Python has the following data types built-in by default, in these categories: Text Type: str Numeric Types: int, float, complex Sequence Types: list, tuple, range Mapping Type: dict Set Types: set, frozenset Boolean Type: bool Binary Types: bytes, bytearray, memoryview
  • 57. 2 April 2022 57 Getting the Data Type • You can get the data type of any object by using the type() function: Example Print the data type of the variable x: x = 5 print(type(x)) Output: <class 'int'>
  • 58. 2 April 2022 58 Setting the Data Type • In Python, the data type is set when you assign a value to a variable: Example Data Type x = "Hello World" str x = 20 int x = 20.5 float x = 1j complex x = ["apple", "banana", "cherry"] list x = ("apple", "banana", "cherry") tuple x = range(6) range x = {"name" : "John", "age" : 36} dict x = {"apple", "banana", "cherry"} set x = frozenset({"apple", "banana", "cherry"}) frozenset x = True bool x = b"Hello" bytes x = bytearray(5) bytearray x = memoryview(bytes(5)) memoryview
  • 59. 2 April 2022 59 Example Example 1 x = "Hello World" #display x: print(x) #display the data type of x: print(type(x)) Output: Hello World <class 'str'>
  • 60. 2 April 2022 60 Example Example 2 x = 20 #display x: print(x) #display the data type of x: print(type(x)) Output: 20 <class 'int'>
  • 61. 2 April 2022 61 Example Example 3 x = 20.5 #display x: print(x) #display the data type of x: print(type(x)) Output: 20.5 <class 'float'>
  • 62. 2 April 2022 62 Example Example 4 x = 1j #display x: print(x) #display the data type of x: print(type(x)) Output: lj <class 'complex'>
  • 63. 2 April 2022 63 Example Example 5 x = ["apple", "banana", "cherry"] #display x: print(x) #display the data type of x: print(type(x)) Output: ['apple', 'banana', 'cherry’] <class 'list'>
  • 64. 2 April 2022 64 Example Example 6 x = ("apple", "banana", "cherry") #display x: print(x) #display the data type of x: print(type(x)) Output: ('apple', 'banana', 'cherry’) <class 'tuple'>
  • 65. 2 April 2022 65 Example Example 7 x = range(6) #display x: print(x) #display the data type of x: print(type(x)) Output: range(0, 6) <class 'range'>
  • 66. 2 April 2022 66 Example Example 8 x = {"name" : "John", "age" : 36} #display x: print(x) #display the data type of x: print(type(x)) Output: {'name': 'John', 'age': 36} <class 'dict'>
  • 67. 2 April 2022 67 Example Example 9 x = {"apple", "banana", "cherry"} #display x: print(x) #display the data type of x: print(type(x)) Output: {'cherry', 'banana', 'apple’} <class 'set'>
  • 68. 2 April 2022 68 Example Example 10 x = frozenset({"apple", "banana", "cherry"}) #display x: print(x) #display the data type of x: print(type(x)) Output: frozenset({'apple', 'cherry', 'banana’}) <class 'frozenset'>
  • 69. 2 April 2022 69 Example Example 11 x = True #display x: print(x) #display the data type of x: print(type(x)) Output: True <class 'bool'>
  • 70. 2 April 2022 70 Example Example 12 x = b"Hello" #display x: print(x) #display the data type of x: print(type(x)) Output: b'Hello’ <class 'bytes'>
  • 71. 2 April 2022 71 Example Example 13 x = bytearray(5) #display x: print(x) #display the data type of x: print(type(x)) Output: bytearray(b'x00x00x00x00x00’) <class 'bytearray'>
  • 72. 2 April 2022 72 Example Example 14 x = memoryview(bytes(5)) #display x: print(x) #display the data type of x: print(type(x)) Output: <memory at 0x14cff7cd9a00> <class 'memoryview'>
  • 73. 2 April 2022 73 Setting the Specific Data Type Example Data Type x = str("Hello World") str x = int(20) int x = float(20.5) float x = complex(1j) complex x = list(("apple", "banana", "cherry")) list x = tuple(("apple", "banana", "cherry")) tuple x = range(6) range x = dict(name="John", age=36) dict x = set(("apple", "banana", "cherry")) set x = frozenset(("apple", "banana", "cherry")) frozenset x = bool(5) bool x = bytes(5) bytes x = bytearray(5) bytearray x = memoryview(bytes(5)) memoryview
  • 74. 2 April 2022 74 Python Numbers There are three numeric types in Python: • int • float • complex Variables of numeric types are created when you assign a value to them: Example x = 1 # int y = 2.8 # float z = 1j # complex
  • 75. 2 April 2022 75 Python Numbers • To verify the type of any object in Python, use the type() function: Example x = 1 y = 2.8 z = 1j print(type(x)) print(type(y)) print(type(z)) Output: <class 'int'> <class 'float'> <class 'complex'>
  • 76. 2 April 2022 76 Int •Int, or integer, is a whole number, positive or negative, without decimals, of unlimited length. Example Integers: x = 1 y = 35656222554887711 z = -3255522 print(type(x)) print(type(y)) print(type(z)) Output <class 'int'> <class 'int'> <class 'int'>
  • 77. 2 April 2022 77 Float • Float, or "floating point number" is a number, positive or negative, containing one or more decimals. Example Floats: x = 1.10 y = 1.0 z = -35.59 print(type(x)) print(type(y)) print(type(z)) Output <class 'float'> <class 'float'> <class 'float'>
  • 78. 2 April 2022 78 Complex •Complex numbers are written with a "j" as the imaginary part: Example Complex: x = 3+5j y = 5j z = -5j print(type(x)) print(type(y)) print(type(z)) Output <class 'complex'> <class 'complex'> <class 'complex'>
  • 79. 2 April 2022 79 Type Conversion • You can convert from one type to another with the int(), float(), and complex() methods: Example Convert from one type to another: x = 1 # int y = 2.8 # float z = 1j # complex #convert from int to float: a = float(x) #convert from float to int: b = int(y) #convert from int to complex: c = complex(x) print(a) print(b) print(c) print(type(a)) print(type(b)) print(type(c)) Output 1.0 2 (1+0j) <class 'float'> <class 'int'> <class 'complex'>
  • 80. 2 April 2022 80 Random Number • Python does not have a random() function to make a random number, but Python has a built- in module called random that can be used to make random numbers: Example Import the random module, and display a random number between 1 and 9: import random print(random.randrange(1, 10)) Output: 7
  • 81. 2 April 2022 81 Python Casting Specify a Variable Type: •There may be times when you want to specify a type on to a variable. This can be done with casting. Casting in python is therefore done using constructor functions: •int() - constructs an integer number from an integer literal, a float literal (by removing all decimals), or a string literal (providing the string represents a whole number) •float()- constructs a float number from an integer literal, a float literal or a string literal (providing the string represents a float or an integer) •str() - constructs a string from a wide variety of data types, including strings, integer literals and float literals.
  • 82. 2 April 2022 82 Example: Integers x = int(1) y = int(2.8) z = int("3") print(x) print(y) print(z) Output: 1 2 3
  • 83. 2 April 2022 83 Example: Floats x = float(1) y = float(2.8) z = float("3") w = float("4.2") print(x) print(y) print(z) print(w) Output: 1.0 2.8 3.0 4.2
  • 84. 2 April 2022 84 Example: Strings x = str("s1") y = str(2) z = str(3.0) print(x) print(y) print(z) Output s1 2 3.0
  • 85. 2 April 2022 85 Python Operators • Operators are used to perform operations on variables and values. • In the example below, we use the + operator to add together two values: Example • print(10 + 5)
  • 86. 2 April 2022 86 Python divides the operators • Arithmetic operators • Assignment operators • Comparison operators • Logical operators • Identity operators • Membership operators • Bitwise operators
  • 87. 2 April 2022 87 Python Arithmetic Operators • Arithmetic operators are used with numeric values to perform common mathematical operations: Operator Name Example + Addition x + y - Subtraction x - y * Multiplication x * y / Division x / y % Modulus x % y ** Exponentiation x ** y / / Floor division x / / y
  • 88. 2 April 2022 88 Python Assignment Operators • Assignment operators are used to assign values to variables: Operator Example Same As = x = 5 x = 5 += x += 3 x = x + 3 -= x -= 3 x = x - 3 *= x *= 3 x = x * 3 / = x / = 3 x = x / 3 %= x %= 3 x = x % 3 / / = x / / = 3 x = x / / 3 **= x **= 3 x = x ** 3 &= x &= 3 x = x & 3 | = x | = 3 x = x | 3 ^= x ^= 3 x = x ^ 3 >>= x >>= 3 x = x >> 3 <<= x <<= 3 x = x << 3
  • 89. 2 April 2022 89 Python Comparison Operators • Comparison operators are used to compare two values: Operator Name Example == Equal x == y != Not equal x != y > Greater than x > y < Less than x < y >= Greater than or equal to x >= y <= Less than or equal to x <= y
  • 90. 2 April 2022 90 Python Logical Operators • Logical operators are used to combine conditional statements: Operator Description Example and Returns True if both statements are true x < 5 and x < 10 or Returns True if one of the statements is true x < 5 or x < 4 not Reverse the result, returns False if the result is true not(x < 5 and x < 10)
  • 91. 2 April 2022 91 Python Identity Operators Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location: Operator Description Example is Returns True if both variables are the same object x is y is not Returns True if both variables are not the same object x is not y
  • 92. 2 April 2022 92 Python Membership Operators Membership operators are used to test if a sequence is presented in an object: Operator Description Example in Returns True if a sequence with the specified value is present in the object x in y not in Returns True if a sequence with the specified value is not present in the object x not in y
  • 93. 2 April 2022 93 Python Bitwise Operators • Bitwise operators are used to compare (binary) numbers: Operator Name Description & AND Sets each bit to 1 if both bits are 1 | OR Sets each bit to 1 if one of two bits is 1 ^ XOR Sets each bit to 1 if only one of two bits is 1 ~ NOT Inverts all the bits << Zero fill left shift Shift left by pushing zeros in from the right and let the leftmost bits fall off >> Signed right shift Shift right by pushing copies of the leftmost bit in from the left, and let the rightmost bits fall off
  • 94. 2 April 2022 94 Expressions in Python • 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. • We have many different types of expressions in Python.
  • 95. 2 April 2022 95 1. Constant Expressions • These are the expressions that have constant values only. Example: # Constant Expressions x = 15 + 1.3 print(x) Output 16.3
  • 96. 2 April 2022 96 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.
  • 97. 2 April 2022 97 Cont… Operators Syntax Functioning + x + y Addition – x – y Subtraction * x * y Multiplication / x / y Division / / x / / y Quotient % x % y Remainder ** x ** y Exponentiation
  • 98. 2 April 2022 98 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 3.3333333333333335
  • 99. 2 April 2022 99 3. Integral Expressions • These are the kind of expressions that produce only integer results after all computations and type conversions. # Integral Expressions a = 13 b = 12.0 c = a + int(b) print(c) Output 25
  • 100. 2 April 2022 100 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
  • 101. 2 April 2022 101 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.
  • 102. 2 April 2022 102 Example # Relational Expressions a = 21 b = 13 c = 40 d = 37 p = (a + b) >= (c - d) print(p) Output True
  • 103. 2 April 2022 103 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.
  • 104. 2 April 2022 104 Cont… Operator Syntax Functioning and P and Q It returns true if both P and Q are true otherwise returns false or P or Q It returns true if at least one of P and Q is true not not P It returns true if condition P is false
  • 105. 2 April 2022 105 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
  • 106. 2 April 2022 106 7. Bitwise 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
  • 107. 2 April 2022 107 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
  • 108. 2 April 2022 108 Decision Structures in Python • There comes a point in your life where you need to decide what steps should be taken and based on that you decide your next decisions. Python has the following decision-making statements: • if statements • if-else statements • if-elif ladder • Nested statements
  • 109. 2 April 2022 109 Python Conditions and If statements • Python supports the usual logical conditions from mathematics: • Equals: a == b • Not Equals: a != b • Less than: a < b • Less than or equal to: a <= b • Greater than: a > b • Greater than or equal to: a >= b • These conditions can be used in several ways, most commonly in "if statements" and loops. • An "if statement" is written by using the if keyword.
  • 110. 2 April 2022 110 Python if statement • if statement is the most simple form of decision-making statement. • It takes an expression and checks if the expression evaluates to True then the block of code in if statement will be executed. • If the expression evaluates to False, then the block of code is skipped. Syntax: if( expression ): Statement 1 Statement 2 … Statement n
  • 111. 2 April 2022 111
  • 112. 2 April 2022 112 if statement Example 1: a = 20 ; b = 20 if ( a == b ): print( “a and b are equal”) print(“If block ended”) Output: a and b are equal If block ended Example 2: num = 5 if ( num >= 10): print(“num is greater than 10”) print(“if block ended”) Output: If block ended
  • 113. 2 April 2022 113 Python if-else statement • From the name itself, we get the clue that the if-else statement checks the expression and executes the if block when the expression is True otherwise it will execute the else block of code. • The else block should be right after if block and it is executed when the expression is False. Syntax: if( expression ): Statement else: Statement
  • 114. 2 April 2022 114
  • 115. 2 April 2022 115 if-else statement Example 1: number1 = 20 ; number2 = 30 if(number1 > number2 ): print(“number 1 is greater than number 2”) else: print(“number 2 is greater than number 1”) Output: number 2 is greater than number 1 Example 1: if (5>10): print(5) else: print(10) else: print(“End”) Output: SyntaxError: invalid syntax
  • 116. Python if-elif ladder Syntax: if( expression1 ): statement elif (expression2 ) : statement elif(expression3 ): statement . . else: stat2eAmpriel 2n0t22 116 • You might have heard of the else-if statements in other languages like C/C++ or Java. • In Python, we have an elif keyword to chain multiple conditions one after another. With elif ladder, we can make complex decision-making statements. • The elif statement helps you to check multiple expressions and it executes the code as soon as one of the conditions evaluates to True.
  • 117. 2 April 2022 117
  • 118. 2 April 2022 118 Python if-elif ladder Example: 1 print(“Select your ride:”) print(“1. Bike”) print(“2. Car”) print(“3. SUV”) choice = int( input() ) if( choice == 1 ): print( “You have selected Bike” ) elif( choice == 2 ): print( “You have selected Car” ) elif( choice == 3 ): print( “You have selected SUV” ) else: print(“Wrong choice!“) Output 1: Select your ride: 1.Bike 2.Car 3.SUV 3 You have selected SUV Output 2: Select your ride: 1.Bike 2.Car 3.SUV 10 Wrong choice!
  • 119. 2 April 2022 119 Python Nested if statement • In very simple words, Nested if statements is an if statement inside another if statement. • Python allows us to stack any number of if statements inside the block of another if statements. • They are useful when we need to make a series of decisions. Syntax: if (expression): if(expression): Statement of nested if else: Statement of nested if else Statement of outer if Statement outside if block
  • 120. 2 April 2022 120
  • 121. 2 April 2022 121 Nested if statement Example : num1 = int( input()) num2 = int( input()) if( num1>= num2): if(num1 == num2): print(f'{num1} and {num2} are equal') else: print(f'{num1} is greater than {num2}') else: print(f'{num1} is smaller than {num2}') Output 1: 10 20 10 is smaller than 20 Output 2: 5 5 5 and 5 are equal
  • 122. 2 April 2022 122 If Statement Example a = 33 b = 200 if b > a: print("b is greater than a") Output: b is greater than a
  • 123. 2 April 2022 123 Indentation • Python relies on indentation (whitespace at the beginning of a line) to define scope in the code. Other programming languages often use curly-brackets for this purpose. Example • If statement, without indentation (will raise an error): a = 33 b = 200 if b > a: print("b is greater than a") Output: File "demo_if_error.py", line 4 print("b is greater than a") ^ IndentationError: expected an indented block
  • 124. 2 April 2022 124 Elif The elif keyword is pythons way of saying "if the previous conditions were not true, then try this condition". Example a = 33 b = 33 if b > a: print("b is greater than a") elif a == b: print("a and b are equal") Output: a and b are equal
  • 125. 2 April 2022 125 Else • The else keyword catches anything which isn't caught by the preceding conditions. Example a = 200 b = 33 ifb > a: print("b is greater than a") elif a == b: print("a and b are equal") else: print("a is greater than b") Output: a is greater than b
  • 126. 2 April 2022 126 Example You can also have an else without the elif: Example a = 200 b = 33 if b > a: print("b is greater than a") else: print("b is not greater than a") Output: b is not greater than a
  • 127. 2 April 2022 127 Short Hand If • If you have only one statement to execute, you can put it on the same line as the if statement. Example • One line if statement: a = 200 b = 33 if a > b: print("a is greater than b") Output: "a is greater than b"
  • 128. 2 April 2022 128 Short Hand If ... Else If you have only one statement to execute, one for if, and one for else, you can put it all on the same line: Example One line if else statement: a = 2 b = 330 print("A") if a > b else print("B") Output B
  • 129. 2 April 2022 129 Cont… • You can also have multiple else statements on the same line: Example • One line if else statement, with 3 conditions: a = 330 b = 350 print("A") if a > b else print("=") if a == b else print("B") Output: B
  • 130. 2 April 2022 130 And • The and keyword is a logical operator, and is used to combine conditional statements: Example • Test if a is greater than b, AND if c is greater than a: a = 200 b = 33 c = 500 if a > b and c > a: print("Both conditions are True") Output: Both conditions are True
  • 131. 2 April 2022 131 Or • The or keyword is a logical operator, and is used to combine conditional statements: Example • Test if a is greater than b, OR if a is greater than c: a = 200 b = 33 c = 500 if a > b or a > c: print("At least one of the conditions is True") Output At least one of the conditions is True
  • 132. 2 April 2022 132 Nested If • You can have if statements inside if statements, this is called nested if statements. Example x = 41 if x > 10: print("Above ten,") if x > 20: print("and also above 20!") else: print("but not above 20.") Output Above ten, and also above 20!
  • 133. 2 April 2022 133 The pass Statement • if statements cannot be empty, but if you for some reason have an if statement with no content, put in the pass statement to avoid getting an error. a = 33 b = 10 ifb > a: pass # having an empty if statement like this, would raise an error without the pass statement
  • 134. 2 April 2022 134 Python Strings Strings Strings in python are surrounded by either single quotation marks, or double quotation marks. 'hello' is the same as "hello". You can display a string literal with the print() function: #You can use double or single quotes: print("Hello") print('Hello')
  • 135. 2 April 2022 135 Assign String to a Variable • Assigning a string to a variable is done with the variable name followed by an equal sign and the string: Example a = "Hello" print(a) Output: Hello
  • 136. 2 April 2022 136 Multiline Strings • You can assign a multiline string to a variable by using three quotes: Example • You can use three double quotes: Program: a = """Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.""" print(a) Output: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Or three single quotes: Program: a = '''Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.''' print(a) Output: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.
  • 137. 2 April 2022 137 Strings are Arrays • Like many other popular programming languages, strings in Python are arrays of bytes representing unicode characters. • However, Python does not have a character data type, a single character is simply a string with a length of 1. • Square brackets can be used to access elements of the string. Example: Note: Get the character at position 1 (remember that the first character has the position 0): a = "Hello, World!" print(a[1]) Output: e
  • 138. 2 April 2022 138 Looping Through a String • Since strings are arrays, we can loop through the characters in a string, with a for loop. Example • Loop through the letters in the word "banana": for x in "banana": print(x) Output: b a n a n a
  • 139. 2 April 2022 139 String Length • To get the length of a string, use the len() function. Example • The len() function returns the length of a string: a = "Hello, World!" print(len(a)) Output: 13
  • 140. 2 April 2022 140 Check String To check if a certain phrase or character is present in a string, we can use the keyword in. Example Check if "free" is present in the following text: txt = "The best things in life are free!" print("free" in txt) Output: True
  • 141. 2 April 2022 141 Cont… Use it in an if statement: Example Print only if "free" is present: Example: txt = "The best things in life are free!" if "free" in txt: print("Yes, 'free' is present.") Output: Yes, 'free' is present.
  • 142. 2 April 2022 142 Check if NOT To check if a certain phrase or character is NOT present in a string, we can use the keyword not in. Example Check if "expensive" is NOT present in the following text: txt = "The best things in life are free!" print("expensive" not in txt) Output: True
  • 143. 2 April 2022 143 String Comparison in Python Method 1: Using Relational Operators Method 2: Using is and is not Method 3: Creating a user-defined function
  • 144. 2 April 2022 144 Method 1: Using Relational Operators • The relational operators compare the Unicode values of the characters of the strings from the zeroth index till the end of the string. • It then returns a boolean value according to the operator used. Example: “Geek” == “Geek” will return True as the Unicode of all the characters are equal In case of “Geek” and “geek” as the unicode of G is u0047 and of g is u0067 “Geek” < “geek” will return True and “Geek” > “geek” will return False
  • 145. 2 April 2022 145 Example print("Geek" == "Geek") print("Geek" < "geek") print("Geek" > "geek") print("Geek" != "Geek") Output True True False False
  • 146. 2 April 2022 146 Method 2: Using is and is not • The same is the case for != and is not. Example: str1 = "Geek" str2 = "Geek" str3 = str1 print("ID of str1 =", hex(id(str1))) print("ID of str2 =", hex(id(str2))) print("ID of str3 =", hex(id(str3))) print(str1 is str1) print(str1 is str2) print(str1 is str3) str1 += "s“ str4 = "Geeks" • The == operator compares the values of both the operands and checks for value equality. • Whereas is operator checks whether both the operands refer to the same object or not. print("nID of changed str1 =", hex(id(str1))) print("ID of str4 =", hex(id(str4))) print(str1 is str4) Output ID of str1 = 0x7f6037051570 ID of str2 = 0x7f6037051570 ID of str3 = 0x7f6037051570 True True True ID of changed str1 = 0x7f60356137d8 ID of str4 = 0x7f60356137a0 False
  • 147. 2 April 2022 147 Method 3: Creating a user-defined function. • By using relational operators we can only compare the strings by their unicodes. • In order to compare two strings according to some other parameters, we can make user-defined functions. • In the following code, our user-defined function will compare the strings based upon the number of digits. Example: # function to compare string # based on the number of digits def compare_strings(str1, str2): count1 = 0 count2 = 0 for i in range(len(str1)): if str1[i] >= "0" and str1[i] <= "9": count1 += 1 for i in range(len(str2)): if str2[i] >= "0" and str2[i] <= "9": count2 += 1 return count1 == count2 print(compare_strings("123", "12345")) print(compare_strings("12345", "geeks")) print(compare_strings("12geeks", "geeks12")) Output False False True
  • 148. 2 April 2022 148 Python Logical Operators Python has three logical operators: • and • or • not
  • 149. 2 April 2022 149 The and operator The and operator checks whether two conditions are both True simultaneously: Example: a and b It returns True if both conditions are True. And it returns False if either the condition a or b is False. >>> price = 9.99 >>> price > 9 and price < 10 True The result is True because the price is greater than 9 and less than 10. >>> price > 10 and price < 20 False In this example, the condition price > 10 returns False while the second condition price < 20 returns True.
  • 150. 2 April 2022 150 Cont… a b a and b True True True True False False False False False False True False The following table illustrates the result of the and operator when combining two conditions:
  • 151. 2 April 2022 151 The or operator Similar to the and operator, the or operator checks multiple conditions. But it returns True when either or both of individual conditions are True: Example: a or b The following table illustrates the result of the or operator when combining two conditions: The or operator returns False only when both conditions are False. a b a or b True True True True False True False True True False False False
  • 152. 2 April 2022 152 Cont… The following example shows how to use the or operator: >>> price = 9.99 >>> price > 10 or price < 20 >>> True In this example, the price < 20 returns True, therefore, the whole expression returns True. The following example returns False because both conditions evaluate to False: >>> price = 9.99 >>> price > 10 or price < 5 False
  • 153. 2 April 2022 153 The not operator The not operator applies to one condition. And it reverses the result of that condition, True becomes False and False becomes True. Example not a If the condition is True, the not operator returns False and vice versa. The following table illustrates the result of the not operator: a not a True False False True
  • 154. 2 April 2022 154 Cont… The following example uses the not operator. Since the price > 10 returns False, the not price > 10 returns True: >>> price = 9.99 >>> not price > 10 O/P True Here is another example that combines the not and the and operators: >>> not (price > 5 and price < 10) O/P False
  • 155. 2 April 2022 155 Boolean Variables • In programming you often need to know if an expression is True or False. • You can evaluate any expression in Python, and get one of two answers, True or False. • When you compare two values, the expression is evaluated and Python returns the Boolean answer: Example print(10 > 9) print(10 == 9) print(10 < 9) Output True False False
  • 156. 2 April 2022 156 Example Print a message based on whether the condition is True or False: Example a = 200 b = 33 if b > a: print("b is greater than a") else: print("b is not greater than a") Output b is not greater than a
  • 157. 2 April 2022 157 Evaluate Values and Variables •The bool() function allows you to evaluate any value, and give you True or False in return, Example •Evaluate a string and a number: print(bool("Hello")) print(bool(15)) Output True True Example Evaluate two variables: x = "Hello" y = 15 print(bool(x)) print(bool(y)) Output True True
  • 158. 2 April 2022 158 Repetition Structures in Python • Repetition statements are called loops and are used to repeat the same code multiple times in succession or allowing a set of statements to repeat until stopped!. Python has two types of loops: Condition-Controlled and Count-Controlled. • Condition-Controlled loop uses a true/false condition to control the number of times that it repeats. • While is Condition-Controlled loop. • 'for' loop is known as a Count-Controlled loop. • It repeats a specific number of times. • We can use 'range' function to simplifies count-controlled for loops.
  • 159. 2 April 2022 159 Repetition Statements • Repetition statements are called loops, and are used to repeat the same code multiple times in succession. • Basic syntax: while condition: statement(s) # notice the indent from of this line relative to the while Count-Controlled loop repeats a specific number of times - for. • Basic syntax: for variable in [value1, value2, etc.]: statement(s) # notice the indent from of this line relative to the for
  • 160. 2 April 2022 160 Repetition Structures • Python provides three ways for executing the loops. • While all the ways provide similar basic functionality, they differ in their syntax and condition checking time. While Loop: •In python, while loop is used to execute a block of condition is satisfied. statements repeatedly until a given Syntax : while expression: statement(s)
  • 161. 2 April 2022 161 Cont… • All the statements indented by the same number of character spaces after a programming construct are considered to be part of a single block of code. • Python uses indentation as its method of grouping statements. Example: # Python program to illustrate # while loop count = 0 while (count < 3): count = count + 1 print("Hello Geek") Output: Hello Geek Hello Geek Hello Geek
  • 162. 2 April 2022 162 Using else statement with while loops • while loop executes the block until a condition is satisfied. • When the condition becomes false, the statement immediately after the loop is executed. • The else clause is only executed when your while condition becomes false. • If you break out of the loop, or if an exception is raised, it won’t be executed. while loop like this are similar while condition: # execute these statements else: # execute these statements #Python program to illustrate # combining else with while count = 0 while (count < 3): count = count + 1 print("Hello Geek") else: print("In Else Block") Output: Hello Geek Hello Geek Hello Geek In Else Block
  • 163. 2 April 2022 163 Examples: Condition-Controlled (while) loop: x=1 while x<=5: print ('I will repeat 5 times') x=x+1 Outputs: I will repeat 5 times I will repeat 5 times I will repeat 5 times I will repeat 5 times I will repeat 5 times
  • 164. 2 April 2022 164 For loops: syntax: for variable in [value1, value2, value 3etc.]: statement(s) Example1: for x in (1,2,3): print(x) Output: 1 2 3
  • 165. 2 April 2022 165 Python Loops • Python has two primitive loop commands: • while loops • for loops The while Loop • With the while loop we can execute a set of statements as long as a condition is true. Example Print i as long as i is less than 6: i = 1 while i < 6: print(i) i += 1 Output 1 2 3 4 5
  • 166. 2 April 2022 166 The break Statement •With the break statement we can stop the loop even if the while condition is true: Example •Exit the loop when i is 3: i = 1 while i < 6: print(i) if(i == 3): break i += 1 Output 1 2 3
  • 167. 2 April 2022 167 The continue Statement • With the continue statement we can stop the current iteration, and continue with the next: Example • Continue to the next iteration if i is 3: i = 0 while i < 6: i += 1 ifi == 3: continue print(i) # Note that number 3 is missing in the result
  • 168. 2 April 2022 168 The else Statement while i < 6: print(i) i += 1 else: print("i is no longer less than 6") •With the else statement we can run a block of code once when the condition no longer is true: Example •Print a message once the condition is false: i = 1 Output 1 2 3 4 5 i is no longer less than 6
  • 169. 2 April 2022 169 Python For Loops • A for loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). • This is less like the for keyword in other programming languages, and works more like an iterator method as found in other object-orientated programming languages. • With the for loop we can execute a set of statements, once for each item in a list, tuple, set etc. Example • Print each fruit in a fruit list: fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) Output apple banana cherry
  • 170. 2 April 2022 170 Looping Through a String •Even strings are iterable objects, they contain a sequence of characters: Example •Loop through the letters in the word "banana": for x in "banana": print(x) Output b a n a n a
  • 171. 2 April 2022 171 The break Statement With the break statement we can stop the loop before it has looped through all the items: Example Exit the loop when x is "banana": fruits = ["apple", "banana", "cherry"] for x in fruits: print(x) if x == "banana": break Output apple banana
  • 172. 2 April 2022 172 The continue Statement • With the continue statement we can stop the current iteration of the loop, and continue with the next: Example #Do not print banana: fruits = ["apple", "banana", "cherry"] for x in fruits: if x == "banana": continue print(x) Output apple cherry
  • 173. 2 April 2022 173 The range() Function • To loop through a set of code a specified number of times, we can use the range() function, • The range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. Example • Using the range() function: for x in range(6): print(x) Output: 0 1 2 3 4 5
  • 174. 2 April 2022 174 Cont… Example •Using the start parameter: for x in range(2, 6): print(x) Output 2 3 4 5
  • 175. 2 April 2022 175 Cont… Example •Increment the sequence with 3 (default is 1): for x in range(2, 30, 3): print(x) Output 2 5 8 11 14 17 20 23 26 29
  • 176. 2 April 2022 176 Else in For Loop The else keyword in a for loop specifies a block of code to be executed when the loop is finished: Example •Print all numbers from 0 to 5, and print a message when the loop has ended: for x in range(6): print(x) else: print("Finally finished!") Output 0 1 2 3 4 5 Finally finished!
  • 177. 2 April 2022 177 Nested Loops • A nested loop is a loop inside a loop. • The "inner loop" will be executed one time for each iteration of the "outer loop": Example Print each adjective for every fruit: adj = ["red", "big", "tasty"] fruits = ["apple", "banana", "cherry"] for x in adj: for y in fruits: print(x, y) Output red apple red banana red cherry big apple big banana big cherry tasty apple tasty banana tasty cherry
  • 178. 2 April 2022 178 The pass Statement • for loops cannot be empty, but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error. Example for x in [0, 1, 2]: pass # having an empty for loop like this, would raise an error without the pass statement
  • 179. 2 April 2022 179 Python Data Types • 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, data types are actually classes and variables are instance (object) of these classes. Following are the standard or built-in data type of Python: • Numeric • Sequence Type • Boolean • Set • Dictionary
  • 180. 2 April 2022 180 Python Data Types • In programming, data type is an important concept. • Variables can store data of different types, and different types can do different things. • Python has the following data types built-in by default, in these categories: Text Type str Numeric Types int, float, complex Sequence Types list, tuple, range Mapping Type dict Set Types set, frozenset Boolean Type bool Binary Types bytes, bytearray, memoryview
  • 181. 2 April 2022 181 Setting the Data Type • In Python, the data type is set when you assign a value to a variable: Example Data Type x = "Hello World" str x = 20 int x = 20.5 float x = 1j complex x = ["apple", "banana", "cherry"] list x = ("apple", "banana", "cherry") tuple x = range(6) range x = {"name" : "John", "age" : 36} dict x = {"apple", "banana", "cherry"} set x = frozenset({"apple", "banana", "cherry"}) frozenset x = True bool x = b"Hello" bytes x = bytearray(5) bytearray x = memoryview(bytes(5)) memoryview
  • 182. 2 April 2022 182
  • 183. 2 April 2022 183 Numeric • In Python, numeric data type represent the data which has numeric value. • Numeric value can be integer, floating number or even complex numbers. • These values are defined as int, float and complex class in Python. Integers – • This value is represented by int class. • It contains positive or negative whole numbers (without fraction or decimal). • In Python there is no limit to how long an integer value can be. Float – • This value is represented by float class. • It is a real number with 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 – • Complex number is represented by complex class. • It is specified as (real part) + (imaginary part)j. For example – 2+3j
  • 184. 2 April 2022 184 Example # Python program to # demonstrate numeric value a = 5 print("Type of a: ", type(a)) b = 5.0 print("nType of b: ", type(b)) c = 2 + 4j print("nType of c: ", type(c)) Output: Type of a: <class 'int'> Type of b: <class 'float'> Type of c: <class 'complex'>
  • 185. 2 April 2022 185 Sequence Type • In Python, sequence is the ordered collection of similar or different data types. • Sequences allows to store multiple values in an organized and efficient fashion. • There are several sequence types in Python – • String • List • Tuple
  • 186. 2 April 2022 186 1) String • In Python, Strings are arrays of bytes representing Unicode characters. • A string is a collection of one or more characters put in a single quote, double- quote or triple quote. • In python there is no character data type, a character is a string of length one. • It is represented by str class. Creating String • Strings in Python can be created using single quotes or double quotes or even triple quotes.
  • 187. 2 April 2022 187 Example # Python Program for # Creation of String # Creating a String # with single Quotes String1 = 'Welcome to the CSE World' print("String with the use of Single Quotes: ") print(String1) # Creating a String # with double Quotes String1 = "I'm a Professor" print("nString with the use of Double Quotes: ") print(String1) print(type(String1)) # Creating a String # with triple Quotes String1 = '''I'm a Professor and I live in a world of “CSE"''' print("nString with the use of Triple Quotes: ") print(String1) print(type(String1)) # Creating String with triple # Quotes allows multiple lines String1 = ‘‘’CSE For Life''' print("nCreating a multiline String: ") print(String1) Output: String with the use of Single Quotes: Welcome to the CSE World String with the use of Double Quotes: I'm a Professor <class 'str'> String with the use of Triple Quotes: I'm a Professor and I live in a world of “CSE" <class 'str'> Creating a multiline String: CSE For Life
  • 188. 2 April 2022 188 2) List • Lists are just like the arrays, declared in other languages which is a ordered collection of data. • It is very flexible as the items in a list do not need to be of the same type. Creating List •Lists in Python can be created by just placing the sequence inside the square brackets [ ].
  • 189. 2 April 2022 189 Example # Python program to demonstrate # Creation of List # Creating a List List = [] print("Initial blank List: ") print(List) # Creating a List with # the use of a String List = [‘ComputerScienceEngineering'] print("nList with the use of String: ") print(List) # Creating a List with # the use of multiple values List = [“Computer", “Science", “Computer"] print("nList containing multiple values: ") print(List[0]) print(List[2]) # Creating a Multi-Dimensional List # (By Nesting a list inside a List) List = [[‘Computer', ‘Science'], [‘Engineering']] print("nMulti-Dimensional List: ") print(List)
  • 190. 2 April 2022 190 Output Initial blank List: [] List with the use of String: [‘ComputerScienceEngineering’] List containing multiple values: Computer Computer Multi-Dimensional List: [[‘Computer', ‘Science'], [‘Engineering']]
  • 191. 2 April 2022 191 3) Tuple • Just like list, tuple is also an ordered collection of Python objects. • The only difference between tuple and list is that tuples are immutable i.e. tuples cannot be modified after it is created. • It is represented by tuple class. Creating Tuple • In Python, tuples are created by placing a sequence of values separated by ‘comma’ with or without the use of parentheses for grouping of the data sequence. • Tuples can contain any number of elements and of any datatype (like strings, integers, list, etc.).
  • 192. 2 April 2022 192 Example # Python program to demonstrate # creation of Set # Creating an empty tuple Tuple1 = () print("Initial empty Tuple: ") print (Tuple1) # Creating a Tuple with # the use of Strings Tuple1 = (‘CSE’, ‘Second Year') print("nTuple with the use of String: ") print(Tuple1) # Creating a Tuple with # the use of list list1 = [1, 2, 4, 5, 6] print("nTuple using List: ") print(tuple(list1)) # Creating a Tuple with the # use of built-in function Tuple1 = tuple(‘CSE') print("nTuple with the use of function: ") print(Tuple1) # Creating a Tuple # with nested tuples Tuple1 = (0, 1, 2, 3) Tuple2 = ('python', ‘cse') Tuple3 = (Tuple1, Tuple2) print("nTuple with nested tuples: ") print(Tuple3)
  • 193. 2 April 2022 193 Output Initial empty Tuple: () Tuple with the use of String: (‘CSE', ‘Second Year') Tuple using List: (1, 2, 4, 5, 6) Tuple with the use of function: (‘C', ‘S', ‘E') Tuple with nested tuples: ((0, 1, 2, 3), ('python', ‘cse'))
  • 194. 2 April 2022 194 Boolean • 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). • But non-Boolean objects can be evaluated in Boolean context as well and determined to be true or false. • It is denoted by the class bool. Note – True and False with capital ‘T’ and ‘F’ are valid booleans otherwise python will throw an error.
  • 195. 2 April 2022 195 Cont… # Python program to # demonstrate boolean type print(type(True)) print(type(False)) print(type(true)) Output: <class 'bool'> <class 'bool'>
  • 196. 2 April 2022 196 Set • In Python, Set is an unordered collection of data type 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. Creating Sets • 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 ‘comma’. • Type of elements in a set need not be the same, various mixed-up data type values can also be passed to the set.
  • 197. 2 April 2022 197 Example # Python program to demonstrate # Creation of Set in Python # Creating a Set set1 = set() print("Initial blank Set: ") print(set1) # Creating a Set with # the use of a String set1 = set("GeeksForGeeks") print("nSet with the use of String: ") print(set1) # Creating a Set with # the use of a List set1 = set(["Geeks", "For", "Geeks"]) print("nSet with the use of List: ") print(set1) # Creating a Set with # a mixed type of values # (Having numbers and strings) set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks']) print("nSet with the use of Mixed Values") print(set1) Output: Initial blank Set: set() Set with the use of String: {'F', 'o', 'G', 's', 'r', 'k', 'e'} Set with the use of List: {'Geeks', 'For'} Set with the use of Mixed Values {1, 2, 4, 6, 'Geeks', 'For'}
  • 198. 2 April 2022 198 Dictionary • Dictionary in Python is an unordered collection of data values, used to store data values like a map, which unlike other Data Types that hold only single value as an element, Dictionary holds 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’. Creating Dictionary • In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces, separated by ‘comma’. • Values in a dictionary can be of any datatype and can be duplicated, whereas keys can’t be repeated and must be immutable. • Dictionary can also be created by the built-in function dict(). • An empty dictionary can be created by just placing it to curly braces{}.
  • 199. 2 April 2022 199 Example # Creating an empty Dictionary Dict = {} print("Empty Dictionary: ") print(Dict) # Creating a Dictionary # with Integer Keys Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'} print(Dict) # Creating a Dictionary # with Mixed keys Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]} print("nDictionary with the use of Mixed Keys: ") print(Dict) print("nDictionary with the use of Integer Keys: ") Dict = dict([(1, 'Geeks'), (2, 'For')]) # Creating a Dictionary # with dict() method Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'}) print("nDictionary with the use of dict(): ") print(Dict) # Creating a Dictionary # with each item as a Pair print("nDictionary with each item as a pair: ") print(Dict)
  • 200. 2 April 2022 200 Output Empty Dictionary: {} Dictionary with the use of Integer Keys: {1: 'Geeks', 2: 'For', 3: 'Geeks'} Dictionary with the use of Mixed Keys: {1: [1, 2, 3, 4], 'Name': 'Geeks'} Dictionary with the use of dict(): {1: 'Geeks', 2: 'For', 3: 'Geeks'} Dictionary with each item as a pair: {1: 'Geeks', 2: 'For’}
  • 201. 2 April 2022 201 Different Forms of Assignment Statements in Python • We use Python assignment statements to assign objects to names. • The target of an assignment statement is written on the left side of the equal sign (=), and the object on the right can be an arbitrary expression that computes an object. There are some important properties of assignment in Python :- • Assignment creates object references instead of copying the objects. • Python creates a variable name the first time when they are assigned a value. • Names must be assigned before being referenced. • There are some operations that perform assignments implicitly.
  • 202. 2 April 2022 202 1. Basic form: student = ‘CSE' print(student) Output CSE
  • 203. 2 April 2022 203 2. Tuple assignment: # equivalent to: (x, y) = (50, 100) x, y = 50, 100 print('x = ', x) print('y = ', y) Output x = 50 y = 100
  • 204. 2 April 2022 204 3. List assignment: [x, y] = [2, 4] print('x = ', x) print('y = ', y) Output x = 2 y = 4
  • 205. 2 April 2022 205 4. Sequence assignment: • In recent version of Python, tuple and list assignment have been generalized into instances of what we now call sequence assignment – any sequence of names can be assigned to any sequence of values, and Python assigns the items one at a time by position. a, b, c = 'HEY' print('a = ', a) print('b = ', b) print('c = ', c) Output a = H b = E c = Y
  • 206. 2 April 2022 206 5. Extended Sequence unpacking: p, *q = 'Hello' print('p = ', p) print('q = ', q) OUTPUT p = H q = ['e', 'l', 'l', 'o']
  • 207. 2 April 2022 207 6. Multiple- target assignment: x = y = 75 print(x, y) Output 75 75
  • 208. 2 April 2022 208 7. Augmented assignment : x = 2 # equivalent to: x = x + 1 x += 1 print(x) Output 3 There are several other augmented assignment forms: -=, **=, &=, etc.
  • 209. Thank You 2 April 2022 209