0% found this document useful (0 votes)
8 views147 pages

Introduction to Python Programming Guide

The document provides an introduction to Python programming, including its history, features, and installation instructions. It emphasizes the importance of practicing coding, understanding basic syntax, and utilizing various resources for learning. Additionally, it outlines the applications of Python and lists its keywords and their functions.

Uploaded by

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

Introduction to Python Programming Guide

The document provides an introduction to Python programming, including its history, features, and installation instructions. It emphasizes the importance of practicing coding, understanding basic syntax, and utilizing various resources for learning. Additionally, it outlines the applications of Python and lists its keywords and their functions.

Uploaded by

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

PYTHON

PROGRAMMIN
g
G
Python_Programmin Raksha
Adyanthaya
1
UNIT-1
INTRODUCTION TO
PYTHON 2
Tips to Keep in Mind While Learning Python
◦ 1. Make it Clear Why We Want to Learn
◦2. Learn the Basic Syntax
◦3. Write Code by Own
◦4. Keep Practicing
◦5. Make Notes as Needed
◦6. Discuss Concepts with Other
◦7. Do small Projects
◦8. Teach Others

3
Python_Programmin
What is Python??
◦ It is a high-level object-oriented programming language that was created by Guido van Rossum in 1991 and
further developed by the Python Software Foundation.

◦ Its syntax allows programmers to express their concepts in fewer lines of code.

◦ Python is also known as a general-purpose programming language, as it is used in the domains given below:

• Web Development

• Software Development

• Game Development

• AI & ML

• Data Analytics

Python_Programmin 4
g
List of top programming language 2021.
The list of programming languages is based on popularity

5
Python_Programmin
How do we get started?
◦ Now, in the era of the digital world, there is a lot of information available on the internet that
might confuse us when we are trying to learn something new. However, with an introduction to
Python programming, we can make a good start. What we can do is follow the documentation
which is a good starting point for learning Python.
◦ Following are references where we can start our journey:
◦ Official Website: [Link]
◦ Udemy Course: [Link]
the-complete-python-developer- course/
◦ YouTube: [Link]
◦ Codechef: [Link]

Python_Programmin 6
g
We can use any IDE[integrated development environmentof] ///…\\\\some IDE’s below

for python:

◦ 1) Visual Studio: [Link]

◦ 2) PyCharm: [Link]

◦ 3) Spyder: [Link]

◦ 4) Atom: [Link]

◦ 5) Google Colab: [Link]

◦ 6)Annaconda:

Python_Programmin 7
g
Python Installations
◦One has to have Python installed on their system in order to start creating Python code
and carrying out many fascinating and helpful procedures. The first step in learning
how to programming in Python is to install or update Python on your computer. There
are several ways to install Python: you may use a package manager, get official
versions from [Link], or install specialized versions for embedded devices,
scientific computing, and the Internet of Things.
◦In order to become Python developer, the first step is to learn how to install or update
Python on a local machine or computer. In this tutorial, we will discuss the installation
of Python on various operating systems.

Python_Programmin 8
g
◦ Installation on Windows
◦ Visit the link [Link] to download the latest release of Python. In this process, we will
install Python 3.11.3 on our Windows operating system. When we click on the above link, it will bring
us the following page.

Python_Programmin
◦ Step - 1: Select the Python's version to download.
◦ Click on the download button to download the exe file of Python.

Python_Programmin 10
g
If in case you want to download the specific version of Python. Then, you can scroll down further below to
see different versions from 2 and 3 respectively. Click on download button right next to the version
number you want to download.

◦ If in case you want to download the specific version of Python. Then, you can
scroll down further below to see different versions from 2 and 3 respectively. Click
on download button right next to the version number you want to download.

1
1
Python_Programmin
Step - 2: Click on the Install Now
◦ Double-click the executable file, which is downloaded.

Python_Programmin 12
g
Python_Programmin 13
g
Step - 3 Installation in Process

1
4
Python_Programmin
Python_Programmin 15
g
Python_Programmin 16
g
Python command line and IDE’s

The Python script is basically a file containing code written in Python.
◦ The file containing python script has the extension ‘.py’ or can also have the extension ‘.pyw’ if it
is being run on a windows machine.
◦To run a python script, we need a python interpreter that needs to be downloaded and
installed. Here is a simple python script to print Hello World!

 print('Hello World!’) Output:Hello World!

 Print (63*56) Output 3528

Python_Programmin 17
g
Different ways to run Python Script
◦ Here are the ways with which we can run a Python script.

◦Interactive Mode
◦Command Line
◦Text Editor (VS Code)

Python_Programmin 18
g
[Link] Mode
◦ In Interactive Mode, you can run your script line by line in a sequence.
◦ To enter in an interactive mode, you will have to open Command Prompt on your windows machine
and
type ‘python’ and press Enter.
◦ Example 1:

Python_Programmin 19
g
Example 2:
◦Run the following lines one by one in the interactive
mode:

◦name = "Aakash"
◦print("My name is " + name)

Python_Programmin 20
g
Example 3:
◦ Run the following line one by one in the interactive
mode:

◦a = 1
◦b = 3
◦ if a > b:
◦ print("a is Greater")
◦ else:
◦ print("b is Greater")

Python_Programmin 21
g
2. Command Line
◦ To run a Python script store in a ‘.py’ file in command line, we have to write ‘python’
keyword before the file name in the command prompt.
◦ python [Link]

Python_Programmin 22
g
3. Text Editor (VS
Code)
◦ To run Python script on a text editor like VS Code (Visual Studio Code) then you will have to do
the following:
◦ Go in the extension section or press ‘Ctrl+Shift+X’ on windows, then search and install the extension
named ‘Python’ and ‘Code Runner’. Restart your vs code after that.
◦ Now, create a new file with the name ‘[Link]’ and write the below code in it:
◦ print('Hello World!')
◦ Then, right click anywhere in the text area and select the option that says ‘Run Code’ or press
‘Ctrl+Alt+N’ to run the code.

Python_Programmin 23
g
◦Creating a Comment

◦Comments can be used to make the code more readable.

◦Comments can be used to prevent execution when testing


code.

◦SINGLELINE COMMENT

◦EXAMPLE :
#This is a comment
print("Hello, World!")

2
4
Python_Programmin
◦ Multiline COMMENT
◦ Python does not really have a syntax for multiline comments.
◦ To add a multiline comment you could insert a # for each line And “ ”
”:
◦ EXAMPLE: #This is a comment
#written in
#more than just one line
print("Hello, World!")
◦ OR/-
◦ Example:
◦ """
This is a comment
written in
more than just one line
"""
print("Hello, World!")

Python_Programmin 25
g
SIMPLE PYTHON PROGRAM

# Python3 program to a d d two


numbers num1 = 15
num2 = 12

# Adding two
nos sum = num1
+ num2

# printing values OR
print("Sum of “{0}
a n d {1} is
{2}”.format(
num1, num2 ,
sum))

Python_Programmin 26
g
Reason for increasing popularity
1. Emphasis on code readability, shorter codes, ease of writing

2. Programmers can express logical concepts in fewer lines of code in comparison to


languages such as C++ or Java.

3. Python supports multiple programming paradigms, like object-oriented, imperative


and functional programming or procedural.

4. There exists inbuilt functions for almost all of the frequently used concepts.

5. Philosophy is “Simplicity is the best”.

Python_Programmin 27
g
PYTHON HISTORY AND VERSIONS
• Python laid its foundation in the late 1980s.

• The implementation of Python was started in December 1989 by Guido Van Rossum at CWI in Netherland.

• In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to [Link].

• In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.

• Python 2.0 added new features such as list comprehensions[used to generate new sequences based on existing sequences],
garbage collection systems[the process of automatic deletion of unwanted or unused objects to free the memory]

• On December 3, 2008, Python 3.0 (also called "Py3K") was released

• ABC programming language is said to be the predecessor of Python language, which was capable of Exception Handling and
interfacing with the Amoeba Operating System.

• The following programming languages influence Python:


• ABC language.
• Modula-3

28
Python_Programmin
g
PYTHON HISTORY AND VERSIONS-
CONT……

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

◦ The comedy series was creative and well random. It talks about everything. Thus it is slow and
unpredictable, which made it very interesting.

Python_Programmin 29
g
FEATURES OF PYTHON
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. 3
0
Python_Programmin
◦ 4) Cross-platform Language
◦ Python can run equally on different platforms such as Windows, Linux, UNIX, and , etc. So, we can say
that Python is a portable language.
◦ It enables programmers to develop the software for several competing platforms by writing a program only
once.
◦ 5) Free and Open Source
◦ Python is freely available for everyone.
◦ It is freely available on its official website [Link].
◦ The open-source means, "Anyone can download its source code without paying any penny."
◦ 6) Object-Oriented Language

◦ Python supports object-oriented language and concepts of classes and objects come into existence.

◦ It supports inheritance, polymorphism, and encapsulation, etc.

◦ The object-oriented procedure helps to programmer to write reusable code and develop applications in less
code.
3
1
Python_Programmin
◦ 7) Extensible
◦ It implies that other languages such as C/C++ can be used to compile the code and thus it can be used further
in our Python code. It converts the program into byte code, and any platform can use that byte code.
◦ 8) Large Standard Library
◦ It provides a vast range of libraries for the various fields such as machine learning, web developer, and also
for the scripting. There are various machine learning libraries, such as Tensor flow, Pandas, Numpy, Keras,
and Pytorch, etc. Django, flask, pyramids are the popular framework for Python web development.
◦ 9) Integrated
◦ It can be easily integrated with languages like C, C++, and JAVA, etc. Python runs code line by line like
C,C++ Java. It makes easy to debug the code.
◦ 10. Dynamic Memory Allocation
◦ In Python, we don't need to specify the data-type of the variable. When we assign some value to the variable,
it automatically allocates the memory to the variable at run time. Suppose we are assigned integer value 15
to x, then we don't need to write int x = 15. Just write x = 15.

3
2
Python_Programmin
Application of
Python
• Desktop Applications
• Web Applications
• Data Science
• Artificial Intelligence
• Machine Learning
• Scientific Computing
• Robotics
• Internet of Things (IoT)
• Gaming
• Mobile Apps
• Data Analysis and Preprocessing

Python_Programmin 33
g
PYTHON HISTORY AND VERSIONS-CONT……

◦Python Version List


◦ Python programming language is being updated regularly with new features and supports.
◦ There are lots of update in Python versions, started from 1994 to current release.
•Python 3.11.4, documentation released on 6 June 2023.
•Python 3.11.3, documentation released on 5 April 2023.
•Python 3.11.2, documentation released on 8 February 2023.
•Python 3.11.1, documentation released on 6 December
2022.
•Python 3.11.0, documentation released on 24 October 2022.
◦ Etc……..

Python_Programmin 34
g
Keywords in Python
◦Python Keywords are some predefined and reserved words in python that
have special meanings. Keywords are used to define the syntax of the coding.
◦Rules for Keywords in Python
•Python keywords cannot be used as identifiers.
•All the keywords in python should be in lowercase except True and False.
•Example: OUTPUT:
◦# code ['False', 'None', 'True', 'and', 'as',
'assert', 'async', 'await', 'break',
◦import keyword 'class',
'continue', 'def', 'del', 'elif', 'else',
◦print([Link]) 'except', 'finally', 'for', 'from',
'global',
'if', 'import', 'in', 'is', 'lambda',
'nonlocal', 'not', 'or', 'pass', 'raise',
'return', 'try', 'while', 'with', 'yield']
35
Keywords Description

and This is a logical operator which returns true if both the operands are true else returns
false.
or This is also a logical operator which returns true if anyone operand is true else returns
false.
not This is again a logical operator it returns True if the operand is false else returns
false.
if This is used to make a conditional statement.
elif is a condition statement used with an if statement. The elif statement is executed if
elif
the
previous conditions were not true.
else
Else is used with if and elif conditional statements. The else block is executed if the
for given condition is not true.
while This is used to create a loop.
break This keyword is used to create a while
loop. This is used to terminate the loop.
def This is used to create an alternative. 3
6
It helps us to define functions.
Identifiers in Python
◦Identifier is a user-defined name given to a variable, function, class, module, etc.
◦The identifier is a combination of character digits and an underscore.
◦They are case-sensitive i.e., ‘num’ and ‘Num’ and ‘NUM’ are three different
identifiers in python.
◦It is a good programming practice to give meaningful names to identifiers to make the
code understandable.
◦Rules for Naming Python Identifiers
•It cannot be a reserved python keyword.
•It should not contain white space.
•It can be a combination of A-Z, a-z, 0-9, or underscore.
•It should start with an alphabet character or an underscore ( _ ).
•It should not contain any special character other than an underscore ( _ ).
3
7
Python_Programmin
Examples for Identifier in
Python ◦Valid identifiers:
•var1
•_var1
•_1_var
•var_1
◦Invalid Identifiers
•!var1
•1var
•1_var
•var#1
•var 1

Python_Programmin 3
g 8
Python Variables
◦ Variable is a name that is used to refer to memory location.
◦ Python variable is also known as an identifier and used to hold value.
◦ In Python, we don't need to specify the type of variable because Python is a infer language and
smart enough to get variable type.
◦ Variable names can be a group of both the letters and digits, but they have to begin with a
letter or an underscore.
◦ It is recommended to use lowercase letters for the variable name. Rahul and rahul both are two
different variables.
◦ Note: Variables are identifier, So rules to declare an variables is same as the Identifiers.

3
9
Python_Programmin
Declaring Variable and Assigning Values
◦Python does not bind us to declare a variable before using it in the application.
◦It allows us to create a variable at the required time.
◦We don't need to declare explicitly variable in Python.
◦When we assign any value to the variable, that variable is
automatically.
declared
◦The equal (=) operator is used to assign value to a variable.

Python_Programmin 4
g 0
◦Example 1:
◦a = 50

◦In the above image, the variable a refers to an integer object.


◦Example 2:
◦Suppose we assign the integer value 50 to a new variable b.
◦a = 50
◦b = a
◦Example 3:
◦Let's assign the new value to b. Now both variables will refer to the different
objects.
◦a = 50
◦b =100
4
1
Python_Programmin
Multiple Assignment
Python allows us to assign a value to multiple variables in a single statement, which is
also known as multiple assignments.
We can apply multiple assignments in two ways, either by assigning a single value
to multiple variables or assigning multiple values to multiple variables.

Consider the following example.


2. Assigning multiple values to multiple
1. Assigning single value to multiple variables
Eg:
variables:
x=y=z=50 a,b,c=5,10,15
print(x)
Output:
print(y) Output: print a 5
print(z) 50 50 50 print b 10
print c 15

Python_Programmin 42
g
Variable Names
◦ Variable names can be any length can have uppercase, lowercase (A to Z, a to z), the
digit (0-9), and underscore character(_). Consider the following example of valid
variables names.

◦ name = “jhon”
◦ age = 20
Output:
◦ marks = 80.50 jhon
20
80.5
◦ print(name)
◦ print(age)
◦ print(marks)

Python_Programmin 43
g
Object Identity
◦In Python, every created object identifies uniquely in Python.
◦Python provides the guaranteed that no two objects will have the same identifier.
◦The built-in id() function, is used to identify the object identifier.
◦Consider the following examples.
◦Example 1:
a = 50
b=a Output:
print(id(a))
print(id(b)) 140734982691168
# Reassigned variable a 140734982691168
a = 500 2822056960944
print(id(a))

Python_Programmin 44
g
Example 2:
name = "A" The multi-word keywords can be created by the following
Name = "B" method.
naMe = "C" • Camel Case - In the camel case, each word or
NAME = "D" abbreviation in the middle of begins with a capital letter.
There is no intervention of whitespace. For example -
n_a_m_e =
nameOfStudent, valueOfVaraible, etc.
"E" • Pascal Case - It is the same as the Camel Case, but here
_name = "F" the first word is also capital. For example - NameOfStudent,
name_ = "G" etc.
_name_ = "H" •Snake Case - In the snake case, Words are separated by
na56me = "I" the
print(name,Name,naMe,NAME,n_a_m_e,
underscore. ForNAME,
examplen_a_m_e, _name, name_,_name,
- name_of_student, etc. na56me)

OUTPUT:
ABCDEDEFGFI

Python_Programmin 45
g
Python Variable
Types
◦ There are two types of variables in Python - Local variable and Global variable. Let's understand the
following
variables.
1. Local Variable
◦ Local variables are the variables that declared inside the function and have scope within the function.
Let's understand the following example.
Example :
# Declaring a function
def add():
#
a= Defining
20 local
variables. They has
b = 30only within a
Output:
scope
cfunction
=a+b
print("The sum is:", c) The sum is: 50
# Calling a function
add() 4
6
Python_Programmin
◦[Link] Variable
◦Global variables can be used throughout the program, and its
scope is in the entire program. We can use global variables inside
or outside the function.

◦A variable declared outside the function is the global variable by


default. Python provides the global keyword to use global variable
inside the function. If we don't use the global keyword, the function
treats it as a local variable. Let's understand the following example.

4
7
Python_Programmin
EXAMPL
◦E
# Declare a variable and initialize it
◦ x = 101
◦ # Global variable in function
◦ def mainFunction():
◦ # printing a global variable Outpu
◦ global x t: 101
◦ print(x) Welcom
◦ # modifying a global variable e
◦ x = 'Welcome'
Welcom
e
◦ print(x)
◦ mainFunction()
◦ print(x)
4
8
Python_Programmin
Python Statements
◦What are Python Statements?
◦In Python, statements are instructions that perform
some sort of action, but do not produce any value.
◦Statements are used to control the flow of the
program and carry out various tasks, such as defining
variables, making decisions, and looping through
data.
4
9
Python_Programmin
◦Some common examples of Python statements include assignment
statements,
control flow statements (such as if/else, for, and while loops), and import
statements.

◦Statements do not have a return value, and are executed simply for their side
effects. For example, the assignment statement x = 1 assigns the value of 1
to the variable x, but does not produce a value that can be used in further
operations.

Python_Programmin 5
g 0
Here are a few more examples of Python Statements:
◦Assignment Statement: x = 1 assigns the value of 1 to the variable x.
◦Control Flow Statement: if x > 0: print("x is positive") checks if the value of x
is positive and prints a message if it is.
◦Import Statement: import math imports the math module and makes its functions
and constants available for use in the program.
◦For Loop Statement: for i in range(5): print(i) iterates over the range 0 to 4 and
prints each number.
◦While Loop Statement: while x < 5: x += 1 repeatedly increments the value of x until
it is no longer less than 5.
◦Function Definition Statement: def add(a, b): return a + b defines a function that
takes two arguments and returns their sum.
5
1
Python_Programmin
Example of ‘Python Statements’
# Assignment Statement
x=1
# Control Flow Statement
if x > 0:
print("x is positive")
# Import Statement
import math
# For Loop
Statement for i in
range(5):
print(i)
# While Loop
Statement while x < 5:
x += 1
# Function Definition
52
Statement def add(a, b): Raksha
What are Python Expressions?
◦In Python, expressions are code constructs that evaluate to a value. Expressions can
contain variables, operators, and function calls, and can be used in a variety
of contexts, such as assignments, print statements, and return statements.

◦An expression always evaluates to a single value, which can be of any data type
(such as integer, float, string, etc.).

◦For example, 1 + 2 is a simple expression that evaluates to the integer value 3,


while (1 + 2) * 3 is a more complex expression that evaluates to the integer value
9. 53

Python_Programmin
Note:
The key difference between expressions and
statements is that expressions produce a
value, while statements do not.
Expressions are a fundamental part of Python
programming and are used to perform
calculations, make decisions, and produce
output.

54

Python_Programmin
Here are a few examples of expressions in
Python.
1. Arithmetic Expression: 1 + 2 evaluates to the integer value 3.
2. Comparison Expression: 1 < 2 evaluates to the Boolean value
True.
3. String Concatenation Expression: "Hello" + " " +"World" evaluates
to the string value “Hello World”.
4. Function Call Expression: len("Hello") evaluates to the
integer value 5.

Python_Programmin 55
g
Datatypes
◦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.

◦The following are the standard or built-in data types in Python:


◦Numeric
◦Sequence Type
◦Boolean
◦Set
◦Dictionary 56

Python_Programmin
57

Python_Programmin
1. Numeric Data Type in Python
◦The numeric data type in Python represents the data that has a numeric value.

◦A numeric value can be an integer, a floating number, or even a complex number.

◦These values are defined as Python int, Python float, and Python complex classes
in
Python.

i) Integers – This value is represented by int class.

◦It contains positive or negative whole numbers (without fractions or decimals).

58

Python_Programmin
◦In Python, there is no limit to how long an integer value can be.
ii) Float – This value is represented by the float class.
◦It is a real number with a floating-point representation. It is specified by
a decimal point.
◦Optionally, the character e or E followed by a positive or negative integer
may be appended to specify scientific notation.
◦iii) Complex Numbers – Complex number is represented by a
complex class.
◦It is specified as (real part) + (imaginary part)j.
◦For example – 2+3j

Python_Programmin 59
g
EXAMPLE
◦# Python program to demonstrate numeric value
◦a = 5
◦print("Type of a: ", type(a))
Type of a: <class 'int'>
◦b = 5.0 Type of b: <class 'float'>
Type of c: <class 'complex'
◦print("\nType of b: ", type(b)) >

◦c = 2 + 4j
◦print("\nType of c: ", type(c))

60

Python_Programmin
2. Sequence Data Type in Python
◦The sequence Data Type in Python is the ordered collection
of similar or different data types.
◦Sequences allow storing of multiple values in an organized
and efficient fashion. There are several sequence types in
Python :
i. Python String
ii. Python List
iii. Python Tuple

61

Python_Programmin
i. Python String
◦A string is a data structure in Python that represents a sequence of characters.
◦It is an immutable data type, meaning that once you have created a string, you
cannot change it.
◦Strings are used widely in many different applications, such as storing and
manipulating text data, representing names, addresses, and other types of data
that can be represented as text.
◦Example:
◦“Hello" or ‘Hello’

◦[Creating a String in Python Strings in Python can be created using


single quotes or double quotes or even triple quotes. ]

Python_Programmin 62
g
OUTPUT
examples String with the use of Single
Quotes: Welcome to the
World
String with the use of Double Quotes:
hello
# Creating a Stringwith single Quotes
String1 = 'Welcome to the World'
print("String with the use of Single
Quotes: ")
print(String1)

# Creating a String with double Quotes


String1 = “hello"
print("\nString with the use of Double
Quotes: ")
print(String1)
63

Python_Programmin
Accessing characters in Python String
◦In Python, individual characters of a String can be accessed by using the method
of Indexing.
◦Indexing allows negative address references to access characters from the back of
the
String, e.g. -1 refers to the last character, -2 refers to the second last character, and
so on.
◦While accessing an index out of the range will cause an IndexError.
◦Only Integers are allowed to be passed as an index, float or other types that will
cause
a TypeError.

64

Python_Programmin
Python_Programmin 65
g
Example:
◦ # Python Program to
Access
◦ # characters of String
◦ String1 = “Simplicity" OUTPUT:
◦ print("Initial String: ") Initial String: Simplicity
First character of String is:
◦ print(String1)
S Last character of String
is:y
◦ # Printing First character
◦ print("\nFirst character of String is: ")
◦ print(String1[0])

◦ # Printing Last character


◦ print("\nLast character of String is: ")
◦ print(String1[-1])
66

Python_Programmin
Reversing a Python String
◦With Accessing Characters from a string, we can also reverse them.
◦We can Reverse a string by writing [::-1] and the string will be reversed.
◦Example:
◦#Program to reverse a string
◦rvrs = “hellofellow"
◦print(rvrs[::-1])
◦Output:
◦wollefolleh

Python_Programmin 67
g
String Slicing
◦To access a range of characters in the String, the method of slicing
is used. Slicing in a String is done by using a Slicing operator
(colon).
◦ String1
Example = “hellofellow"
1: # Python Program to demonstrate String slicing Creating a String
◦ print("Initial String: ")
OUTPUT:
◦ print(String1) Initial String: hellofellow
◦ # Printing 3rd to 8th character Slicing characters from 3-8: ofell
Slicing characters between 3rd and 2nd
◦ print("\nSlicing characters from 3-8: last character: ofell
")

◦ print(String1[3:8])
# Printing characters between 3rd and 2nd last character
◦ print("\nSlicing characters between " +"3rd and 2nd last character:
")
◦ print(String1[3:-2])
68

Python_Programmin
String Slicing
◦To access a range of characters in the String, the method of slicing
is used. Slicing in a String is done by using a Slicing operator
(colon).
◦ String1
# Python= “hellofellow"
Program to demonstrate String slicing Creating a String
◦ print("Initial String: ")
OUTPUT:
◦ print(String1) Initial String: hellofellow
◦ # Printing 3rd to 8th character Slicing characters from 3-8: ofell
Slicing characters between 3rd and 2nd
◦ print("\nSlicing characters from 3-8: last character: ofell
")

◦ print(String1[3:8])
# Printing characters between 3rd and 2nd last character
◦ print("\nSlicing characters between " +"3rd and 2nd last character:
")
◦ print(String1[3:-2])
69

Python_Programmin
Example 2:
str1 = 'hello’ #string str1
str2 = ' how are you’ #string str2
print (str1[0:2]) #printing first two character using slice
operator print (str1[4]) #printing 4th character of the string
print (str1*2) #printing the string twice
print (str1 + str2) #printing the concatenation of str1 and str2

Python_Programmin 70
g
ii. Python
◦LIST
◦ Lists are used to store multiple items in a single variable.
Lists are one of 4 built-in data types in Python used to store collections of data, the other 3 are Tuple, Set
, and Dictionary, all with different qualities and usage.
◦ Lists in Python are like arrays in C, but lists can contain data of different types. The things put away in the
rundown are isolated with a comma (,) and encased inside square sections [].
◦ To gain access to the list's data, we can use slice [:] operators. Like how they worked with strings, the list is
handled by the concatenation operator (+) and the repetition operator (*).

◦ Lists are created using square brackets:


◦ Example:
◦ Create a List:
◦ thislist = ["apple", "banana", "cherry"]
print(thislist)

Python_Programmin 71
g
◦List Items
◦List items are ordered, changeable, and allow duplicate values.

◦List items are indexed, the first item has index [0], the second item has index [1] etc.

◦Ordered :When we say that lists are ordered, it means that the items have a defined
order, and that order will not change.
◦Note: There are some list methods that will change the order, but in general: the order
of the items will not change.

◦Changeable: The list is changeable, meaning that we can change, add, and remove
items
in a list after it has been created.

◦Allow Duplicates: Since lists are indexed, lists can have items with the same value: 72

Python_Programmin
◦List Items - Data Types
◦List items can be of any data type:
◦Example 1:
◦String, int and boolean data types:
◦list1 = ["apple", "banana",
"cherry"] list2 = [1, 5, 7, 9, 3]
list3 = [True, False, False]

◦Example 2:
◦A list with strings, integers and
boolean values:
◦list1 = ["abc", 34, True, 40, "male"] 73

Python_Programmin Raksha
◦The list() Constructor
◦It is also possible to use the list() constructor
when creating a new list.

◦Example
◦Using the list() constructor to make a List:
◦thislist = list(("apple", "banana", "cherry"))
◦# note the double round-
brackets print(thislist)
Python_Programmin Raksha 74
g Adyanthaya
[Link] TUPLE
◦Tuples are used to store multiple items in a single variable.
◦Tuple is one of 4 built-in data types in Python used to store collections of
data, the other 3 are List, Set, and Dictionary, all with different qualities
and usage.
◦A tuple is a collection which is ordered and unchangeable.
◦Tuples are written with round brackets.
◦Example:
◦Create a Tuple:
◦thistuple = ("apple", "banana", "cherry")
print(thistuple)

75

Python_Programmin Raksha
◦ Tuple Items
◦ Tuple items are ordered, unchangeable, and allow duplicate values.

◦ Tuple items are indexed, the first item has index [0], the second item has index [1]
etc.

◦Ordered : When we say that tuples are ordered, it means


that the items have a defi ned order, a n d that order will not
change.
◦Unchangeable: Tuples are unchangeable, meaning that
we cannot
change, a d d or remove items after the tuple has been
created.
◦Allow Duplicates: Since tuples are indexed, they c a n
have items with the same value:
◦Example: 76
◦ Tuple Length :To determine how many items a tuple has, use the len() function:
◦ Example :
#Print the number of items in the tuple:
◦ thistuple = ("apple", "banana", "cherry")
◦ Print(len(thistuple))

◦ Create Tuple With One Item


◦ To create a tuple with only one item, you have to add a comma after the item, otherwise Python
will not recognize it as a tuple.
◦ Example:
#One item tuple, remember the comma:
◦ thistuple = ("apple",)
print(type(thistuple))
#NOT a tuple
thistuple = ("apple")
print(type(thistuple))
◦ 7
7
Python_Programmin Raksha
◦ Tuple Items - Data Types
◦ Tuple items can be of any data type:
◦ Example 1:
◦ String, int and boolean data types:
◦ tuple1 = ("apple", "banana", "cherry")
tuple2 = (1, 5, 7, 9, 3)
tuple3 = (True, False, False)
◦ Example2:
◦ A tuple can contain different data
types:
◦ A tuple with strings, integers and
boolean values:
◦ tuple1 = ("abc", 34, True, 40, "male")
7
8
Python_Programmin Raksha
3. Python
Dictionary
◦Dictionaries are a useful data structure for storing data in Python because they
are capable of imitating real-world data arrangements where a certain value
exists for a given key.
◦The data is stored as key-value pairs using a Python dictionary.

•This data structure is mutable

•The components of dictionary were made using keys and values.

•Keys must only have one component.

•Values can be of any type, including integer, list, and tuple.


7
9
Python_Programmin Raksha
Creating the Dictionary
◦Curly brackets are the simplest way to generate a Python dictionary, although
there are other approaches as well. With many key-value pairs surrounded in
curly brackets and a colon separating each key from its value, the dictionary
can be built. (:). The following provides the syntax for defining the dictionary.
◦ Syntax:

Dict = {"Name": "Gayle", "Age": 25}

◦ In the above dictionary Dict, The keys Name and Age are the strings which comes under the category
of an immutable object.

8
0
Python_Programmin Raksha
◦Example 1:
◦to create a dictionary and print its content.
Employee = {"Name": "Johnny", "Age": 32, "salary":26000,"Company":"TCS"}
print(type(Employee))
print("printing Employee data ....
print(Employee)
") Output

<class 'dict'>
printing Employee data
....
{'Name': 'Johnny',
'Age': 32, 'salary':
26000, 'Company':
TCS}

8
1
Python_Programmin Raksha
Accessing the dictionary values
◦ To access data contained in lists and tuples, indexing has been studied. The keys of the dictionary can be used
to obtain the values because they are unique from one another. The following method can be used to access
dictionary values.
◦ Example 2:
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}
print("printing Employee data .... ")
print("Name : %s" %Employee["Name"])
print("Age : %d" %Employee["Age"])
print("Salary : %d" %Employee["salary"])
print("Company : %s" %Employee["Company"])

8
2
Python_Programmin Raksha
◦Adding Dictionary Values
◦The dictionary is a mutable data type, and utilising the right
keys allows you to change its values.
◦ Dict[key] = value and the value can both be modified. An
existing value can also be updated using the update() method.
◦Note: The value is updated if the key-value pair is already present
in the dictionary. Otherwise, the dictionary's newly added keys.

Python_Programmin Raksha 8
g Adyanthaya 3
◦ Example
◦ Code
Empty Dictionary:
# Creating an empty Dictionary {}
Dict = {}
print("Empty Dictionary: ") Dictionary after adding 3 elements:
print(Dict) {0: 'Peter', 2: 'Joseph', 3: 'Ricky'}
# Adding elements to
Dictionary after adding 3 elements:
dictionary one at a time
{0: 'Peter', 2: 'Joseph', 3: 'Ricky', 'Emp_ages': (20, 33,
Dict[0] = 'Peter' 24)}
Dict[2] = 'Joseph'
Dict[3] = 'Ricky' after adding 3 elements: ")
print("\nDictionary Updated key value:
print(Dict) {0: 'Peter', 2: 'Joseph', 3: 'JavaTpoint', 'Emp_ages':
(20, 33,
# Adding set of values with a single Key The Emp_ages doesn't exist to dictionary
24)}
Dict['Emp_ages'] = 20, 33, 24
print("\nDictionary after adding 3 elements: ")
print(Dict)
# Updating existing Key's Value
Dict[3] = ’rocky' print("\
nUpdated key value: ")
print(Dict) 8
4
Example 2:
Employee = {"Name": "Dev", "Age": 20, "salary":45000,"Company":"WIPRO"}
print(type(Employee))
print("printing Employee data .... ") <class 'dict'>
printing Employee data ....
print(Employee) Employee = {"Name": "Dev", "Age": 20,
print("Enter the details of the new employee...."); "salary":45000,"Company":"WIPRO"}
Enter the details of the new
Employee["Name"] = input("Name: ");
employee....
Employee["Age"] = int(input("Age: ")); Name:
Employee["salary"] = int(input("Salary: ")); Sunny Age:
38
Employee["Company"] = input("Company:"); Salary: 39000
print("printing the new data"); Company:Hcl
printing the new
print(Employee)
data
{'Name': 'Sunny', 'Age': 38, 'salary':
39000, 'Company': 'Hcl'}

Python_Programmin Raksha 85
g Adyanthaya
Deleting Elements using del Keyword
The items of the dictionary can be deleted by using the del keyword
as given below.
◦ Code
Employee = {"Name": "David", "Age": 30, "salary":55000,"Company":"WIPRO"}
print(type(Employee))
print("printing Employee data .... ") <class 'dict'>
print(Employee) printing Employee data
print("Deleting some of the ....
employee data") {'Name': 'David', 'Age': 30, 'salary':
del Employee["Name"] 55000, 'Company':
del Employee["Company"] 'WIPRO'}
print("printing the modified Deleting some of the employee data
information ") printing the modified information
print(Employee) {'Age': 30, 'salary': 55000}
print("Deleting the dictionary: Deleting the dictionary:
Employee"); Employee
del Employee Lets try to print it again
print("Lets try to print it again ");
NameError: name 'Employee' is
not
print(Employee) Python_Programmin
g
Raksha
Adyanthaya
defined. 86
# Creating a Dictionary
Dict1 = {1: aabc', 2: 'Educational', 3: 'Website'}
# Deleting a key
# using pop() method
pop_key = [Link](2)
print(Dict1) {1: ‘aabc', 3: 'Website'}

Python_Programmin Raksha 87
g Adyanthaya
4.
Set
◦Mathematically a set is a collection of items not in any particular order.
◦A Python set is similar to this mathematical definition with below
additional conditions.

◦The elements in the set cannot be duplicates.

◦The elements in the set are immutable(cannot be modified) but the set as a whole
is mutable.

◦There is no index attached to any element in a python set. So they do not support
any
indexing or slicing operation.
Python_Programmin Raksha 88
g Adyanthaya
◦Set Operations
◦ The sets in python are typically used for mathematical operations like union, intersection,
difference and complement etc. We can create a set, access it’s elements and carry out
these mathematical operations as shown below.
◦ 1. Creating a set
◦ A set is created by using the set() function or placing all the elements within a pair of
curly braces.
◦ Example:
◦ Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
◦ Months={"Jan","Feb","Mar"}
◦ Dates={21,22,17} set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon',
◦ print(Days) 'Thu', 'Sat'])
set(['Jan', 'Mar',
◦ print(Months) 'Feb']) set([17, 21,
◦ print(Dates) 22])

Python_Programmin Raksha 89
g Adyanthaya
Accessing Values in a Set
◦ We cannot access individual values in a set. We c a n only access all the elements
together as shown above. But we c a n also get a list of individual elements by
looping through the set.

◦ Example
◦ Days=set(["Mon","Tue","Wed","Thu","Fri","Sat","Sun"])
◦ for d in Days:
◦ print(d)

9
0
Python_Programmin Raksha
Adding Items to a Set
◦ We c a n a d d elements to a set by using add()
method

◦ Example:
◦ Days=set(["Mon","Tue","Wed","Thu","Fri","Sat"])

◦ [Link]("Sun
")
set(['Wed', 'Sun', 'Fri', 'Tue', 'Mon', 'Thu',
◦ print(Days) 'Sat'])

91
Removing Item from
Set
◦ Example:
◦ Days=set(["Mon","Tue","Wed","Thu","Fri","Sat",
"Sun"])
<class 'set'>
◦ print(type(Days)) {'Mon', 'Thu', 'Wed', 'Sun',
◦ 'Sat', 'Fri', 'Tue'}
◦ print(Days) {'Thu', 'Wed', 'Sun', 'Sat', 'Fri',
◦ [Link]("Mo 'Tue'}
n")
◦ print(Days)

Python_Programmin Raksha 92
g Adyanthaya
Union of Sets
◦ The union operation on two sets produces a new set containing all the
distinct elements from both the sets. In the below example the element
“Wed” is present in both the sets.
◦ Example:
◦ DaysA = set(["Mon","Tue","Wed"])
◦ DaysB =
set(["Wed","Thu","Fri","Sat","Sun"])
{'Sat', 'Fri', 'Mon', 'Thu', 'Wed', 'Sun',
◦ AllDays = DaysA|DaysB 'Tue'}
◦ print(AllDays)

Python_Programmin Raksha 93
g Adyanthaya
Intersection of
Sets
◦ The intersection operation on two sets produces a new set containing only the
co mmo n elements from both the sets. In the below example the element
“Wed” is present in both the sets.
◦ Example:
◦ DaysA = set(["Mon","Tue","Wed"])
◦ DaysB = Output:
set(["Wed","Thu","Fri","Sat","Sun"]) {'Wed'}
◦ AllDays = DaysA & DaysB
◦ print(AllDays)

Python_Programmin Raksha 94
g Adyanthaya
5.
Boolean
◦ Python Boolean type is one of the built-in data types provided by Python,
which represents one of the two values i.e. True or False. Generally, it is used
to represent the truth values of the expressions.
◦For example, 1==1 is True whereas 2<1 is False.
◦Example 2
◦a = 10
◦b = 20
◦# Comparing variables False
◦print(a == b)

Python_Programmin Raksha 95
g Adyanthaya
Python Collections
◦ There(Arrays)
are four collection data types in the Python programming language:

◦ List is a collection which is ordered a n d changeable. Allows duplicate members.


◦ Tuple is a collection which is ordered a n d unchangeable. Allows duplicate members.
◦ Set is a collection which is unordered, unchangeable*, a n d unindexed. N o duplicate
members.
◦ Dictionary is a collection which is ordered** a n d changeable. N o duplicate members.
◦ *Set items are unchangeable, but you c a n remove and/or a d d items whenever you
like.

Python_Programmin Raksha 96
g Adyanthaya
 Operators
◦In Python programming, Operators in general are used to perform
operations on values and variables. These are standard symbols used for
the purpose of logical and arithmetic operations. In this article, we will
look into different types of Python operators.
•OPERATORS: These are the special symbols. Eg- + , * , /, etc.
•OPERAND: It is the value on which the operator is applied.

Python_Programmin Raksha 97
g Adyanthaya
Types of Operators in Python
◦Arithmetic Operators
◦Assignment Operators
◦Comparison Operators
◦Logical Operators
◦Bitwise Operators
◦Identity Operators and Membership
Operators

Python_Programmin Raksha 98
g Adyanthaya
Arithmetic Operators
◦Python Arithmetic operators are used to perform basic mathematical
operations like addition, subtraction, multiplication, and division.
Operator Operation Example
+ Addition 5+2=7

- Subtraction 4-2=2

* Multiplication 2*3=6

/ Division 4/2=2

// Floor Division 10 // 3 = 3

% Modulo 5%2=1
** Power 4 ** 2 = 16 99

Python_Programmin Raksha
Example:
a =7
b =2
# addition Sum: 9
print ('Sum: ', a + Subtraction: 5
Multiplication: 14
b) # subtraction
Division: 3.5
print ('Subtraction: ', a - Floor Division: 3
b) # multiplication Modulo: 1
Power: 49
print ('Multiplication: ', a *
b) #division
print ('Division: ', a / b)
# floor division
print ('Floor Division: ', a //
b) # modulo
print ('Modulo: ', a
% b) # a to the
power b print
100
('Power: ', a ** b)
[Link]
Operators
◦Assignment operators are used to assign values to
variables.
◦For example,

◦# assign 5 to x
◦var x = 5

Python_Programmin Raksha 10
g Adyanthaya 1
Operator Description Syntax

= Assign value of right side of expression to left side operand x=y+z

Add and Assign: Add right side operand with left side operand
+= a += b
and then assign to left operand

Subtract AND: Subtract right operand from left operand and


-= a -= b
then assign to left operand: True if both operands are equal

Multiply AND: Multiply right operand with left operand and then
*= a *= b
assign to left operand

Divide AND: Divide left operand with right operand and then
/= a /= b
assign to left operand
102

Python_Programmin Raksha
Modulus AND: Takes modulus using left and right operands and
%= a %= b
assign result to left operand

Divide(floor) AND: Divide left operand with right operand and


//= a //= b
then assign the value(floor) to left operand

Exponent AND: Calculate exponent(raise power) value using


**= a **= b
operands and assign value to left operand

Performs Bitwise AND on operands and assign value to left


&= a &= b
operand
Performs Bitwise O R on operands and assign value to left
|= a |= b
operand
Performs Bitwise x OR on operands and assign value to left
^= a ^= b
operand
Performs Bitwise right shift on operands and assign value to
>>= a >>= b
left operand
Performs BitPwythiosn_eProlgeramftminsg hift on operands aRankshda 103

<<= a s s i g n value to left operand


A dy an th a ya a <<= b
◦1) Assign: This operator is used to assign the value of the
right side of the expression to the left side operand.

◦Syntax:
◦x = y + z

◦Example :
◦a = 3
◦b = 5
◦c = a + b

◦# Output
◦print(c)
Python_Programmin Raksha 104
g Adyanthaya
2) Add and Assign: This operator is used to add 3) Subtract and Assign: This operator is used to
the right side operand with the left side operand subtract the right operand from the left operand
and then assigning the result to the left operand. and then assigning the result to the left operand.

◦ Synta
◦ Synta x:
x:
◦ x -= y
◦ x +=
y ◦ Example
◦ Example:
◦a = 3
◦a = 3
◦b = 5
◦b = 5
◦# a = a -
◦# a = a b
+ b
◦ a -= b
◦ a += b
◦ print(a)
◦ print(a)
◦ Outpu
◦ Outpu t:
t:
◦ -2
◦8
105
4) Multiply and Assign: This 5) Divide and Assign: This operator is used
operator is used to multiply the right to divide the left operand with the right
operand with the left operand and operand and then assigning the result to
to thethe
then assigning leftresult the left operand.
operand.
◦ Syntax:
◦ Syntax: ◦ x /= y
◦ x *= y

Example: ◦ Example:

◦a = 3 ◦a =3

◦b = 5 ◦b =5
◦#a =a /
◦# a = a *
b
b
◦ a /= b
◦ a *= b
◦ print(a)
◦ print(a)
◦ Output:
◦ Output:
◦ 0.6
◦ 15

Python_Programmin Raksha 106


g Adyanthaya
7) Divide (floor) and Assign: This operator 8) Exponent and Assign: This operator is
is used to divide the left operand with the used to calculate the exponent(raise power)
right operand and then assigning the value using operands and then assigning the
result(floor) to the left operand. result to the left operand.
◦Syntax: ◦ Syntax:
◦x //= y ◦ x **= y

◦Example: ◦ Example:
◦a = 3
◦a = 5
◦b = 5
◦b = 3 ◦ # a = a **
◦# a = a // b b
◦a //= b ◦ a **= b
◦print(a) ◦ print(a)

◦ Output:
◦Output: ◦ 243
◦1
10
7
Python_Programmin Raksha
9) Bitwise AND and Assign: This operator is used to 10) Bitwise OR and Assign: This operator is used
perform Bitwise AND on both operands and then to perform Bitwise OR on the operands and then
assigning the result to the left operand. assigning result to the left operand.

◦ Syntax: ◦ Syntax:
◦ x &= y ◦ x |= y

◦ Example: ◦ Example:
◦a = 3 ◦a = 3
◦b = 5 ◦b = 5
◦# a = a ◦# a = a |
& b b
◦ a &= b
◦ a |= b
◦ print(a)
◦ print(a)
◦ Output:
◦ Output:
◦1
◦7

Python_Programmin Raksha 108


g Adyanthaya
Comparison / Relational
Operators
◦ Relational operators are used for comparing the values. It either returns True or False
according to the condition. These operators are also known as Comparison Operators.

Operator Description Syntax

> Greater than: True if the left operand is greater than the right x>y

< Less than: True if the left operand is less than the right x<y

== Equal to: True if both operands are equal x == y

!= Not equal to – True if operands are not equal x != y

Greater than or equal to: True if left operand is greater than or equal to the
>= x >= y
right

<= Less than or equal to: True if left operand is less than or equal to the right x <= y
Python_Programming Raksha 109
Adyanthaya
Logical Operators
◦ In Python, Logical operators are used on conditional statements (either True or False).
They perform Logical AND, Logical OR and Logical NOT operations.

OPERATOR DESCRIPTION SYNTAX


Logical AND: True if both the operands
and x and y
are true
Logical OR: True if either of the operands
or x or y
is true

not Logical NOT: True if operand is false not x

Python_Programmin Raksha 110


g Adyanthaya
Python_Programmin Raksha 111
g Adyanthaya
# Python program to
demonstrate logical a n d
◦ aoperator
= 10
◦ b = 12
◦c = 0
◦ if a and b and c:
◦ print("All the numbers have boolean value as
True")
◦ else:
◦ print("Atleast one number has boolean value as
False")
Output
Atleast one number has boolean value as False

112
# Python program to
demonstrate logical a n d
operator
◦ a = 10
◦ b = 12
◦c = 0
◦ if a or b or c:
◦ print("Atleast one number has boolean value
as True")
◦ else:
◦ print("All the numbers have boolean value as
False")
Output
Atleast one number has boolean value as True
113
Bitwise
Operators
Bitwise operators are used to perform bitwise calculations on
integers. The integers are first converted into binary and then
operations are performed on each bit or corresponding pair of
bits, hence the name bitwise operators. The result is then
returned in decimal format.
OPERATOR NAME DESCRIPTION SYNTAX

& Bitwise AND Result bit 1,if both operand bits are 1;otherwise results bit 0. x&y

| Bitwise OR Result bit 1,if any of the operand bit is 1; otherwise results bit 0. x|y

~ Bitwise NOT inverts individual bits ~x

Results bit 1,if any of the operand bit is 1 but not both,
^ Bitwise XOR x^y
otherwise results bit 0.

114
Membership operators AND Identity
Operator
◦These two are special operators in Python. These
operators look like English words. Here are the differences and
how to use them.
◦IN THIS PAGE
1. Identity Operator
1. Python logic for IS NOT
2. Python logic for IS
2. Membership operator
1. Python logic for IN
2. Python logic for NOT IN

Python_Programmin Raksha 115


g Adyanthaya
◦ Membership operators are used to identify the membership of a value. These
operators test for membership in a n order, that is, string, lists, or tuples. The
in a n d not in operators are examples of membership operators.

◦ Membership operator
◦ There are two membership operators in python. Those are in & not in.
• IN
• NOT IN

Python_Programmin Raksha 116


g Adyanthaya
◦ Example:

Python logic for IN


c = int(input("Enter the value"))
print ("The value of c is: " + format(c))
lst1 = [12,3,5,6,9]
if c in lst1:
print('c value is available in the list', c in lst1)
else:
print('c value is not available in the list', c in
lst1)

Python_Programmin Raksha 117


g Adyanthaya
Python logic for NOT IN
c = int(input("Enter the value"))
print ("The value of c is: " + format(c))
lst1 = [12,3,5,6,9]
if c in lst1:
print('c value is available in the list', c in lst1)
else:
print('c value is not available in the list', c in
lst1)

Python_Programmin Raksha 118


g Adyanthaya
Identity Operator

◦The are two identity operators in python.


•IS
•IS NOT

Python_Programmin Raksha 119


g Adyanthaya
Python logic for IS

a1 = 'java’
b1 = 'java’
print ('Output is True because a1 and b1 values matches',
a1 is b1)

Python_Programmin Raksha 120


g Adyanthaya
Operato Name
Python r
Operator ()
**
Parenthesis
Exponent
Precedence ~ Bitwise NOT

Python Operator Precedence *, /, %, // Multiplication, Division, Modulo, Floor


(Highest to Lowest) Division
Below is the table containing +, – Addition, Subtraction
the precedence of all >>, << Bitwise right and left shift
operators in Python.
& Bitwise AND
The operators are
listed down in the ^ Bitwise XOR
decreasing order of | Bitwise OR
==, !=, >, <,
Comparison
>=,
<=
=, +=, -=, *=,
Assignment
/=, %=, **=, //=
is, is not Identity
121
In, not in Membership
Operator Name Associativity

Operator ()

**
Parenthesis

Exponent
Left to right

Right to left

Associati ~ Bitwise NOT Left to right

on
Multiplication, Division,
*, /, %, // Left to right
Modulo, Floor Division

+, – Addition, Subtraction Left to right

Associativity is the order in which an >>, << Bitwise right and left shift Left to right
expression with multiple operators of
the same precedence is evaluated. & Bitwise AND Left to right

Associativity can be either from left ^ Bitwise XOR Left to right

to | Bitwise OR Left to right

right or right to left. ==, !=, >, <, >=, <= Comparison Left to right

=, +=, -=, *=, /=,


Assignment Right to left
%=, **=, //=

is, is not Identity Left to right

In, not in Membership Left to right

and, or, not Logical Left to right

122
Control
flow
◦ A program’s control flow is the order in which the program’s c o d e executes.
◦ The control flow of a Python program is regulated by conditional statements,
loops, and
function calls. This section covers the if statement a n d for a n d while loops

Python_Programmin Raksha 123


g Adyanthaya
The if
Statement
◦ Often, you need to execute some statements only if some condition holds, or choose
statements to execute depending on several mutually exclusive conditions.
◦ The Python compound statement if, which uses if, elif, and else clauses

◦ Here’s the syntax for the if statement:

◦ if expression:
◦ statement(s)
◦ elif expression:
◦ statement(s)
◦ elif expression:
◦ statement(s)
◦ ...
◦ else:
◦ statement(s)
◦ [For Example program Refere 12
4
Observation]
Loops in Python

◦Python programming language provides the


following types of loops to handle looping
requirements.

◦ Python provides three ways for executing the


loops.

◦While all the ways provide similar basic


functionality, they differ in their syntax and
Python_Programmin Raksha 125

condition-checking time.
g Adyanthaya
While Loop in Python

◦ In python, a while loop is used to execute a block of statements


repeatedly until a given condition is satisfied.
◦ When the condition becomes false, the line immediately after the
loop in the
program is executed.

◦ Syntax:
◦ while expression:
◦ statement(s)

Python_Programmin Raksha 126


g Adyanthaya
EXAMPLE
◦ # Python program to illustrate while loop
◦count = 0 OUTPUT:
Hello
◦while (count < 3): World
◦ count = count + Hello
World
1 Hello
◦ print("Hello World
World")

Python_Programmin Raksha 127


g Adyanthaya
Using else statement with While
Loop in Python
◦ 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.

◦ Syntax of While Loop with else statement:


◦ while condition:
◦ # execute these statements
◦ else:
◦ # execute these statements

Python_Programmin Raksha 128


g Adyanthaya
# Python program to illustrate
combining else with while
◦count =
◦0
while (count < OUTPUT
◦6): count = count + Hello world
2 Hello world
◦ Hello world
◦else print("Hello In Else
: world")
◦ print("In Else Block
Block")

Python_Programmin Raksha 129


g Adyanthaya
Do while loop

◦ Do while loop is a type of control looping statement that can run any
statement until the condition statement becomes false specified in the loop. In
do while loop the statement runs at least once no matter whether the
condition is false or true.
◦ Syntax:
◦ do{
◦ // statement or
◦ // set of statements
◦}
◦ while(condition)

Python_Programmin Raksha 130


g Adyanthaya
For loops in
python
◦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.

Python_Programmin Raksha 131


g Adyanthaya
The for Statement
◦ The for statement in Python supports repeated execution of a statement
or block of statements that is controlled by an iterable expression.
Here’s the syntax for the for statement:

◦ General Syntax
◦ for itarator_variable in sequence_name:
◦ Statement
s

...

Statement
s

Python_Programmin Raksha 132


g Adyanthaya
◦ # use of range() to define a range of
values
◦ values = range(4)

◦ # iterate from i = 0 to i = 3
◦ for i in values:
◦ print(i)

Python_Programmin Raksha 133


g Adyanthaya
◦ fruits = ["apple", "mango", "cherry"]
◦ for x in fruits:
◦ print(x)

◦ Looping Through a String


◦ Even strings are iterable objects, they contain a sequence of
characters:

◦ Example
◦ Loop through the letters in the word "abcd":

◦ for x in "abcd":
◦ print(x)

Python_Programmin Raksha 134


g Adyanthaya
1. Print individual letters of a
string using the for loop
◦ EXAMPL
◦ E:
word="ABCDE OUTPUT
DF" A

◦ for letter in
print
word: (letter) B
C

E
D
Python_Programmin Raksha 135
g Adyanthaya F
2. Using the for loop to iterate
over a Python list or tuple
◦ words= ["Apple", "Banana", "Car",
"Dolphin" ]
◦ for word in words:
◦ print (word)

◦ Output:
◦ Apple
◦ Banana
◦ Car
◦ Dolphin

Python_Programmin Raksha 136


g Adyanthaya
Now, let’s move ahead and work on
looping
over the elements of a tuple here.
◦ nums = (1, 2, 3, 4)
◦ sum_nums = 0
◦ for num in nums:
◦ sum_nums = sum_nums + num
◦ print(f'Sum of numbers is
{sum_nums}')

◦ # Output
◦ # Sum of numbers is 10

Python_Programmin Raksha 137


g Adyanthaya
3. Nesting Python for loops
◦ words= ["Apple", "Banana", "Car", "Dolphin" ]
◦ for word in words:
◦ #This loop is fetching word from the list
◦ print ("The following lines will print e a c h letters of
"+word)
◦ for letter in word:
◦ #This loop is fetching letter for the word
◦ print (letter)
◦ print("") #This print is used to print a blank line

Python_Programmin Raksha 138


g Adyanthaya
outpu
t

Python_Programmin Raksha 139


g Adyanthaya
4. Python for loop with range()
function
◦ for x in range(3):
◦ print("Printing:",
x)

◦ Output
◦ Printing: 0
◦ Printing: 1
◦ Printing: 2

Python_Programmin Raksha 140


g Adyanthaya
◦ In the below example, I’ve used number 3 as the step a n d you c a n see
the output
numbers are the previous number + 3.

◦ for n in range(1, 10, 3):


◦ print("Printing with step:", n)

◦ # Output

◦ # Printing with step: 1


◦ # Printing with step: 4
◦ # Printing with step: 7

Python_Programmin Raksha 141


g Adyanthaya
•Continue: The continue statement in
Python is used to skip the remaining code
inside a loop for the current iteration only.
• Pass: The pass statement in Python is
used when a statement or a condition is
required to be present in the program, but
we don’t want any command or code to
execute. It’s typically used as a placeholder
for future code.

Python_Programmin Raksha 142


g Adyanthaya
5. break statement with for
loop
◦ Break: A break statement in Python alters the flow of a loop by terminating it
once a specified condition is met.

◦ Example: outpu
◦ for num in t:

◦ range(0,10):
if num == 5:
◦ break
◦ print(f'Iteration:
{num}’)

Python_Programmin Raksha 143


g Adyanthaya
◦ Now, let’s a d d one more for loop outside the existing for loop, as
shown below:
◦ Example 2:
◦ for k in range(0,5):
◦ print(f'Outer For Loop Iteration: {k}')
◦ for num in range(0,10):
◦ if num == 5:
◦ break
◦ print(f'--Inner For Loop Iteration: {num}')

Python_Programmin Raksha 144


g Adyanthaya
Continue Statement in Python
◦ The continue statement is used to skip the remaining c o d e inside a loop for the current
iteration only

◦ Example:
◦ for num in range(0,10):
◦ if num == 5:
◦ continue
◦ print(f'Iteration: {num}')

Python_Programmin Raksha 145


g Adyanthaya
Pass Statement in Python

◦ As its n a me suggests, the pass statement does nothing.


◦ It’s used when a statement or a condition is required to b e present in the
program, but
we d o not want any c o m m a n d or c o d e to execute.
◦ Example:
◦ for num in range(0,10):
◦ if num == 5:
◦ pass
◦ print(f'Iteration: {num}')

Python_Programmin Raksha 146


g Adyanthaya
Question Introduction to Features and Applications of Python
1. What are identifiers? Write the different Rules for Naming Python Identifiers

bank unit 1
2. 2. What is control flow in Python, and why is it important in programming?
3. 3. Define Data Type? Explain the different classification of data type
[Link] is a Comment? Explain the different types of comments? What Are the
Advantages of Using Comments in Python? Explain with example 5. Write a python
program to
a. Find the add two numbers and print its result
b. b. To find the string is palindrome or not
c. 6. Define Variables in Python, Explain the declaration and initialization of variable in
python
[Link] between Keywords and Variables explain with suitable example
[Link] short notes on types of operators in python with appropriate example
[Link] how Python's standard library can be beneficial for developers.
[Link] how the "continue" statement differs from the "break" statement in Python.
With example
[Link] does Python handle conditional execution, and what are the key control flow
statements used for this purpose?
[Link] a Python Program find the factorial of a
[Link] and explain any six features of python.
[Link] about different loop statements in python with example
a. For loop
b. While loop
c. Do while loop

You might also like