0% found this document useful (0 votes)
35 views

CSE Python R20

Python is a free, open-source, and cross-platform programming language that is easy to code and read. It has a simple syntax compared to languages like C and Java. Python can be used for tasks like data visualization, machine learning, and deep learning. It has many features that make it a popular language like being easy to code, having a large standard library, supporting object-oriented and procedural programming, and being dynamically typed and interpreted. Python supports numeric, string, list, tuple, dictionary, set, and boolean data types.

Uploaded by

Sudhakar B
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views

CSE Python R20

Python is a free, open-source, and cross-platform programming language that is easy to code and read. It has a simple syntax compared to languages like C and Java. Python can be used for tasks like data visualization, machine learning, and deep learning. It has many features that make it a popular language like being easy to code, having a large standard library, supporting object-oriented and procedural programming, and being dynamically typed and interpreted. Python supports numeric, string, list, tuple, dictionary, set, and boolean data types.

Uploaded by

Sudhakar B
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 56

Python Programming & Data Science (20A05101T) KLMCEW

Introduction of Python
Python is a free, open-source programming language. Python is also a cross-platform
compatible language.
So, what does this mean?

It means you can install and run Python on several operating systems. Whether you have a
Windows, Mac, or Linux, you can rest assured that Python will work on all these operating systems.

Python is also a great visualization tool. It provides libraries such as Matplotlib, Seaborn, and bokeh to
create stunning visualizations.

Python is the most popular language for Machine learning and deep Learning.

Why Python?

If you compare Python with any other language, for example, C or Java or C++, then you will find that
its syntax is a way lot easier. You also don’t have to worry about the missing semicolons (;) in the end!

Suppose we want to print “Welcome to the world of programming” on our screen. Let’s compare the
syntax for C and Python:

C Syntax:

#include<stdio.h>
int main(){
printf(“Welcome to the world of programming”);
}

Python Syntax:

print(“Welcome to the world of programming”)

So here we see that Python code consists of only one line, but for Java, there are multiple lines of code
just for printing a statement.

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 1


Python Programming & Data Science (20A05101T) KLMCEW

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 2


Python Programming & Data Science (20A05101T) KLMCEW

Features of Python
1. Easy
 Easy to CodePython is very easy to code as compared to other popular languages like Java
and C++
 Easy to Readbeing a high-level language, Python code is quite like English. Looking at it, you
can tell what the code is supposed to do. Also, since it is dynamically-typed, it mandates
indentation. This aids readability.

2. Expressive First, let’s learn what expressiveness is. Suppose we have two languages A and B,
and all programs that can be made in A can be made in B using local transformations.
However, there are some programs that can be made in B, but not in A, using local
transformations. Then, B is said to be more expressive than A.
 Python provides us with a myriad of constructs that help us focus on the solution rather than on
the syntax. This is one of the outstanding python features that tell you why you should learn
Python.

3. Free and Open-SourceFirstly, Python is freely available. You can download it from the Python
Official Website (https://python.org).
Secondly, it is open-source. This means that its source code is available to the public. You can
download it, change it, use it, and distribute it.
This is called FLOSS(Free/Libre and Open Source Software).

4. High-LevelPython is a high-level language. This means that as programmers, we don’t need to


remember the system architecture.

5. PortableLet’s assume you’ve written a Python code for your Windows machine. Now, if you
want to run it on a Mac or Ubuntu, you don’t need to make changes to it for the same. In other
words, you can take one code and run it on any machine. This makes Python a portable language.
However, you must avoid any system-dependent features in this case.
6. Interpretedif you’re familiar with any languages like C++ or Java, you must first compile it, and
then run it. But in Python, there is no need to compile it. Internally, its source code is converted
into an immediate form called bytecode. So, all you need to do is to run your Python code without
worrying about linking to libraries, and a few other things.
By interpreted, we mean the source code is executed line by line, and not all at once. Because of
this, it is easier to debug your code. Also, interpreting makes it just slightly slower than Java, but
that does not matter compared to the benefits it offers.
7. Object-OrientedA programming language that can model the real world is said to be object-
oriented. It focuses on objects and combines data and functions. Contrarily, a procedure-oriented
language revolves around functions, which are code that can be reused. Python supports both
procedure-oriented and object-oriented programming which is one of the key python features. It

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 3


Python Programming & Data Science (20A05101T) KLMCEW
also supports multiple inheritances, unlike Java. A class is a blueprint for such an object. It is an
abstract data type and holds no values.
8. Extensibleif needed, you can write some of your Python code in other languages like C++. This
makes Python an extensible language, meaning that it can be extended to other languages.

9. Embeddablewe just saw that we can put code in other languages in our Python source code.
However, it is also possible to put our Python code in a source code in a different language like C++.
This allows us to integrate scripting capabilities into our program of the other language.
10. Large Standard LibraryPython downloads with a large library that you can use so you don’t
have to write your own code for every single thing. There are libraries for regular expressions,
documentation-generation, unit-testing, web browsers, threading, databases, CGI, email, image
manipulation, and a lot of other functionality.

11. GUI Programming Software is not user-friendly until its GUI is made. A user can easily interact
with the software with a GUI. Python offers various libraries for making Graphical user interface for
your applications. For this, you can use Tkinter, wxPython or JPython. These toolkits allow you for
easy and fast development of GUI.

12. Dynamically TypedPython is dynamically-typed. This means that the type for a value is decided
at runtime, not in advance. This is why we don’t need to specify the type of data while declaring it.

Data Types in Python


Numeric:
Numeric is called as Numbers. The Numeric are classified into
three group

 Integer: It is whole number. It is effectively no limit to


how long an integer value can be.

>>>print(123123123123123123123123123123123123123123123123+1)
123123123123123123123123123123123123123123123124
 Python interprets a sequence of decimal digits without any prefix to be a decimal number:

>>>print(10)
10
The following strings can be prepended to an integer value to indicate a base other than 10:

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 4


Python Programming & Data Science (20A05101T) KLMCEW

 Complex Numbers
Complex Numbers are specified as <real part>+<imaginary part>j. For example:

 Floating-point Numbers
The float type in Python designates a floating-point number. float values are specified with a
decimal point

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 5


Python Programming & Data Science (20A05101T) KLMCEW

Almost all platforms represent Python float values as 64-bit “double-precision” values, according to
the IEEE 754 standard. In that case, the maximum value a floating-point number can have is
approximately 1.8 ⨉ 10308. Python will indicate a number greater than that by the string inf:

The closest a nonzero number can be to zero is approximately 5.0 ⨉ 10-324. Anything closer to zero
than that is effectively zero:

Floating point numbers are represented internally as binary (base-2) fractions.

Dictionaries Data type:


Python provides another composite data type called a dictionary, which is similar to a list in that it is a
collection of objects.

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 6


Python Programming & Data Science (20A05101T) KLMCEW
Dictionaries are Python’s implementation of a data structure that is more generally known as an
associative array. A dictionary consists of a collection of key-value pairs. Each key-value pair maps the
key to its associated value.

You can define a dictionary by enclosing a comma-separated list of key-value pairs in curly braces ({}). A
colon (:) separates each key from its associated value:

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 7


Python Programming & Data Science (20A05101T) KLMCEW
Boolean Data Types:
Python 3 provides a Boolean data type. Objects of Boolean type may have
one of two values, True or False:

Sets:
Set is collection of elements or group of elements. Python’s built-in set type has the following
characteristics:
 Sets are unordered.
 Set elements are unique. Duplicate elements are not allowed.
 A set itself may be modified, but the elements contained in the set must be of an immutable
type.
A set can be created in two ways. First, you can define a set with the built-in set() function:
>>>X = set(<iter>)

Strings are also iterable, so a string can be passed to set() as well. You have already seen that list(s)
generates a list of the characters in the string s. Similarly, set(s) generates a set of the characters in s:

Alternately, a set can be defined with curly braces ({}):


x={<obj>,<obj>,...,<obj>}

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 8


Python Programming & Data Science (20A05101T) KLMCEW
When a set is defined this way, each <obj> becomes a distinct element of the set, even if it is an
iterable. This behavior is similar to that of the .append() list method.

Thus, the sets shown above can also be defined like this:

Observe the difference between these two set definitions:


>>>{'foo'} >>>set('foo')
{'foo'} {'o', 'f'}

A set can be empty. However, recall that Python interprets empty curly braces ({}) as an empty
dictionary, so the only way to define an empty set is with the set() function:

You might think the most intuitive sets would contain similar objects—for example, even numbers or
surnames:

>>>s1={2,4,6,8,10}
>>>s2={'Smith','McArthur','Wilson','Johansson'}

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 9


Python Programming & Data Science (20A05101T) KLMCEW
Python does not require this, though. The elements in a set can be objects of different types:

>>>x={42,'foo',3.14159,None}
>>>x
{None, 'foo', 42, 3.14159}
>>>x={42,'foo',(1,2,3),3.14159}
>>>x
{42, 'foo', 3.14159, (1, 2, 3)}

But lists and dictionaries are mutable, so they can’t be set elements:

Sequence type:
Sequence type is collection elements in linear way. The Sequence type are classified into three group

 Strings:

Strings are sequences of character data. The string type in Python is called str.

String literals may be delimited using either single or double quotes. All the characters between the
opening delimiter and matching closing delimiter are part of the string:

>>>print("I am a string.")
I am a string.
>>>type("I am a string.")
<class 'str'>
>>>print('I am too.')
I am too.
>>>type('I am too.')
<class 'str'>

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 10


Python Programming & Data Science (20A05101T) KLMCEW
A string in Python can contain as many characters as you wish. The only limit is your machine’s
memory resources. A string can also be empty:

>>>''
''
What if you want to include a quote character as part of the string itself? Your first impulse might be to
try something like this:

>>>print('This string contains a single quote (')character.')


SyntaxError: invalid syntax
>>>print("This string contains a single quote (') character.")
This string contains a single quote (') character.
>>>print('This string contains a double quote (") character.')
This string contains a double quote (") character.
Escape Sequences in Strings

Sometimes, you want Python to interpret a character or sequence of characters within a string
differently. This may occur in one of two ways:

 You may want to suppress the special interpretation that certain characters are usually given
within a string.
 You may want to apply special interpretation to characters in a string which would normally be
taken literally.

You can accomplish this using a backslash (\) character. A backslash character in a string indicates that
one or more characters that follow it should be treated specially.

The following is a table of escape sequences which cause Python to suppress the usual special
interpretation of a character in a string:

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 11


Python Programming & Data Science (20A05101T) KLMCEW

>>>print('a
SyntaxError: EOL while scanning string literal
>>>print('a\
... b\
... c')
abc
>>>print('foo\\bar')
foo\bar
>>>print('foo\tbar')
foo bar

Escape Sequence “Escaped” Interpretation


\a ASCII Bell (BEL) character
\b ASCII Backspace (BS) character
\f ASCII Formfeed (FF) character
\n ASCII Linefeed (LF) character
\N{<name>} Character from Unicode database with
given <name>
\r ASCII Carriage Return (CR) character
\t ASCII Horizontal Tab (TAB) character
\uxxxx Unicode character with 16-bit hex value xxxx
\Uxxxxxxxx Unicode character with 32-bit hex
value xxxxxxxx
\v ASCII Vertical Tab (VT) character
\ooo Character with octal value ooo
\xhh Character with hex value hh

Examples:

>>>print("a\tb")
a b
>>>print("a\141\x61")
aaa
>>>print("a\nb")
a
b
>>>print('\u2192 \N{rightwards arrow}')
→ →
>>>print('foo\nbar')
foo
bar
>>>print(r'foo\nbar')

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 12


Python Programming & Data Science (20A05101T) KLMCEW

foo\nbar

>>>print('foo\\bar')
foo\bar
>>>print(R'foo\\bar')
foo\\bar
>>>print('''This string has a single (') and a double (") quote.''')
This string has a single (') and a double (") quote.
>>>print("""This is a
string that spans
across several lines""")
This is a
string that spans
across several lines

 List:
Lists are used to store multiple items in a single variable. Lists are a very useful variable type in
Python. A list can contain a series of values. List variables are declared by using brackets [
] following the variable name.

The important characteristics of Python lists are as follows:

* Lists are ordered.


* Lists can contain any arbitrary objects.
* List elements can be accessed by index.
* Lists can be nested to arbitrary depth.
* Lists are mutable.
* Lists are dynamic.

A = [ ] # This is a blank list variable


B = [1, 23, 45, 67] # this list creates an initial list of 4 numbers.
C = [2, 4, 'john'] # lists can contain different variable types.
mylist = ['Rhino', 'Grasshopper', 'Flamingo', 'Bongo']
B = len(mylist) # This will return the length of the list which is 3.
The index is 0,
1, 2, 3.
print(mylist[1])# This will return the value at index 1, which is
'Grasshopper'
print(mylist[0:2])# This will return the first 3 elements in the list.
mylist = [0, 1, 2, 3]

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 13


Python Programming & Data Science (20A05101T) KLMCEW
mylist[0] = 'Rhino'
mylist[1] = 'Grasshopper'
mylist[2] = 'Flamingo'
mylist[3] = 'Bongo'
print (mylist[1]) # This will return the value at index 1, which is
'Grasshopper'
print (mylist) # This will return all the value

>>>a=['foo','bar','baz','qux']
>>>b=['baz','qux','bar','foo']
>>>a==b
False
>>>aisb
False

>>>[1,2,3,4]==[4,1,3,2]
False
>>>a=[2,4,6,8]
>>>a
[2, 4, 6, 8]
>>>a=[21.42,'foobar',3,4,'bark',False,3.14159]
>>>a
[21.42, 'foobar', 3, 4, 'bark', False, 3.14159]
>>>int
<class 'int'>
>>>len
<built-in function len>
>>>deffoo():
... pass
...
>>>foo
<function foo at 0x035B9030>
>>>importmath
>>>math
<module 'math' (built-in)>

>>>a=[int,len,foo,math]
>>>a
[<class 'int'>, <built-in function len>, <function foo at 0x02CA2618>,

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 14


Python Programming & Data Science (20A05101T) KLMCEW

<module 'math' (built-in)>]


>>>a=[]
>>>a
[]

>>>a=['foo']
>>>a
['foo']

>>>a=[0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,
... 21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,
... 41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,
... 61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,
... 81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100]
>>>a
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39,
40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58,
59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77,
78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96,
97, 98, 99, 100]
>>>a=['bark','meow','woof','bark','cheep','bark']
>>>a
['bark', 'meow', 'woof', 'bark', 'cheep', 'bark']

>>>a[0]
'foo'
>>>a[2]
'baz'
>>>a[5]
'corge'
>>>a[-1]

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 15


Python Programming & Data Science (20A05101T) KLMCEW

'corge'
>>>a[-2]
'quux'
>>>a[-5]
'bar'
>>>a=['foo','bar','baz','qux','quux','corge']

>>>a[2:5]
['baz', 'qux', 'quux']
 Both positive and negative indices can be specified:

>>>a[-5:-2]
['bar', 'baz', 'qux']
>>>a[1:4]
['bar', 'baz', 'qux']
>>>a[-5:-2]==a[1:4]
True

 Omitting the first index starts the slice at the beginning of the list, and omitting the
second index extends the slice to the end of the list:

>>>print(a[:4],a[0:4])
['foo', 'bar', 'baz', 'qux'] ['foo', 'bar', 'baz', 'qux']
>>>print(a[2:],a[2:len(a)])
['baz', 'qux', 'quux', 'corge'] ['baz', 'qux', 'quux', 'corge']

>>>a[:4]+a[4:]
['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
>>>a[:4]+a[4:]==a
True
 You can specify a stride—either positive or negative:

>>>a[0:6:2]
['foo', 'baz', 'quux']
>>>a[1:6:2]
['bar', 'qux', 'corge']
>>>a[6:0:-2]
['corge', 'qux', 'bar']

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 16


Python Programming & Data Science (20A05101T) KLMCEW
 The syntax for reversing a list works the same way it does for strings:

>>>a[::-1]
['corge', 'quux', 'qux', 'baz', 'bar', 'foo']
 The [:] syntax works for lists.

>>>s='foobar'
>>>s[:]
'foobar'
>>>s[:]iss
True
>>>a=['foo','bar','baz','qux','quux','corge']
>>>a[:]
['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
>>>a[:]isa
False
>>>a
['foo', 'bar', 'baz', 'qux', 'quux', 'corge']

>>>'qux'ina
True
>>>'thud'notina
True
 The concatenation (+) and replication (*) operators:
>>>a
['foo', 'bar', 'baz', 'qux', 'quux', 'corge']
>>>a+['grault','garply']
['foo', 'bar', 'baz', 'qux', 'quux', 'corge', 'grault', 'garply']
>>>a*2
['foo', 'bar', 'baz', 'qux', 'quux', 'corge', 'foo', 'bar', 'baz',
'qux', 'quux', 'corge']
 The len(), min(), and max() functions:

>>>a
['foo', 'bar', 'baz', 'qux', 'quux', 'corge']

>>>len(a)
6
>>>min(a)

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 17


Python Programming & Data Science (20A05101T) KLMCEW

'bar'
>>>max(a)
'qux'

To define matrix
MyTable variable is a two-dimensional array :
MyTable = [[], []]
 Tuple:
Tuples are a group of values like a list and are manipulated in similar ways. But, tuples are fixed in
size once they are assigned. In Python the fixed size is considered immutable as compared to a
list that is dynamic and mutable. Tuples are defined by parenthesis ().

myGroup = ('Rhino', 'Grasshopper', 'Flamingo', 'Bongo')

print(myGroup)

Here are some advantages of tuples over lists:

1. Elements to a tuple. Tuples have no append or extend method.


2. Elements cannot be removed from a tuple.
3. You can find elements in a tuple, since this doesn’t change the tuple.
4. You can also use the in operator to check if an element exists in the tuple.
5. Tuples are faster than lists. If you’re defining a constant set of values and all you’re ever going to
do with it is iterate through it, use a tuple instead of a list.
6. It makes your code safer if you “write-protect” data that does not need to be changed.

>>>t=('spam','egg','bacon','tomato','ham','lobster')
>>>t
('spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster')
>>>type(t)
<class 'tuple'>

>>>t[0]
'spam'
>>>t[-1]
'lobster'
>>>t[3:6]
('tomato', 'ham', 'lobster')
>>>t[1:4]
('egg', 'bacon', 'tomato')
>>>t[0:6:2]
('spam', 'bacon', 'ham')

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 18


Python Programming & Data Science (20A05101T) KLMCEW

>>>t[::-1]
('lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam')

>>>t
('spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster')
>>>t[2]
'bacon'
>>>t[2]='butter'
Traceback (most recent call last):
File "<input>", line 1, in <module>
t[2]='butter'
TypeError: 'tuple' object does not support item assignment

>>>a='spam'
>>>b=42
>>>a,3.14159,b
('spam', 3.14159, 42)
>>>t=()
>>>type(t)
<class 'tuple'>
>>>t
()

>>>t=(1,2)
>>>type(t)
<class 'tuple'>
>>>t=(2)
>>>t
2
>>>type(t)
<class 'int'>

>>>t=(2,)
>>>type(t)
<class 'tuple'>
>>>t
(2,)

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 19


Python Programming & Data Science (20A05101T) KLMCEW

Operators in Python
In Python, operators are special symbols that designate that some sort of computation should be
performed. The values that an operator acts on are called operands.

Here is an example:

A sequence of operands and operators, like a + b - 5, is called an expression. Python supports many
operators for combining data objects into expressions. These are explored below.

Arithmetic Operators
The following table lists the arithmetic operators supported by Python:

Operator Example Meaning Result


+ (unary) +a Unary Positive aIn other words, it doesn’t really do anything. It
mostly exists for the sake of completeness, to
complement Unary Negation.
+ (binary) a + b Addition Sum of a and b
- (unary) -a Unary Negation Value equal to a but opposite in sign
- (binary) a - b Subtraction b subtracted from a
* a * b Multiplication Product of a and b
/ a / b Division Quotient when a is divided by b.
The result always has type float.
% a % b Modulo Remainder when a is divided by b
// a // b Floor Division (also Quotient when a is divided by b, rounded to the
called Integer Division) next smallest whole number
** a ** b Exponentiation a raised to the power of b

Comparison Operators

Operator Example Meaning Result


== a == b Equal to True if the value of a is equal to the value
of bFalse otherwise
!= a != b Not equal to True if a is not equal to bFalse otherwise
< a < b Less than True if a is less than bFalse otherwise
<= a <= b Less than or True if a is less than or equal to b
equal to

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 20


Python Programming & Data Science (20A05101T) KLMCEW
False otherwise
> a > b Greater than True if a is greater than bFalse otherwise
>= a >= b Greater than or True if a is greater than or equal
equal to to bFalse otherwise

Logical Operators
The logical operators not, or, and and modify and join together expressions evaluated in Boolean
context to create more complex conditions.

Logical Expressions Involving Boolean Operands


As you have seen, some objects and expressions in Python actually are of Boolean type. That is, they
are equal to one of the Python objects True or False.

Interpretation of logical expressions involving not, or, and and is straightforward when the operands
are Boolean:

Operator Example Meaning


Not not x True if x is FalseFalse if x is True
(Logically reverses the sense of x)
Or x or y True if either x or y is TrueFalse otherwise
and x and y True if both x and y are TrueFalse otherwise

“not” and Boolean Operands


x=5
notx<10
False
notcallable(x)
True

Operand Value Logical Expression Value


x < 10 True not x < 10 False
callable(x) False not callable(x) True

“or” and Boolean Operands


x=5
x<10orcallable(x)
True
x<0orcallable(x)
False

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 21


Python Programming & Data Science (20A05101T) KLMCEW

Operand Value Operand Value Logical Expression Value


x < 10 True callable(x) False x < 10 or callable(x) True
x < 0 False callable(x) False x < 0 or callable(x) False

“and” and Boolean Operands


x=5
x<10andcallable(x)
False
x<10andcallable(len)
True
Operand Value Operand Value Logical Expression Value
x < 10 True callable(x) False x < 10 and callable(x) False
x < 10 True callable(len) True x < 10 or callable(len) True

“not” and Non-Boolean Operands


Here is what happens for a non-Boolean value x:

If x is not x is
“truthy” False
“falsy” True

Here are some concrete examples:


>>>x=3
>>>bool(x)
True
>>>notx
False

>>>x=0.0
>>>bool(x)
False
>>>notx
True

Similar like “or” & “and”


>>>f(1)andf(False)andf(2)andf(3)
->f(1) = 1
->f(False) = False

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 22


Python Programming & Data Science (20A05101T) KLMCEW

False

>>>f(1)andf(0.0)andf(2)andf(3)
->f(1) = 1
->f(0.0) = 0.0
0.0

Selecting a Default Value

Another idiom involves selecting a default value when a specified value is zero or empty. For example,
suppose you want to assign a variable s to the value contained in another variable called string. But if
string is empty, you want to supply a default value.

Here is a concise way of expressing this using short-circuits evaluation:

s=stringor'<default_value>'
>>>string='foo bar'
>>>s=stringor'<default_value>'
>>>s
'foo bar'

Chained Comparisons

Comparison operators can be chained together to arbitrary length. For example, the following
expressions are nearly equivalent:
x<y<=z
x<yandy<=z
x<f()<=z# Here f() is a user function
x<f()andf()<=z

Bitwise Operators
Bitwise operators treat operands as sequences of binary digits and operate on them bit by bit. The
following operators are supported:
Operator Exam Meaning Result
ple
& a & b bitwise AND Each bit position in the result is the
logical AND of the bits in the corresponding
position of the operands. (1 if both are 1,
otherwise 0.)
| a | b bitwise OR Each bit position in the result is the logical OR of

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 23


Python Programming & Data Science (20A05101T) KLMCEW
the bits in the corresponding position of the
operands. (1 if either is 1, otherwise 0.)
~ ~a bitwise negation Each bit position in the result is the logical
negation of the bit in the corresponding position
of the operand. (1 if 0, 0 if 1.)
^ a ^ b bitwise XOR Each bit position in the result is the
(exclusive OR) logical XOR of the bits in the corresponding
position of the operands. (1 if the bits in the
operands are different, 0 if they are the same.)
>> a >> n Shift right n places Each bit is shifted right n places.
<< a << n Shift left n places Each bit is shifted left n places.
Examples:
>>>0b1100&0b1010
8
>>>0b1100|0b1010
14
>>>0b1100^0b1010
6
>>>0b1100>> 2
3
>>>0b1100<< 2
48

Identity Operators
Python provides two operators, is and is not, that determine whether the given operands have the
same identity—that is, refer to the same object. This is not the same thing as equality, which means
the two operands refer to objects that contain the same data but are not necessarily the same object.
Here is an example of two objects that are equal but not identical:
>>>x=1001
>>>y=1000+1
>>>print(x,y)
1001 1001

>>>x==y
True
>>>xisy
False
Here, x and y both refer to objects whose value is 1001. They are equal. But they do not reference the
same object, as you can verify:
>>>id(x)

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 24


Python Programming & Data Science (20A05101T) KLMCEW

60307920
>>>id(y)
60307936

Unsurprisingly, the opposite of is is is not:


>>>x=10
>>>y=20
>>>xisnoty
True

Operator Precedence
Here is the order of precedence of the Python operators you have seen so far, from lowest to highest:

Description
Operator
lowest Or Boolean OR
precedence
And Boolean AND
Not Boolean NOT
==, !=, <, <=, >, >=, is, is comparisons, identity
not
| bitwise OR
^ bitwise XOR
& bitwise AND
<<, >> bit shifts
+, - addition, subtraction
*, /, //, % multiplication, division, floor division, modulo
+x, -x, ~x unary positive, unary negation, bitwise
negation
highest ** Exponentiation
precedence
>>>2*3**4*5# Here ** is work like as power operator i.e.3 power of 4
810

Augmented Assignment Operators

Assignment operator (=) and list of Augmented operators are


+=, -=, /=, *= and %=,

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 25


Python Programming & Data Science (20A05101T) KLMCEW

Input and Output Function in Python


Reading Input from the Keyboard

Programs often need to read data from the user, usually by way of input from the keyboard. One way
to accomplish this in Python is with input() function:
Syntax:
input([<prompt>])
Example:
>>>user_input=input()
foo bar baz
>>>user_input
'foo bar baz'

If you include the optional <prompt> argument, then input() displays it as a prompt so that your user
knows what to input:

>>>name=input("What is your name? ")


What is your name? Winston Smith
>>>name
'Winston Smith'
input() always returns a string. If you want a numeric type, then you need to convert the string to the
appropriate type with the built-in int(), float(), or complex() function:

Writing Output to the Console

In addition to obtaining data from the user, a program will also usually need to present data back to
the user. You can display program data to the console in Python with print().
To display objects to the console, pass them as a comma-separated list of arguments to print().

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 26


Python Programming & Data Science (20A05101T) KLMCEW
Syntax:
print(<obj>,<obj>,<obj>,…….<obj>)

By default, print() separates objects by a single space and appends a newline to the end of the output:
>>>first_name="Winston"
>>>last_name="Smith"
>>>print("Name:",first_name,last_name)
Name: Winston Smith

print() takes a few additional arguments that provide modest control over the format of the output.
Each of these is a special type of argument called a keyword argument.
>>>print("foo",42,"bar")
foo 42 bar
>>>print("foo",42,"bar",sep="/")
foo/42/bar

>>>print("foo",42,"bar",sep="...")
foo...42...bar

>>>d={"foo":1,"bar":2,"baz":3}
>>>fork,vind.items():
... print(k,v,sep=" -> ")
...
foo -> 1
bar -> 2
baz -> 3

Controlling the Newline Character


The keyword argument end=<str> causes output to be terminated by <str> instead of by the default
newline:
>>>ifTrue:
... print("foo",end="/")
... print(42,end="/")
... print("bar")
foo/42/bar

>>>fornumberinrange(10):
... print(number)
0

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 27


Python Programming & Data Science (20A05101T) KLMCEW

1
2
3
4
5
6
7
8
9
>>>fornumberinrange(10):
... print(number,end=(" "ifnumber<9else"\n"))
...
0 1 2 3 4 5 6 7 8 9
>>>name=input("What is your name? ")
What is your name? Winston
>>>age=int(input("How old are you? "))
How old are you? 24
>>>print(name)
Winston
>>>print(age)
24

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 28


Python Programming & Data Science (20A05101T) KLMCEW

Control flow Statement


Control flow Statements are classified
into three groups. They are
 Conditional Statements
 Iterative Statements
 Transfer Statements

 Conditional Statements
In Python, condition statements act
depending on whether a given condition
is true or false. You can execute
different blocks of codes depending on
the outcome of a condition. Condition
statements always evaluate to either
True or False.

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 29


Python Programming & Data Science (20A05101T) KLMCEW
There are three types of conditional statements.
1. if statement
2. if-else
3. if-elif-else
4. nested if-else

Iterative Statement
Iteration means executing the same block of code over and over, potentially many times. A
programming structure that implements iteration is called a loop.

In programming, there are two types of iteration, indefinite and definite:

 With indefinite iteration, the number of times the loop is executed isn’t specified explicitly in
advance. Rather, the designated block is executed repeatedly as long as some condition is met.
 With definite iteration, the number of times the designated block will be executed is specified
explicitly at the time the loop starts.

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 30


Python Programming & Data Science (20A05101T) KLMCEW

The while Loop

The format of a rudimentary while loop is shown below:

while<expr>:
<statement(s)>

<statement(s)> represents the block to be repeatedly executed, often referred to as the body of the
loop

The controlling expression, <expr>, typically involves one or more variables that are initialized prior to
starting the loop and then modified somewhere in the loop body.

When a while loop is encountered, <expr> is first evaluated in Boolean context. If it is true, the loop
body is executed. Then <expr> is checked again, and if still true, the body is executed again. This
continues until <expr> becomes false, at which point program execution proceeds to the first
statement beyond the loop body.

Example1:
>>>n=5
>>>whilen>0:
n-=1
print(n)
4
3
2
1
0
Example2:
>>>n=0
>>>whilen>0:
... n-=1
... print(n)

In the example above, when the loop is encountered, n is 0. The controlling expression n > 0 is
already false, so the loop body never executes.

Here’s another while loop involving a list, rather than a numeric comparison:

>>>a=['foo','bar','baz']
>>>whilea:
... print(a.pop(-1))

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 31


Python Programming & Data Science (20A05101T) KLMCEW

...
baz
bar
foo

The Python break and continue Statements


In each example you have seen so far, the entire body of the while loop is executed on each iteration.
Python provides two keywords that terminate loop iteration prematurely:
 The Python break statement immediately terminates a loop entirely. Program execution
proceeds to the first statement following the loop body.
 The Python continue statement immediately terminates the current loop iteration. Execution
jumps to the top of the loop, and the controlling expression is re-evaluated to determine
whether the loop will execute again or terminate.

The distinction between break and continue is demonstrated in the following diagram:

Here’s a script file called break.py that demonstrates the


break statement:

n=5
whilen>0:
n-=1
ifn==2:
break
print(n)
print('Loop ended.')

Running break.py from a command-line interpreter


produces the following output:

C:\Users\john\Documents>python break.py
4
3
Loop ended.

When n becomes 2, the break statement is executed. The loop is terminated completely, and program
execution jumps to the print() statement on line 7.

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 32


Python Programming & Data Science (20A05101T) KLMCEW
The next script, continue.py, is identical except for a continue statement in place of the break:

n=5
whilen>0:
n-=1
ifn==2:
continue
print(n)
print('Loop ended.')

The output of continue.py looks like this:

C:\Users\john\Documents>python continue.py
4
3
1
0
Loop ended.

The else Clause


Python allows an optional else clause at the end of a while loop. This is a unique feature of Python, not
found in most other programming languages. The syntax is shown below:

while<expr>:
<statement(s)>
else:
<additional_statement(s)>

The <additional_statement(s)> specified in the else clause will be executed when the while loop
terminates.
You could accomplish the same thing by putting those statements immediately after the while loop,
without the else:

while<expr>:
<statement(s)>
<additional_statement(s)>

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 33


Python Programming & Data Science (20A05101T) KLMCEW
Example1:
>>>n=5
>>>whilen>0:
... n-=1
... print(n)
... else:
... print('Loop done.')
...
4
3
2
1
0
Loop done.

Example2:
>>>n=5
>>>whilen>0:
... n-=1
... print(n)
... ifn==2:
... break
... else:
... print('Loop done.')
...
4
3
2

Example3:
>>>a=['foo','bar','baz','qux']
>>>s='corge'
>>>i=0
>>>whilei<len(a):
... ifa[i]==s:
... # Processing for item found
... break
... i+=1
... else:

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 34


Python Programming & Data Science (20A05101T) KLMCEW

... # Processing for item not found


... print(s,'not found in list.')
...
corge not found in list.

Infinite Loops
Suppose you write a while loop that theoretically never ends. Sounds weird, right?

Consider this example:

>>>whileTrue:
... print('foo')
...
foo
foo
foo
.
.
.
foo
foo
foo
KeyboardInterrupt
Traceback (most recent call last):
File "<pyshell#2>", line 2, in <module>
print('foo')

Here’s another variant of the loop shown above that successively removes items from a list using
.pop() until it is empty:

Example:
>>>a=['foo','bar','baz']
>>>whileTrue:
... ifnota:
... break
... print(a.pop(-1))
...
baz

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 35


Python Programming & Data Science (20A05101T) KLMCEW

bar
foo
When a becomes empty, not a becomes true, and the break statement exits the loop.

You can also specify multiple break statements in a loop:


whileTrue:
if<expr1>:# One condition for loop termination
break
...
if<expr2>:# Another termination condition
break
...
if<expr3>:# Yet another
break
Where there are multiple reasons to end the loop, it is often cleaner to break out from several
different locations, rather than try to specify all the termination conditions in the loop header.
Infinite loops can be very useful. Just remember that you must ensure the loop gets broken out of at
some point, so it doesn’t truly become infinite.

Nested while Loops

In general, Python control structures can be nested within one another. For
example, if/elif/else conditional statements can be nested:
ifage<18:
ifgender=='M':
print('son')
else:
print('daughter')
elifage>=18andage<65:
ifgender=='M':
print('father')
else:
print('mother')
else:
ifgender=='M':
print('grandfather')
else:
print('grandmother')

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 36


Python Programming & Data Science (20A05101T) KLMCEW
Similarly, a while loop can be contained within another while loop, as shown here:

>>>a=['foo','bar']
>>>whilelen(a):
... print(a.pop(0))
... b=['baz','qux']
... whilelen(b):
... print('>',b.pop(0))
...
foo
>baz
>qux
bar
>baz
>qux

A break or continue statement found within nested loops applies to the nearest enclosing loop:
while<expr1>:
statement
statement

while<expr2>:
statement
statement
break# Applies to while <expr2>: loop
break# Applies to while <expr1>: loop

Additionally, while loops can be nested inside if/elif/else statements, and vice versa:
Syntax1:
if<expr>:
statement
while<expr>:
statement
statement
else:
while<expr>:
statement
statement
statement

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 37


Python Programming & Data Science (20A05101T) KLMCEW
Syntax2:
while<expr>:
if<expr>:
statement
elif<expr>:
statement
else:
statement
if<expr>:
statement

In fact, all the Python control structures can be intermingled with one another to whatever extent you
need.

One-Line while Loops


As with an if statement, a while loop can be specified on one line. If there are multiple statements in
the block that makes up the loop body, they can be separated by semicolons (;):
>>>n=5
>>>whilen>0:n-=1;print(n)
4
3
2
1
0

This only works with simple statements though. You can’t combine two compound statements into one
line. Thus, you can specify a while loop all on one line as above, and you write an if statement on one
line:
>>>ifTrue:print('foo')
Foo

But you can’t do this:


>>>whilen>0:n-=1;ifTrue:print('foo')
SyntaxError: invalid syntax

Python Range() function


The range() function generates a list of numbers. This is very useful when creating new lists or when
using for loops: it can be used for both.

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 38


Python Programming & Data Science (20A05101T) KLMCEW
The range() function takes parameter, which must be integers. They can be both positive and negative.
By default, it creates a list of numbers starting from zero, as parameter the stop value is defined

range(stop)

But you can define the starting number of the sequence and then step size.

range(start, stop, step)


Example:
x =list(range(100))
print(x)
...
0,1,2,3,…………….100

x =list(range(1,101))
print(x)
...
1,2,3,…………….100

i=range(0,100,10):
... print(i)
...
0, 10, 20, 30, 40, 50, 60, 70, 80, 90

Numeric Range Loop


The most basic for loop is a simple numeric range statement with start and end values. The exact
format varies depending on the language but typically looks something like this:

fori=1to10
<loopbody>

Here, the body of the loop is executed ten times. The variable i assumes the value 1 on the first
iteration, 2 on the second, and so on. This sort of for loop is used in the languages BASIC, Algol, and
Pascal.

Another form of for loop popularized by the C programming language contains three parts:

* An initialization
* An expression specifying an ending condition
* An action to be performed at the end of each iteration.

This type of loop has the following form:

for(i=1;i<=10;i++)
<loopbody>

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 39


Python Programming & Data Science (20A05101T) KLMCEW
The Python for Loop
Python’s for loop looks like this:

for<var>in<iterable>:
<statement(s)> [

<iterable> is
a collection of objects—for example, a list or tuple. The <statement(s)> in the loop
body are denoted by indentation, as with all Python control structures, and are executed
once for each item in <iterable>. The loop variable <var> takes on the value of the next
element in <iterable> each time through the loop.

Here is a representative example:


>>>a=['foo','bar','baz']
>>>foriina:
... print(i)
...
foo
bar
baz
In this example, <iterable> is the list a, and <var> is the variable i. Each time through the
loop, i takes on a successive item in a, so print() displays the values 'foo', 'bar', and 'baz',
respectively. A for loop like this is the Pythonic way to process the items in an iterable.

Iterables
In Python, iterable means an object can be used in iteration. The term is used as:

 An adjective: An object may be described as iterable.


 A noun: An object may be characterized as an iterable.

If an object is iterable, it can be passed to the built-in Python function iter(), which returns something
called an iterator

Each of the objects in the following example is an iterable and returns some type of iterator when
passed to iter():

>>>iter('foobar')# String
<str_iterator object at 0x036E2750>

>>>iter(['foo','bar','baz'])# List
<list_iterator object at 0x036E27D0>

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 40


Python Programming & Data Science (20A05101T) KLMCEW

>>>iter(('foo','bar','baz'))# Tuple
<tuple_iterator object at 0x036E27F0>

>>>iter({'foo','bar','baz'})# Set
<set_iterator object at 0x036DEA08>

>>>iter({'foo':1,'bar':2,'baz':3})# Dict
<dict_keyiterator object at 0x036DD990>

These object types, on the other hand, aren’t iterable:

>>>iter(42)# Integer
Traceback (most recent call last):
File "<pyshell#26>", line 1, in <module>
iter(42)
TypeError: 'int' object is not iterable

>>>iter(3.1)# Float
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
iter(3.1)
TypeError: 'float' object is not iterable

>>>iter(len)# Built-in function


Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
iter(len)
TypeError: 'builtin_function_or_method' object is not iterable

Here is an example using the same list as above:


>>>a=['foo','bar','baz']

>>>itr=iter(a)
>>>itr
<list_iterator object at 0x031EFD10>

>>>next(itr)
'foo'
>>>next(itr)

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 41


Python Programming & Data Science (20A05101T) KLMCEW

'bar'
>>>next(itr)
'baz'

Python for Loop

Term Meaning
Iteration The process of looping through the objects or items in a
collection
Iterable An object (or the adjective used to describe an object)
that can be iterated over
Iterator The object that produces successive items or values from
its associated iterable
iter() The built-in function used to obtain an iterator from an
iterable
Now, consider again the simple for loop presented at the start of this tutorial:

>>>a=['foo','bar','baz']
>>>for i in a:
... print(i)
...
foo
bar
baz
This loop can be described entirely in terms of the concepts you have just learned about. To carry out
the iteration this for loop describes, Python does the following:

* Calls iter() to obtain an iterator for a


* Calls next() repeatedly to obtain each item from the iterator in turn
* Terminates the loop when next() raises the StopIteration exception

The loop body is executed once for each item next() returns,
with loop variable i set to the given item for each iteration.

This sequence of events is summarized in the following


diagram:

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 42


Python Programming & Data Science (20A05101T) KLMCEW
Iterating Through a Dictionary Example:

>>>d={'foo':1,'bar':2,'baz':3}
>>>forkind:
... print(k)
...
foo
bar
baz
>>>forkind:
... print(d[k])
...
1
2
3
>>>forvind.values():
... print(v)
...
1
2
3
>>>d.items()
dict_items([('foo', 1), ('bar', 2), ('baz', 3)])
>>>d={'foo':1,'bar':2,'baz':3}
>>>fork,vind.items():
... print('k =',k,', v =',v)
...
k = foo , v = 1
k = bar , v = 2
k = baz , v = 3

Using range() in for loop Example:

>>>fornin(0,1,2,3,4):
... print(n)
...
0
1

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 43


Python Programming & Data Science (20A05101T) KLMCEW

2
3
4
returns an iterable that yields integers starting with 0, up to but not
range(<end>)
including <end>:
>>>x=range(5)
>>>x
range(0, 5)
>>>type(x)
<class 'range'>
>>>forninx:
... print(n)
...
0
1
2
3
4
>>>list(x)
[0, 1, 2, 3, 4]

>>>tuple(x)
(0, 1, 2, 3, 4)
>>>list(range(5,20,3))
[5, 8, 11, 14, 17]
>>>list(range(5,10,1))
[5, 6, 7, 8, 9]
>>>list(range(5,10))
[5, 6, 7, 8, 9]
>>>list(range(-5,5))
[-5, -4, -3, -2, -1, 0, 1, 2, 3, 4]

>>>list(range(5,-5))
[]
>>>list(range(5,-5,-1))
[5, 4, 3, 2, 1, 0, -1, -2, -3, -4]

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 44


Python Programming & Data Science (20A05101T) KLMCEW
The break and continue Statements

break and continue work the same way with for loops as with while loops. break terminates the loop
completely and proceeds to the first statement following the loop

>>>foriin['foo','bar','baz','qux']:
... if'b'ini:
... break
... print(i)
...
foo
continue terminates the current iteration and proceeds to the next iteration:
>>>foriin['foo','bar','baz','qux']:
... if'b'ini:
... continue
... print(i)
...
foo
qux

The else Clause

A for loop can have an else clause as well. The interpretation is analogous to that of a while loop.
The else clause will be executed if the loop terminates through exhaustion of the iterable:

>>>foriin['foo','bar','baz','qux']:
... print(i)
... else:
... print('Done.')# Will execute
...
foo
bar
baz
qux
Done.

The else clause won’t be executed if the list is broken out of with a break statement:
>>>foriin['foo','bar','baz','qux']:
... ifi=='bar':
... break

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 45


Python Programming & Data Science (20A05101T) KLMCEW

... print(i)
... else:
... print('Done.')# Will not execute
...
foo

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 46


Python Programming & Data Science (20A05101T) KLMCEW

Sequence Types — list, tuple, range


Operation Result
x in s True if an item of s is equal to x, else False
x not in s False if an item of s is equal to x, else True
s + t the concatenation of s and t
s * n or n * s equivalent to adding s to itself n times
s[i] ith item of s, origin 0
s[i:j] slice of s from i to j
s[i:j:k] slice of s from i to j with step k
len(s) length of s
min(s) smallest item of s
max(s) largest item of s
index of the first occurrence of x in s (at or after index i and
s.index(x[, i[, j]])
before index j)
s.count(x) total number of occurrences of x in s
Mutable Sequence Types
s[i] = x item i of s is replaced by x
s[i:j] = t slice of s from i to j is replaced by the contents of the iterable t
del s[i:j] same as s[i:j] = []
s[i:j:k] = t the elements of s[i:j:k] are replaced by those of t
del s[i:j:k] removes the elements of s[i:j:k] from the list
appends x to the end of the sequence (same
s.append(x)
as s[len(s):len(s)] = [x])
s.clear() removes all items from s (same as del s[:])
s.copy() creates a shallow copy of s (same as s[:])
extends s with the contents of t (for the most part the same
s.extend(t) or s += t
as s[len(s):len(s)] = t)
s *= n updates s with its contents repeated n times
s.insert(i, x) inserts x into s at the index given by i (same as s[i:i] = [x])
s.pop() or s.pop(i) retrieves the item at i and also removes it from s
s.remove(x) remove the first item from s where s[i] is equal to x
s.reverse() reverses the items of s in place

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 47


Python Programming & Data Science (20A05101T) KLMCEW

String Methods

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 48


Python Programming & Data Science (20A05101T) KLMCEW

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 49


Python Programming & Data Science (20A05101T) KLMCEW

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 50


Python Programming & Data Science (20A05101T) KLMCEW

Dictionary Methods

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 51


Python Programming & Data Science (20A05101T) KLMCEW

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 52


Python Programming & Data Science (20A05101T) KLMCEW

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 53


Python Programming & Data Science (20A05101T) KLMCEW

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 54


Python Programming & Data Science (20A05101T) KLMCEW

List Methods

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 55


Python Programming & Data Science (20A05101T) KLMCEW

SUSHAKAR BATHALA ASST.PROFESSOR CSE DEPT 56

You might also like