0% found this document useful (0 votes)
131 views103 pages

Python Notes

The document outlines a Python syllabus covering various topics in 12 sections. The syllabus introduces Python programming basics like data types, variables, operators, conditional statements, loops, functions, object-oriented programming concepts, file handling, modules, packages, regular expressions and multithreading. It includes concepts like classes, objects, inheritance, polymorphism, encapsulation and exceptions. The syllabus also covers string, list, tuple, dictionary and set manipulations along with Python libraries like NumPy, TensorFlow, OpenCV etc.

Uploaded by

kasarla rakesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
131 views103 pages

Python Notes

The document outlines a Python syllabus covering various topics in 12 sections. The syllabus introduces Python programming basics like data types, variables, operators, conditional statements, loops, functions, object-oriented programming concepts, file handling, modules, packages, regular expressions and multithreading. It includes concepts like classes, objects, inheritance, polymorphism, encapsulation and exceptions. The syllabus also covers string, list, tuple, dictionary and set manipulations along with Python libraries like NumPy, TensorFlow, OpenCV etc.

Uploaded by

kasarla rakesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 103

Python Syllabus

1. Basics Understanding of programming and Data


Types, Variables & Operators
1. Introduction to Python Language
2. How to Install Python and what is IDEs?
3. Hello World Program in Python
4. Comments, Escape Sequences & Print Statement
5. All about Variables and Datatypes..?
6. Type casting..?
7. All about Operators..?
8. Chaining Comparison in Python..?

2. Conditional & Flow Control Statements


1. loops or control statements (for & while)
2. Decision making or Conditional statements (if, else, and elf)
3. User Input

3. String Manipulations and Boolean datatype


1. Python Strings and Inbuilt functions
2. Boolean Variables

4. List and Tuple Manipulations


1. Python List Inbuilt functions
2. Python Tuples-Inbuilt functions

5. Dictionary & set Manipulations


1. Python Sets- Inbuilt functions
2. Python Dictionaries-Inbuilt functions
3. Learnig all data structures again

6. Functions
1. Function with arguments In Python
2. All builtin functions
3. Lambda Functions(map, filter & reduce)
7. Object-Oriented Approach
1. Class, Object & Method.
2. Inheritance in python
3. Polymorphism in python
4. Encapsulation in python
5. Data Abstraction in python
6. Data Hiding & Object Printing
7. Constructors Destructors in Python
8. Garbage Collection in Python

8. Exception Handling
1. Python Exception Handling
2. User-defined Exception
3. Built-in Exception
4. Python Try Except

9. Python File Operations


1. Basics of File Handling in Python
2. Open a File in Python
3. Reading a File in python
4. Writing to a File in python
5. Python seek() & tell () function
6. SQL and MongoDB python libraries basics(Optional)

10. Modules and Packages


1. Python Modules
2. Python Package

11. Regular Expression


1. Regular Expression in Python(Regex)
2. Python Closures, Iterators & Generators

12. Multithreading & Python CGI(Optional)


1. Multithreading in Python
2. CGI Programming in Python
3. Python Collections
1. Basics Understanding
of programming and Data
Types, Variables &
Operators
1. Introduction to Python Language
2. How to Install Python and what is IDEs?
3. Hello World Program in Python
4. Comments, Escape Sequences & Print Statement
5. All about Variables and Datatypes..?
6. Type casting..?
7. All about Operators..?
8. Chaining Comparison in Python..?

1.1 Introduction to Python Language

What is programming...?

Programming is a way for us to tell computers what to do. Computer is a very dumb machine
and it only does what we tell it to do. Hence, we learn programming and tell computers to do
what we are very slow at - computation. If I ask you to calculate 5+6, you will immediately say
11. How about 23453453 X 56456?

What is Python?

Python is a dynamically typed, general purpose programming language that supports an


object-oriented programming approach as well as a functional programming approach.
Python is an interpreted and a high-level programming language.
It was created by Guido Van Rossum in 1989.

Features of Python

Python is simple and easy to understand.


It is Interpreted and platform-independent which makes debugging very easy.
Python is an open-source programming language.
Python provides very big library support. Some of the popular libraries include NumPy,
Tensorflow, Selenium, OpenCV, etc.
It is possible to integrate other programming languages within python.

What is Python used for


Python is used in Data Visualization to create plots and graphical representations.
Python helps in Data Analytics to analyze and understand raw data for insights and trends.
It is used in AI and Machine Learning to simulate human behavior and to learn from past
data without hard coding.
It is used to create web applications.
It can be used to handle databases.
It is used in business and accounting to perform complex mathematical operations along
with quantitative and qualitative analysis.

1.2 How to Install Python and what is IDEs?


Install python : https://www.python.org/ (https://www.python.org/)

What is IDE..?

An integrated development environment (IDE) is a software application that helps


programmers develop software code efficiently. It increases developer productivity by
combining capabilities such as software editing, building, testing, and packaging in an easy-to-
use application. Just as writers use text editors and accountants use spreadsheets, software
developers use IDEs to make their job easier.

1.3 Hello World Program in Python


To print hello world program in python we use print function like below.
print can be used to print something on the console in python

In [1]: 1 print("Hello World")

Hello World

1.4 Comments, Escape Sequences & Print Statement

Comments :
A comment is a part of the coding file that the programmer does not want to execute, rather the
programmer uses it to either explain a block of code or to avoid the execution of a specific part
of code while testing.

Single-Line Comments:

To write a comment just add a ‘#’ at the start of the line.

Example - 1 :
In [2]: 1 # this is comment so this will note execute
2 print("This is actual code")

This is actual code

Example - 2 :

In [5]: 1 print("This is actual code")# this is comment so this will note execute

This is actual code

Example - 3 :

In [6]: 1 print("This is actual code")


2 # this is comment so this will note execute

This is actual code

Multi-Line Comments:

To write multi-line comments you can use ‘#’ at each line or you can use the multiline string.

Example 1: The use of ‘#’.

In [3]: 1 #It will execute a block of code if a specified condition is true.


2 #If the condition is false then it will execute another block of code.
3 p = 7
4 if (p > 5):
5 print("p is greater than 5.")
6 else:
7 print("p is not greater than 5.")

p is greater than 5.

Example 2: The use of multiline string.

In [4]: 1 """This is an if-else statement.


2 It will execute a block of code if a specified condition is true.
3 If the condition is false then it will execute another block of code."""
4 p = 7
5 if (p > 5):
6 print("p is greater than 5.")
7 else:
8 print("p is not greater than 5.")

p is greater than 5.
Escape Sequences :
To insert characters that are illegal in a string, use an escape character.
An escape character is a backslash \ followed by the character you want to insert.
An example of an illegal character is a double quote inside a string that is surrounded by
double quotes:

In [24]: 1 #Without escape charcter


2 txt = "Ramu is the Number "ONE" Person in the world"
3 print(txt)

Input In [24]
txt = "Ramu is the Number "ONE" Person in the world"
^
SyntaxError: invalid syntax

In [27]: 1 #Without escape charcter


2 txt = "Ramu is the Number \"ONE\" Person in the world"
3 print(txt)

Ramu is the Number "ONE" Person in the world

Other escape sequence charcters:


Char Description

' Single Quote

\ Backslash

\n New Line

\r Carriage Return

\t Tab

\b Backspace

\f Form Feed

\ooo Octal value

\xhh Hex value

In [4]: 1 txt = "It\'s ok"


2 print(txt)

It's ok
In [29]: 1 txt = "This will insert one \\ (backslash)."
2 print(txt)

This will insert one \ (backslash).

In [30]: 1 txt = "This will insert new line \n(newline)."


2 print(txt)

This will insert new line


(newline).

Print Statement :
The syntax of a print statement looks something like this:
print(object(s), sep=separator, end=end, file=file, flush=flush)

Other Parameters of Print Statement

1. object(s): Any object, and as many as you like. Will be converted to string before printed
2. sep='separator': Specify how to separate the objects, if there is more than one. Default is
''
3. end='end': Specify what to print at the end. Default is '\n' (line feed)
4. file: An object with a write method. Default is sys.stdout
Parameters 2 to 4 are optional

In [33]: 1 print("Python")

Python

Practical on print function:

In [34]: 1 # all element will print by seperation space


2 a = 45
3 print("Rakesh",a,67)

Rakesh 45 67

END Argument

In [35]: 1 # with out end every print display in separete line.


2 for i in range(1,5):
3 print(i)

1
2
3
4
In [36]: 1 # we can use end to make then one line with space seperation
2 for i in range(1,5):
3 print(i,end=" ")

1 2 3 4

In [37]: 1 for i in [1,2,3,4]:


2 print(i,end=" % ")

1 % 2 % 3 % 4 %

SEP Argument

In [39]: 1 #sep argument is used to seperate the elements with in print function
2 print("rakesh",a,67,sep=" --> ")

rakesh --> 45 --> 67

Difference between end and sep:

End is used to between two print statements.


Sep is used to within elements in print.

In [3]: 1 print(1,2,3,4,end="-->")

1 2 3 4-->

In [5]: 1 print(1,2,3,4,sep="-->")

1-->2-->3-->4

In [4]: 1 for i in range(5):


2 print(i,end="-->")

0-->1-->2-->3-->4-->

In [6]: 1 for i in range(5):


2 print(i,sep="-->")

0
1
2
3
4
In [8]: 1 for i in range(5):
2 print(i,i+1,sep="-->")

0-->1
1-->2
2-->3
3-->4
4-->5

file : Is used to store output in seperate file.

In [41]: 1 f = open("sample.txt","w")
2 for i in [1,2,3,4]:
3 print(i,file=f)
4 f.close()

Flush:

The flush parameter in Python's print function controls whether the output is immediately
flushed or buffered. By default, the print() function buffers the output, which means that it may
not be immediately displayed on the screen or written to a file. However, you can force the
output to be flushed immediately by setting the flush parameter to True.

1.5 All about Variables and datatypes ..?

Variables
Variables are containers for storing data values.

Creating Variables
Python has no command for declaring a variable.
A variable is created the moment you first assign a value to it.

In [2]: 1 a = "Python"
2 b = 200

Variables do not need to be declared with any particular type, and can even change variable
type after they have been set.
In [3]: 1 a = 100 # This is int type
2 b = "Python" # this is STR type
3 print(a,b)

100 Python

Get the Type


You can get the data type of a variable with the type() function.

Example

In [5]: 1 x = 5
2 y = "John"
3 print(type(x))
4 print(type(y))

<class 'int'>
<class 'str'>

Casting
If you want to specify the data type of a variable, this can be done with casting.

Example

In [7]: 1 x = str(3) # x will be '3'


2 y = int(3) # y will be 3
3 z = float(3) # z will be 3.0
4 print(type(x))
5 print(type(y))
6 print(type(z))

<class 'str'>
<class 'int'>
<class 'float'>

Single or Double Quotes?


String variables can be declared either by using single or double quotes:

Example
In [8]: 1 a = "John"
2 # is the same as
3 b = 'John'
4 print(a)
5 print(b)

John
John

Case-Sensitive
Variable names are case-sensitive.

Example : This will create two variables:

In [9]: 1 a = 4
2 A = "Sally"
3 #A will not overwrite a
4 print(a)
5 print(A)

4
Sally

Python Variables - variable names


A variable can have a short name (like x and y) or a more descriptive name (age,
carname, total_volume). Rules for Python variables:
A variable name must start with a letter or the underscore character
A variable name cannot start with a number
A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9,
and _ )
Variable names are case-sensitive (age, Age and AGE are three different variables)
A variable name cannot be any of the Python keywords.

Examples(Legal and ilegal names):

In [20]: 1 # Legal names


2 Varaible = 23
3 VARAIBLE= "Python"
4 _vRIAble= 45.7
5 variabLE234 = 48
6 Variable_name = 67
In [1]: 1 #Illegal name
2 2Variable = 56

Input In [1]
2Variable = 56
^
SyntaxError: invalid syntax

In [3]: 1 Variable@ = 45

Input In [3]
Variable@ = 45
^
SyntaxError: invalid syntax

In [2]: 1 variable name =87

Input In [2]
variable name =87
^
SyntaxError: invalid syntax

In [12]: 1 def1 = 10
2 def = 10

Input In [12]
def = 10
^
SyntaxError: invalid syntax

In [10]: 1 class = 10

Input In [10]
class = 10
^
SyntaxError: invalid syntax
Multi Words Variable Names
Variable names with more than one word can be difficult to read.
There are several techniques you can use to make them more readable:

Camel Case
Each word, except the first, starts with a capital letter:

In [28]: 1 myVariableName = "John"

Snake Case
Each word is separated by an underscore character:

In [29]: 1 my_variable_name = "John"

Pascal Case
Each word starts with a capital letter:

In [30]: 1 MyVariableName = "John"

Python Variables - assign multiple values

Many Values to Multiple Variables


Python allows you to assign values to multiple variables in one line:

In [31]: 1 a,b,c = 10,20,30


2 print(a,b,c)

10 20 30

Note: Make sure the number of variables matches the number of values, or else you will get
an error.
In [32]: 1 a,b = 10,20,30
2 print(a,b,c)

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [32], in <cell line: 1>()
----> 1 a,b = 10,20,30
2 print(a,b,c)

ValueError: too many values to unpack (expected 2)

One Value to Multiple Variables


And you can assign the same value to multiple variables in one line:

In [34]: 1 a = b = c = 34
2 print(a,b,c)

34 34 34

Unpack a Collection
If you have a collection of values in a list, tuple etc. Python allows you to extract the values into
variables. This is called unpacking.

In [35]: 1 lst = [1,2,3]


2 x,y,z = lst
3 print(x,y,z)

1 2 3

In [36]: 1 lst = [1,2,3]


2 x,y = lst
3 print(x,y)

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [36], in <cell line: 2>()
1 lst = [1,2,3]
----> 2 x,y = lst
3 print(x,y)

ValueError: too many values to unpack (expected 2)


In [37]: 1 lst = [1,2,3]
2 x,y,z,xy = lst
3 print(x,y)

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [37], in <cell line: 2>()
1 lst = [1,2,3]
----> 2 x,y,z,xy = lst
3 print(x,y)

ValueError: not enough values to unpack (expected 4, got 3)

Python Variables - Output Variables

Output Variables
The Python print() function is often used to output variables.

In [38]: 1 print("Python is easy")

Python is easy

In the print() function, we can output multiple variables, separated by a comma:

In [39]: 1 a = "Python"
2 b = "is"
3 c = "easy"
4 print(a, b, c)

Python is easy

You can also use the + operator to output multiple variables:

In [40]: 1 a = "Python "


2 b = "is "
3 c = "easy"
4 print(a+b+c)

Python is easy

Notice the space character after "Python " and "is ", without them the result would be
"Pythonisawesome".

For numbers, the + character works as a mathematical operator:


In [41]: 1 a = 10
2 b = 20
3 print(a+b)

30

In the print() function, when you try to combine a string and a number with the + operator,
Python will give you an error:

In [42]: 1 a = 40
2 b = "Python"
3 print(a+b)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [42], in <cell line: 3>()
1 a = 40
2 b = "Python"
----> 3 print(a+b)

TypeError: unsupported operand type(s) for +: 'int' and 'str'

The best way to output multiple variables in the print() function is to separate them with
commas, which even support different data types:

In [43]: 1 a = 20
2 b = 30.07
3 c = 34+8j
4 d = "Python"
5 print(a,b,c,d)

20 30.07 (34+8j) Python

Python Variables - Global Variables

Global Variables
Variables that are created outside of a function (as in all of the examples above) are known as
global variables.

Global variables can be used by everyone, both inside of functions and outside.
In [64]: 1 a = 10
2 def Sample():
3 print(a+20)
4 Sample()

30

If you create a variable with the same name inside a function, this variable will be local, and
can only be used inside the function. The global variable with the same name will remain as it
was, global and with the original value.

In [3]: 1 a = 10
2 def Sample():
3 a = "Python is king"
4 print(a)
5 Sample()
6 print(a)

Python is king
10

Let's see this way. in local variable if we try to access global variable before creat it.

In [5]: 1 a = 10
2 def Sample():
3 print(a)
4 a = "Python is king"
5 print(a)
6 print(a)
7 Sample()

10

---------------------------------------------------------------------------
UnboundLocalError Traceback (most recent call last)
Input In [5], in <cell line: 7>()
5 print(a)
6 print(a)
----> 7 Sample()

Input In [5], in Sample()


2 def Sample():
----> 3 print(a)
4 a = "Python is king"
5 print(a)

UnboundLocalError: local variable 'a' referenced before assignment


The global Keyword
Normally, when you create a variable inside a function, that variable is local, and can only
be used inside that function.
To create a global variable inside a function, you can use the global keyword.

In [69]: 1 #With out global key word


2 def Sample():
3 Var = "This is local keyword"
4 Sample()
5 print(Var)

---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [69], in <cell line: 5>()
3 Var = "This is local keyword"
4 Sample()
----> 5 print(Var)

NameError: name 'Var' is not defined

In [70]: 1 #With global key word


2 def Sample():
3 global Var
4 Var = "This is local keyword"
5 Sample()
6 print(Var)

This is local keyword

Also, use the global keyword if you want to change a global variable inside a function.

To change the value of a global variable inside a function, refer to the variable by using the
global keyword:

In [74]: 1 var1 = "Sample"


2 ​
3 def Fun():
4 global var1
5 var1 = "This is was changed inside a \"Fun\" function"
6 Fun()
7 print(var1)

This is was changed inside a "Fun" function

Data Types in python


In programming, data type is an important concept.
Variables can store data of different types, and different types can do different things.
Python has the following data types built-in by default, in these categories:

Text Type : str


Numeric Types : int, float, complex
Sequence Types : list, tuple, range
Mapping Type : dict
Set Types : set, frozenset
Boolean Type : bool
Binary Types : bytes, bytearray, memoryview
None Type : NoneType

Getting the Data Type


You can get the data type of any object by using the type() function:

In [76]: 1 x = 5222
2 print(type(x))

<class 'int'>

Setting the Data Type


In Python, the data type is set when you assign a value to a variable:
In [84]: 1 i = 34
2 de = 34.34
3 c = 34.34j
4 s = "Sample"
5 l = [1,2,"sample"]
6 t = (1,2,"Python")
7 se = {1,2,3,3,4,4}
8 fse = frozenset(t)
9 d = {"name":"Python","age":23}
10 ​
11 #Printing values with type
12 print("i is",i,"with type of ",type(i))
13 print("d is",de,"with type of ",type(de))
14 print("s is",s,"with type of ",type(s))
15 print("l is",l,"with type of ",type(l))
16 print("t is",t,"with type of ",type(t))
17 print("se is",se,"with type of ",type(se))
18 print("fse is",fse,"with type of ",type(fse))
19 print("d is",d,"with type of ",type(d))

i is 34 with type of <class 'int'>


d is 34.34 with type of <class 'float'>
s is Sample with type of <class 'str'>
l is [1, 2, 'sample'] with type of <class 'list'>
t is (1, 2, 'Python') with type of <class 'tuple'>
se is {1, 2, 3, 4} with type of <class 'set'>
fse is frozenset({1, 2, 'Python'}) with type of <class 'frozenset'>
d is {'name': 'Python', 'age': 23} with type of <class 'dict'>

Setting the Specific Data Type


If you want to specify the data type, you can use the following constructor functions:

In [87]: 1 x = str("Hello World") #str


2 x = int(20)#int
3 x = float(20.5)#float
4 x = complex(1j)#complex
5 x = list(("apple", "banana", "cherry"))#list
6 x = tuple(("apple", "banana", "cherry"))#tuple
7 x = range(6)#range
8 x = dict(name="John", age=36)#dict
9 x = set(("apple", "banana", "cherry"))#set
10 x = frozenset(("apple", "banana", "cherry"))#frozenset

1.6 Type Conversion or Type casting..?


There may be times when you want to specify a type on to a variable. This can be done with
casting. Python is an object-orientated language, and as such it uses classes to define data
types, including its primitive types.

Casting in python is therefore done using constructor functions:


int() - constructs an integer number from an integer literal, a float literal (by removing all
decimals), or a string literal (providing the string represents a whole number)
float() - constructs a float number from an integer literal, a float literal or a string literal
(providing the string represents a float or an integer)
str() - constructs a string from a wide variety of data types, including strings, integer literals
and float literals

Below are inbuild functions of python:


01. int()
02. bool()
03. float(x)
04. str(x)
05. list(s)
06. tuple(s)
07. set(s)
08. dict(d)
09. ord(x)
10. chr(x)
11. complex(real,img)
12. eval()

01. INT ==> It converts given value into number.

In [50]: 1 x = int(1) # x will be 1


2 y = int(2.8) # y will be 2
3 z = int("3") # z will be 3
4 print(x)
5 print(type(x))
6 print(y)
7 print(type(y))
8 print(z)
9 print(type(z))

1
<class 'int'>
2
<class 'int'>
3
<class 'int'>

02. bool() ==> It converts the value into a boolean


The following values are considered false in Python:
None
False
Zero of any numeric type. For example, 0, 0.0, 0j
Empty sequence. For example, (), [], ''.
Empty mapping. For example, {}
In [51]: 1 print(bool(None))
2 print(bool(False))
3 print(bool(0))
4 print(bool(0.0))
5 print(bool(0j))
6 print(bool(()))
7 print(bool([]))
8 print(bool(""))
9 print(bool({}))

False
False
False
False
False
False
False
False
False

In [52]: 1 print(bool(1))
2 print(bool("Python"))
3 print(bool(2.8))
4 print(bool([1,2,4]))
5 print(bool(23+56j))

True
True
True
True
True

03. Floot ==>To convert value to a floating-point number


We can convert any value to float type except complex type.
In [48]: 1 x = float(1) # x will be 1.0
2 y = float(2.8) # y will be 2.8
3 z = float("3") # z will be 3.0
4 w = float("4.2") # w will be 4.2
5 ​
6 print(x)
7 print(type(x))
8 print(y)
9 print(type(y))
10 print(z)
11 print(type(z))

1.0
<class 'float'>
2.8
<class 'float'>
3.0
<class 'float'>

In [56]: 1 print(float(complex(34,45j)))

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [56], in <cell line: 1>()
----> 1 print(float(complex(34,45j)))

TypeError: can't convert complex to float

In [57]: 1 print(float([1,2,4]))

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [57], in <cell line: 1>()
----> 1 print(float([1,2,4]))

TypeError: float() argument must be a string or a number, not 'list'


04. str ==> It is Used to convert integer into a string

In [58]: 1 x = str("s1") # x will be 's1'


2 y = str(2) # y will be '2'
3 z = str(3.0) # z will be '3.0'
4 ​
5 print(x)
6 print(type(x))
7 print(y)
8 print(type(y))
9 print(z)
10 print(type(z))

s1
<class 'str'>
2
<class 'str'>
3.0
<class 'str'>

In [62]: 1 print(str([1,2,4]))
2 print(type(str([1,2,4])))

[1, 2, 4]
<class 'str'>

In [64]: 1 print(str((1,2,4,5)))
2 print(type(str((1,2,4,5))))

(1, 2, 4, 5)
<class 'str'>

05. list() ==> It is used to convert any data type to a list type.

In [65]: 1 print(list(34))

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [65], in <cell line: 1>()
----> 1 print(list(34))

TypeError: 'int' object is not iterable


In [66]: 1 print(list(34.7))

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [66], in <cell line: 1>()
----> 1 print(list(34.7))

TypeError: 'float' object is not iterable

In [74]: 1 print(list(True))

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [74], in <cell line: 1>()
----> 1 print(list(True))

TypeError: 'bool' object is not iterable

In [90]: 1 print(list("3445"))
2 print(list("Python"))
3 print(list((1,2,4,5)))
4 print(list({1:2,3:4}))
5 print(list({1,2,2,3,3,4,5}))

['3', '4', '4', '5']


['P', 'y', 't', 'h', 'o', 'n']
[1, 2, 4, 5]
[1, 3]
[1, 2, 3, 4, 5]

06. tuple() ==> It is used to convert to a tuple.


Same as list we need iterables only

In [89]: 1 print(tuple("3445"))
2 print(tuple("Python"))
3 print(tuple([1,2,4,5]))
4 print(tuple({1:2,3:4}))
5 print(tuple({1,2,2,3,3,4,5}))

('3', '4', '4', '5')


('P', 'y', 't', 'h', 'o', 'n')
(1, 2, 4, 5)
(1, 3)
(1, 2, 3, 4, 5)
07. set() ==> It returns the type after converting to set
Same as list we need iterables only

print(list(34)) print(list(34.7)) print(list(True)) print(list("3445")) print(list("Python"))


print(list((1,2,4,5))) print(list({1:2,3:4})) print(list({1,2,2,3,3,4,5}))

In [92]: 1 print(set("3445"))
2 print(set("Python"))
3 print(set([1,2,4,5]))
4 print(set({1:2,3:4}))
5 print(set((1,2,2,3,3,4,5)))

{'5', '4', '3'}


{'t', 'h', 'o', 'n', 'y', 'P'}
{1, 2, 4, 5}
{1, 3}
{1, 2, 3, 4, 5}

08. dict() ==> It is used to convert a tuple of order (key,value) into a


dictionary.

In [96]: 1 #list of list


2 print(dict([[1,2],[2,3],[3,4]]))

{1: 2, 2: 3, 3: 4}

In [102]: 1 #tuple of lists


2 print(dict(([1,2],[2,3],[3,4])))

{1: 2, 2: 3, 3: 4}

In [99]: 1 #list of list with more then 2 elements


2 print(dict([[1,2,5],[2,3],[3,4]]))

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [99], in <cell line: 2>()
1 #list of list with more then 2 elements
----> 2 print(dict([[1,2,5],[2,3],[3,4]]))

ValueError: dictionary update sequence element #0 has length 3; 2 is require


d
In [100]: 1 # tuple of tuples
2 print(dict(((1,2),(2,3),(3,4))))

{1: 2, 2: 3, 3: 4}

In [101]: 1 # List of tuples


2 print(dict([(1,2),(2,3),(3,4)]))

{1: 2, 2: 3, 3: 4}

In [103]: 1 # set of sets


2 print(dict({{1,2},{1,3},{3,4}}))

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [103], in <cell line: 2>()
1 # set of sets
----> 2 print(dict({{1,2},{1,3},{3,4}}))

TypeError: unhashable type: 'set'

09. ord() ==> It is used to convert a character to integer.

In [106]: 1 print(ord("a"))
2 print(ord("A"))

97
65

10. Chr ==> it conevrt number into ascii charcter

In [109]: 1 print(chr(97))
2 print(chr(65))

a
A
11.complex ==> This function converts real numbers to complex
number

In [111]: 1 a=1
2 print(type(a))
3 print(a)
4 b=complex(a)
5 print(type(b))
6 print(b)

<class 'int'>
1
<class 'complex'>
(1+0j)

In [113]: 1 a=complex(1,2)
2 b=complex(2,3)
3 c=a+b;print(c)
4 d=a-b;print(d)

(3+5j)
(-1-1j)

In [119]: 1 print(complex(20))
2 print(complex(10.5))
3 print(complex(True))
4 print(complex(False))
5 print(complex("10"))
6 print(complex("10.5"))
7 print(complex(1,-2))
8 print(complex(1,-0))

(20+0j)
(10.5+0j)
(1+0j)
0j
(10+0j)
(10.5+0j)
(1-2j)
(1+0j)

In [121]: 1 print(complex(True,True))
2 print(complex(True,False))
3 print(complex(False,False))
4 print(complex(False,True))

(1+1j)
(1+0j)
0j
1j
1.7 All about 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.

Types of Operators in Python

1. Arithmetic Operators
2. Comparison Operators
3. Logical Operators
4. Assignment Operators
5. Identity Operators
6. Membership Operators
7. Ternary Operator
8. Bitwise Operators

Arithmetic Operators in Python


Python Arithmetic operators are used to perform basic mathematical operations like
addition, subtraction, multiplication, and division.
In Python 3.x the result of division is a floating-point while in Python 2.x division of 2
integers was an integer. To obtain an integer result in Python 3.x floored (// integer) is
used.

Operator Description Syntax

+ Addition: adds two operands x+y

– Subtraction: subtracts two operands x–y

* Multiplication: multiplies two operands x*y

/ Division (float): divides the first operand by the second x/y

// Division (floor): divides the first operand by the second x // y

% Modulus: returns the remainder when the first operand is divided by the second x%y

** Power: Returns first raised to power second x ** y


In [31]: 1 x=10
2 y=2
3 ​
4 print("Addition of {} and {} is {}".format(x,y,x+y))
5 print("Subtraction of {} and {} is {}".format(x,y,x-y))
6 print("Multiplication of {} and {} is {}".format(x,y,x*y))
7 print("float Division of {} and {} is {}".format(x,y,x/y))
8 print("floor Division of {} and {} is {}".format(x,y,x//y))
9 print("Modulus of {} and {} is {}".format(x,y,x%y))
10 print("Power of {} and {} is {}".format(x,y,x**y))

Addition of 10 and 2 is 12
Subtraction of 10 and 2 is 8
Multiplication of 10 and 2 is 20
float Division of 10 and 2 is 5.0
floor Division of 10 and 2 is 5
Modulus of 10 and 2 is 0
Power of 10 and 2 is 100

Division Operators
Division Operators allow you to divide two numbers and return a quotient, i.e., the first number
or number at the left is divided by the second number or number at the right and returns the
quotient.

There are two types of division operators:

1. Float division
2. Floor division

Float division

The quotient returned by this operator is always a float number, no matter if two numbers are
integers. For example:

In [32]: 1 print(5/5) #0.0


2 print(10/2) #5.0
3 print(-10/2) #-5.0
4 print(20.0/2)#10.0

1.0
5.0
-5.0
10.0

Integer division( Floor division)

The quotient returned by this operator is dependent on the argument being passed. If any of
the numbers is float, it returns output in float. It is also known as Floor division because, if any
number is negative, then the output will be floored. For example:
In [37]: 1 print(10//3) #3
2 print (-3//2) #-2
3 print (5.0//2) #2
4 print (-5.0//2) #-2
5 print(7//3) #3
6 print(7/3) #3

3
-2
2.0
-3.0
2
2.3333333333333335

Precedence of Arithmetic Operators in Python

The precedence of Arithmetic Operators in python is as follows:(PEMDAS)

P – Parentheses
E – Exponentiation
M – Multiplication (Multiplication and division have the same precedence)
D – Division
A – Addition (Addition and subtraction have the same precedence)
S – Subtraction

The modulus operator helps us extract the last digit/s of a number.

For example:
x % 10 -> yields the last digit
x % 100 -> yield last two digits

In [41]: 1 #To get last 1 didigt for any numer


2 print(234%10)
3 print(234%100)
4 print(234%1000)

4
34
234

Comparison or Relational Operators in Python


In Python Comparison of Relational operators compares the values. It either returns True or
False according to the condition.

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


Operator Description Syntax

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

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

<= Less than or equal to : True if the left operand is less than or equal to the right x <= y

= is an assignment operator and == comparison operator.

Precedence of Comparison Operators in Python

In python, the comparison operators have lower precedence than the arithmetic operators. All

In [42]: 1 # Examples of Relational Operators


2 a = 13
3 b = 33
4
5 # a > b is False
6 print(a > b)
7
8 # a < b is True
9 print(a < b)
10
11 # a == b is False
12 print(a == b)
13
14 # a != b is True
15 print(a != b)
16
17 # a >= b is False
18 print(a >= b)
19
20 # a <= b is True
21 print(a <= b)

False
True
False
True
False
True

Logical Operators in Python


Python Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is
used to combine conditional statements.

Operator Description Syntax

and Logical AND: True if both the operands are true x and y

or Logical OR: True if either of the operands is true x or y

not Logical NOT: True if the operand is false not x


Precedence of Logical Operators in Python

The precedence of Logical Operators in python is as follows:

1. Logical not
2. logical and
3. logical or

Example of Logical Operators in Python

The following code shows how to implement Logical Operators in Python:

In [44]: 1 # Examples of Logical Operator


2 a = True
3 b = False
4
5 # Print a and b is False
6 print(a and b)
7
8 # Print a or b is True
9 print(a or b)
10
11 # Print not a is False
12 print(not a)

False
True
False

Assignment Operators in Python


Python Assignment operators are used to assign values to the variables.

Operator Description Syntax

Assign the value of the right side of the expression to the


= x=y+z
left side operand

Add AND: Add right-side operand with left-side operand


+= a+=b a=a+b
and then assign to left operand

Subtract AND: Subtract right operand from left operand


-= a-=b a=a-b
and then assign to left operand

Multiply AND: Multiply right operand with left operand


*= a=b a=ab
and then assign to left operand

Divide AND: Divide left operand with right operand and


/= a/=b a=a/b
then assign to left operand

Modulus AND: Takes modulus using left and right


%= a%=b a=a%b
operands and assign the result to left operand

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


//= a//=b a=a//b
and then assign the value(floor) to left operand
Operator Description Syntax

Exponent AND: Calculate exponent(raise power) value


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

Performs Bitwise AND on operands and assign value to


&= a&=b a=a&b
left operand

Performs Bitwise OR on operands


=
and assign value to left operand

Performs Bitwise xOR on operands and assign value to


^= a^=b a=a^b
left operand

Performs Bitwise right shift on operands and assign value


>>= a>>=b a=a>>b

Membership Operators in Python


In Python, in and not in are the membership operators that are used to test whether a value or
variable is in a sequence.

in ======> True if value is found in the sequence


not in ==> True if value is not found in the sequence

Examples of Membership Operators in Python

The following code shows how to implement Membership Operators in Python:

In [57]: 1 print(10 in [10,20,30])


2 print(10 not in [10,20,30])

True
False

In [59]: 1 x = 24
2 y = 20
3 list = [10, 20, 30, 40, 50]
4
5 if (x not in list):
6 print("x is NOT present in given list")
7 else:
8 print("x is present in given list")
9 if (y in list):
10 print("y is present in given list")
11 else:
12 print("y is NOT present in given list")

x is NOT present in given list


y is present in given list
Identity Operators in Python
In Python, is and is not are the identity operators both are used to check if two values are
located on the same part of the memory. Two variables that are equal do not imply that they
are identical.

is ======>True if the operands are identical


is not ==> True if the operands are not identical

Example Identity Operators in Python

Let’s see an example of Identity Operators in Python.

In [65]: 1 x = 10
2 y = 10
3 z = x
4 print(x is y)
5 print(x is z)
6 print(x is not y)
7 print(id(x))
8 print(id(y))
9 print(id(z))

True
True
False
2770717928016
2770717928016
2770717928016

Difference between "is" vs "=="


The is operator may seem like the same as the equality operator but they are not same.
The is operator checks if both the variables point to the same object whereas the ==
operator sign checks if the values for the two variables are the same.
In [3]: 1 a=[1,2,3]
2 b=a
3 print(b)
4 print(a is b)
5 print(a == b)
6 c=list(a)
7 print(c)
8 print(a is c)
9 print(a == c)

[1, 2, 3]
True
True
[1, 2, 3]
False
True

Ternary Operator in Python


in Python, Ternary operators also known as conditional expressions are operators that
evaluate something based on a condition being true or false. It was added to Python in version
2.5.

It simply allows testing a condition in a single line replacing the multiline if-else making the
code compact.

Syntax : [on_true] if [expression] else [on_false]

Examples of Ternary Operator in Python Here is a simple example of Ternary Operator in


Python.

In [63]: 1 x = 10
2 y = 20
3 min1 = x if x<y else y
4 print(min1)

10

Bitwise Operators in Python


Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to
operate on binary numbers.

Operator Description Syntax

& Bitwise AND x&y

| Bitwise OR x|y

~ Bitwise NOT ~x

^ Bitwise XOR x^y


Operator Description Syntax

>> Bitwise right shift x>>

<< Bitwise left shift x<<

Precedence of Bitwise Operators in Python

The precedence of Bitwise Operators in python is as follows:

1. Bitwise NOT
2. Bitwise Shift
3. Bitwise AND
4. Bitwise XOR
5. Bitwise OR

Bitwise Operators in Python


In [64]: 1 # Examples of Bitwise operators
2 a = 10
3 b = 4
4
5 # Print bitwise AND operation
6 print(a & b)
7
8 # Print bitwise OR operation
9 print(a | b)
10
11 # Print bitwise NOT operation
12 print(~a)
13
14 # print bitwise XOR operation
15 print(a ^ b)
16
17 # print bitwise right shift operation
18 print(a >> 2)
19
20 # print bitwise left shift operation
21 print(a << 2)

0
14
-11
14
2
40

Bit Wise opearations explanation:

Bitwise AND (&)


It compares each bit of the first operand to the corresponding bit of the second operand.
If both bits are 1, the corresponding result bit is set to 1.
x y x&y

0 0 0

0 1 0

1 0 0

1 1 1

Example:

a=10;b=20

ANALYSIS

We declared 2 integers a and b, The binary form of


10 = 00001010 ==> for 1 Byte ==> 8 bits
20 = 00010100 ==> for 1 Byte ==> 8 bits
00001010 & 00010100 ==> 00000000=> Result is 0

In [23]: 1 a=10;b=20
2 print(bin(a))
3 print(bin(b))

0b1010
0b10100

In [24]: 1 print(a&b)

bitwise OR ( | )
It takes two bit patterns of equal length.
The result in each position is 0 if both bits are 0,
while otherwise the result is 1 (Any One 1 the Result is 1)

x y x|y

0 0 0

0 1 1

1 0 1

1 1 1

Example :

a = 9;b = 65

ANALYSIS
We declared 2 integers a and b, The binary form of
09 = 00001001 ==> for 1 Byte ==> 8 bits
65 = 01000001 ==> for 1 Byte ==> 8 bits
00001001 & 01000001 01001001 R l i 3
In [25]: 1 a = 9
2 b = 65
3 print(bin(a))
4 print(bin(b))
5 print(0b01001001)

0b1001
0b1000001
73

In [22]: 1 print(a|b)

73

bitwise exclusive OR operator (^)


It compares each bit of its first operand to the corresponding bit of its second operand.
If one bit is 0 and the other bit is 1, the corresponding result bit is set to 1. Otherwise,
the corresponding result bit is set to 0. (Identical is 0)

x y x^y

0 0 0

0 1 1

1 0 1

1 1 0

Example:

a = 9;b = 65

ANALYSIS

We declared 2 integers a and b, The binary form of


09 = 00001001 ==> for 1 Byte ==> 8 bits
65 = 01000001 ==> for 1 Byte ==> 8 bits
00001001 & 01000001 ==> 01001000=> Result is 72

In [29]: 1 print(bin(9))
2 print(bin(65))
3 print(0b01001000)

0b1001
0b1000001
72
Bitwise complement ( ~ ) :

Binary Ones Complement

It is unary and has the effect of 'flipping' bits.


Given number should be convert into binary number.
That binary number converting '0' to '1' and '1' to '0' is called Binary Ones
Complement.
In Mathematical Approach:
x=10 ==> 0000 1010 (is Binary Number)
Binary Ones Complement is ==> 1111 0101

Binary Twos Complement:

• Add '1' to Binary Ones Complement is called Binary Twos Complement.


1111 0101
+++++++1
-------------
1111 0110
------------

NOTE: Binary Addition computations are the following:

1+1=10, 1+0=1, 0+1=1,0+0=0, 1+1+1=11

Binary Left Shift:- ( << )


The left operands value is moved left by the number of bits specified by the right operand.

a = 10 # 10=1010
a << 2; # 40=101000==>Add Two digits right side

Binary Right Shift :-( >> )


The left operands value is moved right by the number of bits specified by the right operand.

a = 10 #10=1010
a >> 2; #2=10==>Remove two digits right side

1.8 Comparison operator Chaining...?


Checking more than two conditions is very common in Programming Languages. Let’s say we
want to check the below condition:

a<b<c

The most common syntax to do it is as follows:


if a < b and b < c :
{...}

In Python, there is a better way to write this using the Comparison operator Chaining. The
chaining of operators can be written as follows:

if a < b < c :
{.....}

According to associativity and precedence in Python, all comparison operations in Python have
the same priority, which is lower than that of any arithmetic, shifting, or bitwise operation. Also
unlike C, expressions like a < b < c have an interpretation that is conventional in mathematics.
List of comparison operators in Python:

In [10]: 1 a = 200
2 b = 300
3 c = 40
4 ​
5 if a>b and a>c:
6 print(a)
7 elif b>a and b>c:
8 print(b)
9 elif c>a and c>b:
10 print(c)

300

In [11]: 1 if b<a>c:
2 print(a)
3 elif a<b>c:
4 print(b)
5 elif a<c>b:
6 print(c)
7 else:
8 print("Nothing to do")

300

String Formatting in Python:


In Python a string of required formatting can be achieved by different methods.

1) Using %
2) Using {}
Using %:
The formatting using % is similar to that of ‘printf’ in C programming language.
%d ==> integer
%f ==> float
%s ==> string
%x ==> hexadecimal
%o ==> octal

Syntax:

In [123]: 1 print("My name is %s and my age is %d"%("Python",23))

My Python is and my age is 23

Using {}:
We can format strings with variable values by using replacement operator {} and format()
method.

Syntax:
{} .format(value)

In [7]: 1 print("My name is {} and my age is {}".format("Python",23))


2 print("My name is {1} and my age is {0}".format(23,"Python"))
3 print("My name is {pl} and my age is {age}".format(age=23,pl="Python"))

My name is Python and my age is 23


My name is Python and my age is 23
My name is Python and my age is 23
2. Conditional & Control
Flow Statements(Control
Structures)
1. Decision making or Conditional statements (if, else, and elif)
2. loops or control statements (for & while)
3. User Input

PYTHON Control Structures:


In PYTHON Programming Control Structures are classified into:

1. Sequential Control Structures


2. Selection Control Structures
3. Iterative Control Structures

Control_Flow Pic:

1. Sequential Control Structures:


It gets executes the lines of code in sequential order.
In [1]: 1 print("Line1")
2 print("Line2")
3 print("Line3")

Line1
Line2
Line3

In [2]: 1 print("Line1");print("Line2");print("Line3")

Line1
Line2
Line3

2. Selection Control Structures: (Conditional Control


Statements):
It is popularly known as Python Decision Making statments.
Python programming language provides following types of decision making statements.

1. if statement ====================>One-Way Decisions


2. if .. else statement ============>Two-Way Decisions
3. if .. elif .. else statement ====>Multi-Way Decisions
4. Nested if .. else ===============>inner Decisions
5. Negative Conditions =============>Using Member-ship operators

Python 'if' Statement:-

It executes a set of statements conditionally, based on the value of a logical expression.

In [1]: 1 n = 101
2 if n>100:
3 print("This is more then 100")
4 print("THis always executes")

This is more then 100


THis always executes

In [2]: 1 n = 10
2 if n>100:
3 print("This is more then 100")
4 print("THis always executes")

THis always executes

if .. else Statement:-
An else statement can be combined with an if statement. An else statement contains the block

In [6]: 1 n = 101
2 if n>100:
3 print("This is more then 100")
4 else:
5 print("This is less then 100")
6 print("THis always executes")

This is more then 100


THis always executes

In [7]: 1 n = 10
2 if n>100:
3 print("This is more then 100")
4 else:
5 print("This is less then 100")
6 print("THis always executes")

This is less then 100


THis always executes

Python if...elif...else:-

The elif statement allows you to check multiple expressions for TRUE and execute a block of
code as soon as one of the conditions evaluates to TRUE.

In [21]: 1 n = 0
2 if n>100:
3 print("This is more then 100")
4 elif n<0:
5 print("This is negative number")
6 elif n>1000:
7 print("This is more then 1000")
8 else:
9 print("Value is zero")

Value is zero

Nested if .. else statement;-

In general nested if-else statement is used when we want to check more than one conditions.
Conditions are executed from top to bottom and check each condition whether it evaluates to
true or not.
In [23]: 1 num = int(input("Enter a number: "))
2 if num >= 0:
3 if (num == 0):
4 print("ZERO")
5 else:
6 print("Positive number")
7 else:
8 print("Negative number")

Enter a number: 0
ZERO

In [9]: 1 # Election age calculating


2 age = 20
3 identity_card = "Yes"
4 if age>18:
5 if identity_card == 'Yes':
6 print("He can vote")
7 else:
8 print("he can't vote as he dont have identity_card")
9 else:
10 print("He can't vote as his age is less then 18...")

He can vote

In [10]: 1 # Election age calculating


2 age = 17
3 identity_card = "Yes"
4 if age>18:
5 if identity_card == 'Yes':
6 print("He can vote")
7 else:
8 print("he can't vote as he dont have identity_card")
9 else:
10 print("He can't vote as his age is less then 18...")

He can't vote as his age is less then 18...

In [11]: 1 # Election age calculating


2 age = 23
3 identity_card = "No"
4 if age>18:
5 if identity_card == 'Yes':
6 print("He can vote")
7 else:
8 print("he can't vote as he dont have identity_card")
9 else:
10 print("He can't vote as his age is less then 18...")

he can't vote as he dont have identity_card

Negative Conditions in PYTHON:


If a condition is true the not operator is used to reverse the logical state, then logical not
operator will make it false.

In [24]: 1 x = int(input("Enter Any Number: "))


2 print(x)
3 if not x == 50:
4 print('the value of x different from 50')
5 else:
6 print('the value of x is equal to 50')

Enter Any Number: 50


50
the value of x is equal to 50

3. Iterative Control Structures (Python Loops):

What is a Loop?
A loop is a sequence of instructions that is continually repeated until a certain condition is
reached.

Why Loop?
In a loop structure, the loop asks a question. If the answer requires an action, it is executed.
The same question is asked again and again until no further action is required. Each time the
question is asked is called an iteration.

TYPES OF LOOPS in PYTHON:


1. for .
2. while.
3. nested loops.
4. break and continue (Loop Control Statements)

For loop in python:


It is used to iterate over the items of any sequence including the Python list, string, tuple etc.

In [27]: 1 for char in "PYTHON":


2 print("The Character is: ",char)

The Character is: P


The Character is: Y
The Character is: T
The Character is: H
The Character is: O
The Character is: N
How for loop work :

In [31]: 1 s = "PYTHON"
2 s_iter = iter(s)
3 print(next(s_iter))
4 print(next(s_iter))
5 print(next(s_iter))
6 print(next(s_iter))
7 print(next(s_iter))
8 print(next(s_iter))

P
Y
T
H
O
N

In [34]: 1 primes = [2, 3, 5, 7]


2 for prime in primes:
3 print(prime)

2
3
5
7

range() and xrange() functions in PYTHON:


range() – This returns a list of numbers created using range() function.
xrange() – This function returns the generator object that can be used to display numbers
only by looping.

xrange() renamed as range() in Python-3.0

Range Function
It generates lists containing arithmetic progression. It returns a list of consecutive integers. The
function has one, two or three parameters where last two parameters are optional. It is widely
used in for loops.

3 variations of range() function:

range(stop) - Starts from O till (stop - 1)


range(start,stop) - Ends at (stop - 1)
range(start,stop,step) - Step can not be 0, default is 1
In [17]: 1 rg = range(1,10)
2 print(rg)
3 print(list(rg))
4 print(type(rg))

range(1, 10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
<class 'range'>

In [38]: 1 for i in range(10):


2 print(i)

0
1
2
3
4
5
6
7
8
9

In [5]: 1 print(list(range(10)))
2 print(list(range(10,30)))
3 print(list(range(10,30,5)))

[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]
[10, 15, 20, 25]

for loop with else clause


A for loop can have an optional else block as well.
The else part is executed if the items in the sequence used in for loop exhausts.
break statement can be used to stop a for loop. In such case, the else part is ignored.

In [8]: 1 # for with else and no break


2 for i in range(5):
3 print(i)
4 else:
5 print("No items left in list")

0
1
2
3
4
No items left in list
In [9]: 1 # for with else with break
2 for i in range(5):
3 if i == 4:
4 break;
5 print(i)
6 else:
7 print("No items left in list")

0
1
2
3

NOTE:

if we stop the loop, say with a break statement, then the else suite will not be executed

break
To break out from a loop, you can use the keyword "break".

In [10]: 1 for x in "PYTHON":


2 if(x=='O'):
3 break
4 print(x)
5 else:
6 print("Loop Completed")

P
Y
T
H

In [11]: 1 for x in "PYTHON":


2 if(x=='R'):
3 break
4 print(x)
5 else:
6 print("Loop Completed")
7 ​

P
Y
T
H
O
N
Loop Completed
Continue
The continue statement is used to tell Python to skip the rest of the statements in the current
loop block and to continue to the next iteration of the loop.

In [19]: 1 for i in range(6):


2 if i==3:
3 continue
4 print(i)
5 else:
6 print("Else will execute eveytime in continue")

0
1
2
4
5
Else will execute eveytime in continue

In [17]: 1 for i in range(6):


2 print(i)
3 if i==3:
4 continue
5 else:
6 print("Else will execute eveytime in continue")

0
1
2
3
4
5
Else will execute eveytime in continue

while Loop Statements:


while Loop is used to execute number of statements or body till the condition passed in while is
true. Once the condition is false, the control will come out of the loop.

In [18]: 1 x = 0
2 while x<=5:
3 print(x)
4 x+=1

0
1
2
3
4
5
while and else statement
There is a structural similarity between while and else statement. Both have a block of
statement(s) which is only executed when the condition is true.

In [19]: 1 x=1
2 while x<=5:
3 print(x)
4 x=x+1
5 else:
6 print("loop Finished")
7 ​

1
2
3
4
5
loop Finished

In [20]: 1 a=10
2 while a>0:
3 print("Value of a is",a)
4 a=a-2
5 else:
6 print("Loop is Completed")
7 ​

Value of a is 10
Value of a is 8
Value of a is 6
Value of a is 4
Value of a is 2
Loop is Completed

In [2]: 1 x = 0
2 while x<6:
3 print(x)
4 x+=1
5 else:
6 print("While completed")

0
1
2
3
4
5
While completed
In [3]: 1 x = 0
2 while x<6:
3 if x == 3:
4 break;
5 print(x)
6 x+=1
7 else:
8 print("While completed")

0
1
2

In [ ]: 1 # This will have infinte loops as we have mentioned continue before incre
2 # when poniter reaches 3 it will keep executing continue there is no incr
3 x = 0
4 while x<6:
5 if x == 3:
6 continue;
7 print(x)
8 x+=1
9 else:
10 print("While completed")

0
1
2

In [1]: 1 x = 0
2 while x<6:
3 x+=1
4 if x == 3:
5 continue;
6 print(x)
7 else:
8 print("While completed")

1
2
4
5
6
While completed

Python nested loops


• Python programming language allows to use one loop inside another loop.

Syntax
for [first iterating variable] in [outer loop]: # Outer loop
[do something] # Optional
f [ d it ti i bl ] i [ t dl ] #N t dl
In [26]: 1 for i in range(5):
2 for j in range(5):
3 print(i+j,end=" ")
4 print()

0 1 2 3 4
1 2 3 4 5
2 3 4 5 6
3 4 5 6 7
4 5 6 7 8

Printing patterens in python:

In [27]: 1 pattern=int(input("Enter Number of Rows: "))


2 for i in range(1, pattern+1):
3 for j in range(1,i+1):
4 print("*",end=" ")
5 print()

Enter Number of Rows: 5


*
* *
* * *
* * * *
* * * * *

In [31]: 1 pattern=int(input("Enter Number of rows: "))


2 for i in range(pattern,0,-1):
3 for j in range(0,i):
4 print("*",end="")
5 print()

Enter Number of rows: 5


*****
****
***
**
*

In [32]: 1 pattern=int(input("Enter Number of rows: "))


2 for i in range(1,pattern+1):
3 for j in range(1,pattern+2-i):
4 print("*",end="")
5 print()

Enter Number of rows: 5


*****
****
***
**
*
In [30]: 1 pattern=int(input("Enter Number of rows: "))
2 for i in range(0,pattern):
3 for j in range(0,pattern-i-1):
4 print(end=" ")
5 for j in range(0,i+1):
6 print("*",end=" ")
7 print()

Enter Number of rows: 5


*
* *
* * *
* * * *
* * * * *

In [33]: 1 pattern=int(input("Enter Number of rows: "))


2 for i in range(pattern,0,-1):
3 for j in range(0,pattern-i):
4 print(end=" ")
5 for j in range(0,i):
6 print("*",end=" ")
7 print()

Enter Number of rows: 5


* * * * *
* * * *
* * *
* *
*

PASS KEYWORD
It is used when a statement is required syntactically but you do not want any command or code
to execute.
Why Pass?

It is an empty statement
It is null statement
It results into no operation (NOP)

In [35]: 1 for i in "PYTHON":


2

Input In [35]

^
IndentationError: expected an indented block
In [36]: 1 for i in "PYTHON":
2 pass

Note:
Above we can understand that when we use pass keyword there is no error.

User Input
Python allows for user input.
That means we are able to ask the user for input.
The method is a bit different in Python 3.6 than Python 2.7.
Python 3.6 uses the input() method.
Python 2.7 uses the raw_input() method.

In [1]: 1 name = input("Enter your name:")


2 print(name)

Enter your name:Rakesh


Rakesh

In [2]: 1 age = input("Enter your age: ")


2 print(type(age))

Enter your age: 30


<class 'str'>

In [19]: 1 ### Taking some charcter as in put


2 mobile = input("Enter your number : ")[0:10]
3 print(mobile,len(mobile))

Enter your number : 11111222223333344444


1111122222 10

Evaluating expression

In [20]: 1 res = input("Enter expression : ")


2 print(res)

Enter expression : 2 + 3 + 5
2 + 3 + 5
In [21]: 1 res = eval(input("Enter expression : "))
2 print(res)

Enter expression : 2 + 3 + 5
10

How to take input from cmd to python

Create a py file with below code:

Trying to running now

Changing code like below now:

Output:
3. String and Boolean
Manipulations
1. Python Strings and Inbuilt functions
2. Boolean Variables

Strings
Strings in python are surrounded by either single quotation marks, or double quotation marks.
'python' is the same as "python".
You can display a string literal with the print() function:

In [13]: 1 print("python")
2 print('python')

python
python

Some basic operations using python strings:

Concatenation:
when we use + operated between a strings then it act as concatenation and add both string.

In [1]: 1 var1 = "Python1"


2 var2 = "Python2"
3 print(var1+var2)
4 print(var1+" "+var2)

Python1Python2
Python1 Python2

String Repetition

In [2]: 1 print("Python "*5)

Python Python Python Python Python


Different Quotes in PYTHON:

In [3]: 1 PyStr="PYTHON"
2 print(PyStr,type(PyStr))
3 PyStr='PYTHON'
4 print(PyStr,type(PyStr))
5 PyStr="""PYTHON"""
6 print(PyStr,type(PyStr))
7 PyStr='''PYTHON'''
8 print(PyStr,type(PyStr))

PYTHON <class 'str'>


PYTHON <class 'str'>
PYTHON <class 'str'>
PYTHON <class 'str'>

Assign a string to a variable and Re-Assigning


To assign a value to Python variables, type the value after the equal sign(=).

In [6]: 1 #Example-1 (We can do reasing for total string)


2 MyStr="PYTHON"
3 print(MyStr)
4 MyStr="Machine Leaning"
5 print(MyStr)

PYTHON
Machine Leaning

In [4]: 1 #Example-2
2 MyStr="PYTHON"
3 print(MyStr)
4 print(MyStr[-1])
5 MyStr[-1]="R"
6 print(MyStr)

PYTHON
N

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [4], in <cell line: 5>()
3 print(MyStr)
4 print(MyStr[-1])
----> 5 MyStr[-1]="R"
6 print(MyStr)

TypeError: 'str' object does not support item assignment


Multiline Strings
You can assign a multiline string to a variable by using three quotes:

Example
You can use three double quotes:

In [4]: 1 a = """Lorem ipsum dolor sit amet,


2 consectetur adipiscing elit,
3 sed do eiusmod tempor incididunt
4 ut labore et dolore magna aliqua."""
5 print(a)

Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.

Example
Or three single quotes:

In [7]: 1 a = '''Lorem ipsum dolor sit amet,


2 consectetur adipiscing elit,
3 sed do eiusmod tempor incididunt
4 ​
5 ut labore et dolore magna aliqua.'''
6 print(a)

Lorem ipsum dolor sit amet,


consectetur adipiscing elit,
sed do eiusmod tempor incididunt

ut labore et dolore magna aliqua.

Note: in the result, the line breaks are inserted at the same position as in the code.

Looping Through a String


Since strings are arrays, we can loop through the characters in a string, with a for loop.
In [17]: 1 MyStr = "PYTHON"
2 for i in MyStr:
3 print(i)

P
Y
T
H
O
N

String Length
To get the length of a string, use the len() function.

In [19]: 1 MyStr = "PYTHON"


2 print(len(MyStr))

Check String
To check if a certain phrase or character is present in a string, we can use the in keyword.

In [21]: 1 txt ="Good morning master"


2 print("Good" in txt)
3 print("good" in txt)

True
False

Using in an if statement:

In [30]: 1 txt ="Good morning master"


2 if "Good" in txt:
3 print("\"Good\" is there")
4 else:
5 print("\"good\" is not there")

"Good" is there

Check if NOT
To check if a certain phrase or character is NOT present in a string, we can use the keyword
not in.
In [33]: 1 txt ="Good morning master"
2 if "good" not in txt:
3 print("good is not there ")
4 else:
5 print("\"good\" is there")

good is not there

Slicing:

What is String Slicing?


To cut a substring from a string is called string slicing. OR
You can return a range of characters by using the slice syntax.
Specify the start index and the end index, separated by a colon, to return a part of the
string.
Here two indices are used separated by a colon (:). A slice 3:7 means
indices characters of 3rd, 4th, 5th and 6th positions. The second
integer index i.e. 7 is not included. You can use negative indices for slicing.

String Indices or Indexing


Strings are arrays of characters and elements of an array can be accessed using indexing.
Indices start with 0 from right and left side -1

If our string in "PYTHON" then +ve and -ve indexes will assign like below:

P Y T H O N

0 1 2 3 4 5

-6 -5 -4 -3 -2 -1
In [14]: 1 #+ve slicing
2 a = "PYTHON"
3 print(a[0])
4 print(a[1])
5 print(a[2])
6 print(a[3])
7 print(a[4])
8 print(a[5])
9 print(a[6])

P
Y
T
H
O
N

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Input In [14], in <cell line: 9>()
7 print(a[4])
8 print(a[5])
----> 9 print(a[6])

IndexError: string index out of range

In [15]: 1 #-ve slicing


2 print(a[-1])
3 print(a[-2])
4 print(a[-3])
5 print(a[-4])
6 print(a[-5])
7 print(a[-6])
8 print(a[-7])

N
O
H
T
Y
P

---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Input In [15], in <cell line: 8>()
6 print(a[-5])
7 print(a[-6])
----> 8 print(a[-7])

IndexError: string index out of range


Note : When we give index more then index of string then it will give IndexError: string index
out of range.

Slice From the Start


By leaving out the start index, the range will start at the first character:

In [16]: 1 print(a[:4])

PYTH

Slice To the End


By leaving out the end index, the range will go to the end:

In [17]: 1 print(a[2:])

THON

Negative Indexing
Use negative indexes to start the slice from the end of the string:

In [19]: 1 print(a[-6:-2])

PYTH

Wrt a program to check either given string is a" Palindrome or not..?

In [215]: 1 s = "level"
2 if s == s[::-1]:
3 print("Yess ....")
4 else:
5 print("Noooooo...")

Yess ....

In [216]: 1 s = "Rakesh"
2 if s == s[::-1]:
3 print("Yess ....")
4 else:
5 print("Noooooo...")

Noooooo...
What is difference between ASCII and UNICODE string.?

ASCII (American Standard Code for Information Interchange) :

It is a character encoding standard or format that uses numbers from 0 to 127 to represent
English characters.
ASCII value of "A" is 65
ASCII value of "a"is 97

UNICODE:

This UNICODE is superset of ASCII...


which are numbers from 0 through 0x10FFFF (1,114,111 decimal).

chr() and ord() two methods which will provide Charcter based on ASCII value and ASCII value
based on character represntly.

In [22]: 1 print(ord("A"))
2 print(chr(65))

65
A

In [30]: 1 print(ord("అ"))

3077

In [35]: 1 amma = "అమ్మ "


In [45]: 1 print(amma[0])
2 print(amma[1])
3 print(amma[2])
4 print(amma[3])
5 print(amma[4])




---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
Input In [45], in <cell line: 5>()
3 print(amma[2])
4 print(amma[3])
----> 5 print(amma[4])

IndexError: string index out of range

String Format
As we learned in the Python Variables chapter, we cannot combine strings and numbers like
this:

In [47]: 1 age = 25
2 print(" My age is "+age)

---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Input In [47], in <cell line: 2>()
1 age = 25
----> 2 print(" My age is "+age)

TypeError: can only concatenate str (not "int") to str

But we can combine strings and numbers by using the format() method!

The format() method takes the passed arguments, formats them, and places them in the string
where the placeholders {} are:

In [52]: 1 name = "Rakesh"


2 age = 25
3 place = "Hyderbad"
4 print("Hello, My name is {} and my age is {} and i live in {}...!".format

Hello, My name is Rakesh and my age is 25 and i live in Hyderbad...!


You can use index numbers {0} to be sure the arguments are placed in the correct
placeholders:

In [54]: 1 name = "Rakesh"


2 age = 25
3 place = "Hyderbad"
4 print("Hello, My name is {2} and my age is {0} and i live in {1}...!".for

Hello, My name is Rakesh and my age is 25 and i live in Hyderbad...!

String Methods
Python has a set of built-in methods that you can use on strings.

Note : All string methods return new values. They do not change the original string until we
asign it to original variable.

All Methods:
S.NO Method Description

01 capitalize() Converts the first character to upper case

02 casefold() Converts string into lower case.

03 count() Returns the number of times a specified value occurs in a string.

04 startswith() Returns true if the string starts with the specified value

05 endswith() Returns true if the string ends with the specified value.

06 expandtabs() Sets the tab size of the string

Searches the string for a specified value and returns the position of where it was
07 find()
found

Searches the string for a specified value and returns the position of where it was
08 index()
found

Searches the string for a specified value and returns the last position of where it was
09 rfind()
found

Searches the string for a specified value and returns the last position of where it was
10 rindex()
found

11 join() This method takes all items in an iterable and joins them into one string.

12 format() Formats specified values in a string.

13 lower() Converts a string into lower case

14 upper() Converts a string into upper case

15 rjust() Returns a right justified version of the string.

16 ljust() Returns a left justified version of the string.

17 center() Returns a centered string.

18 lstrip() Returns a left trim version of the string.


S.NO Method Description

19 rstrip() Returns a right trim version of the string.

20 strip() Returns a trimmed version of the string.

21 replace() This method replaces a specified phrase with another specified phrase.

22 split() Splits the string at the specified separator, and returns a list

23 rsplit() Splits the string at the specified separator, and returns a list

24 splitlines() Splits the string at line breaks and returns a list

25 title() This method make upper case of starting letter of each word in sentance.

26 zfill() This method adds zeros (0) at the beginning of the string.

27 swapcase() Swaps cases, lower case becomes upper case and vice versa.

28 isalnum() It checks whether the string consists of alphanumeric characters.

29 isalpha() Returns True if all characters in the string are in the alphabet.

30 isascii() Returns True if all characters in the string are ascii characters.

31 isdecimal() Returns True if all characters in the string are decimals.

32 isdigit() Checks whether the string consists of digits only.

33 isidentifier() Returns True if the string is an identifier.

34 islower() Checks whether the string consists of lower case only.

35 isupper() Checks whether the string consists of upper case only.

36 isspace() Returns True if all characters in the string are whitespaces.

37 isprintable() Returns True if all characters in the string are printable

38 isnumeric() Returns True if all characters in the string are numeric

39 istitle() Returns True if the string follows the rules of a title

40 maketrans() Returns a translation table to be used in translations

41 translate() Returns a translated string

01. capitalize() :
Converts the first character to upper case and rest to lower..!

In [6]: 1 #Example -1 : General example


2 s = "python is a programming language"
3 print(s.capitalize())

Python is a programming language


In [3]: 1 #Example -2 :The first character is converted to upper case, and the rest
2 s = "python is a Programming Language"
3 print(s.capitalize())

Python is a programming language

In [5]: 1 #example -3: See what happens if the first character is a number:
2 s = "25 Is my Age"
3 print(s.capitalize())

25 is my age

02. casefold():
The casefold() method returns a string where all the characters are lower case.
This method is similar to the lower() method, but the casefold() method is stronger, more
aggressive, meaning that it will convert more characters into lower case, and will find more
matches when comparing two strings and both are converted using the casefold() method.

In [1]: 1 txt = "Hello, And Welcome To My World!"


2 print(txt.casefold())

hello, and welcome to my world!

03. count():
string.count(value, start, end)

value : Required. A String. The string to value to search for


start : Optional. An Integer. The position to start the search. Default is 0
end : Optional. An Integer. The position to end the search. Default is the end of the string

The count() method returns the number of times a specified value appears in the string.

In [2]: 1 txt = "I love apples, apple are my favorite fruit"


2 x = txt.count("apple")
3 print(x)

In [3]: 1 #Search from position 10 to 24:


2 txt = "I love apples, apple are my favorite fruit"
3 x = txt.count("apple", 10, 24)
4 print(x)

1
04. startswith():
string.startswith(value, start, end)

value : Required. The value to check if the string starts with


start : Optional. An Integer specifying at which position to start the search
end : Optional. An Integer specifying at which position to end the search

The startswith() method returns True if the string starts with the specified value, otherwise
False.

In [7]: 1 txt = "Hello, welcome to my world."


2 x = txt.startswith("Hello")
3 print(x)

True

In [8]: 1 #Check if position 7 to 20 starts with the characters "wel":


2 txt = "Hello, welcome to my world."
3 x = txt.startswith("wel", 7, 20)
4 print(x)

True

In [9]: 1 PyTxt="Python programming is easy."


2 print(PyTxt.startswith('programming is', 7))
3 print(PyTxt.startswith('programming is', 7, 19))
4 print(PyTxt.startswith('programming is', 7, 22))

True
False
True

05. endswith():
string.endswith(value, start, end)

value : Required. The value to check if the string starts with


start : Optional. An Integer specifying at which position to start the search
end : Optional. An Integer specifying at which position to end the search

The endswith() method returns True if the string ends with the specified value, otherwise
False.
In [11]: 1 txt = "Hello, welcome to my world."
2 x = txt.endswith(".")
3 print(x)

True

In [12]: 1 #Check if the string ends with the phrase "my world.":
2 txt = "Hello, welcome to my world."
3 x = txt.endswith("my world.")
4 print(x)

True

In [13]: 1 #Check if position 5 to 11 ends with the phrase "my world.":


2 txt = "Hello, welcome to my world."
3 x = txt.endswith("my world.", 5, 11)
4 print(x)

False

06. expandtabs():
string.expandtabs(tabsize)

The expandtabs() method sets the tab size to the specified number of whitespaces.
tabsize : A number specifying the tabsize. Default tabsize is 8

In [15]: 1 txt = "H\te\tl\tl\to"


2 x = txt.expandtabs()
3 print(x)

H e l l o

In [16]: 1 txt = "H\te\tl\tl\to"


2 x = txt.expandtabs(8)
3 print(x)

H e l l o

In [17]: 1 txt = "H\te\tl\tl\to"


2 x = txt.expandtabs(4)
3 print(x)

H e l l o
In [19]: 1 txt = "H\te\tl\tl\to"
2 print(txt)

H e l l o

In [18]: 1 txt = "H\te\tl\tl\to"


2 print(txt)
3 print(txt.expandtabs())
4 print(txt.expandtabs(2))
5 print(txt.expandtabs(4))
6 print(txt.expandtabs(10))

H e l l o
H e l l o
H e l l o
H e l l o
H e l l o

Finding Substrings:
In PYTHON programming to find sub strings we can use the following 4 methods:
Forward direction:

21.find() 22.index()

Backward direction:

23.rfind() 24.rindex()

07. find():
string.find(value, start, end)

value : Required. The value to search for


start : Optional. Where to start the search. Default is 0
end : Optional. Where to end the search. Default is to the end of the string

The find() method finds the first occurrence of the specified value.
The find() method returns -1 if the value is not found.
The find() method is almost the same as the index() method, the only difference is that the
index() method raises an exception if the value is not found. (See example below)

In [20]: 1 txt = "Hello, welcome to my world."


2 x = txt.find("welcome")
3 print(x)

7
In [21]: 1 #Where in the text is the first occurrence of the letter "e"?:
2 txt = "Hello, welcome to my world."
3 x = txt.find("e")
4 print(x)

In [22]: 1 #Where in the text is the first occurrence of the letter "e" when you onl
2 txt = "Hello, welcome to my world."
3 x = txt.find("e", 5, 10)
4 print(x)

In [4]: 1 #If the value is not found, the find() method returns -1, but the index()
2 txt = "Hello, welcome to my world."
3 print(txt.find("q"))

-1

08. index():
string.index(value, start, end)

value : Required. The value to search for


start : Optional. Where to start the search. Default is 0
end : Optional. Where to end the search. Default is to the end of the string

The index() method finds the first occurrence of the specified value.
The index() method raises an exception if the value is not found.
The index() method is almost the same as the find() method, the only difference is that the
find() method returns -1 if the value is not found. (See example below)

In [24]: 1 txt = "Hello, welcome to my world."


2 x = txt.index("welcome")
3 print(x)

In [25]: 1 #Where in the text is the first occurrence of the letter "e"?:
2 txt = "Hello, welcome to my world."
3 x = txt.index("e")
4 print(x)

1
In [26]: 1 #Where in the text is the first occurrence of the letter "e" when you onl
2 txt = "Hello, welcome to my world."
3 x = txt.index("e", 5, 10)
4 print(x)

In [5]: 1 #If the value is not found, the find() method returns -1, but the index()
2 txt = "Hello, welcome to my world."
3 print(txt.index("q"))

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [5], in <cell line: 3>()
1 #If the value is not found, the find() method returns -1, but the in
dex() method will raise an exception:
2 txt = "Hello, welcome to my world."
----> 3 print(txt.index("q"))

ValueError: substring not found

09. rfind():
string.rfind(value, start, end)

value : Required. The value to search for


start : Optional. Where to start the search. Default is 0
end : Optional. Where to end the search. Default is to the end of the string

The rfind() method finds the last occurrence of the specified value.
The rfind() method returns -1 if the value is not found.
The rfind() method is almost the same as the rindex() method. See example below.

In [29]: 1 txt = "Mi casa, su casa."


2 x = txt.rfind("casa")
3 print(x)

12

In [30]: 1 txt = "Mi casa, su casa."


2 x = txt.find("casa")
3 print(x)

3
In [31]: 1 #Where in the text is the last occurrence of the letter "e"?:
2 txt = "Hello, welcome to my world."
3 x = txt.rfind("e")
4 print(x)

13

In [32]: 1 #Where in the text is the last occurrence of the letter "e" when you only
2 txt = "Hello, welcome to my world."
3 x = txt.rfind("e", 5, 10)
4 print(x)

In [33]: 1 #If the value is not found, the rfind() method returns -1, but the rindex
2 txt = "Hello, welcome to my world."
3 print(txt.rfind("q"))
4 print(txt.rindex("q"))

-1

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [33], in <cell line: 4>()
2 txt = "Hello, welcome to my world."
3 print(txt.rfind("q"))
----> 4 print(txt.rindex("q"))

ValueError: substring not found

10. rindex():
string.rindex(value, start, end)

value : Required. The value to search for


start : Optional. Where to start the search. Default is 0
end : Optional. Where to end the search. Default is to the end of the string

The rindex() method finds the last occurrence of the specified value.
The rindex() method raises an exception if the value is not found.
The rindex() method is almost the same as the rfind() method. See example below.

In [34]: 1 txt = "Mi casa, su casa."


2 x = txt.rindex("casa")
3 print(x)

12
In [35]: 1 txt = "Mi casa, su casa."
2 x = txt.index("casa")
3 print(x)

In [36]: 1 #Where in the text is the last occurrence of the letter "e"?:
2 txt = "Hello, welcome to my world."
3 x = txt.rindex("e")
4 print(x)

13

In [37]: 1 #Where in the text is the last occurrence of the letter "e" when you only
2 txt = "Hello, welcome to my world."
3 x = txt.rindex("e", 5, 10)
4 print(x)

In [38]: 1 #If the value is not found, the rfind() method returns -1, but the rindex
2 txt = "Hello, welcome to my world."
3 print(txt.rfind("q"))
4 print(txt.rindex("q"))

-1

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [38], in <cell line: 4>()
2 txt = "Hello, welcome to my world."
3 print(txt.rfind("q"))
----> 4 print(txt.rindex("q"))

ValueError: substring not found

11. join():
The join() method takes all items in an iterable and joins them into one string.
A string must be specified as the separator.

Note : When using a dictionary as an iterable, the returned values are the keys, not the
values.

In [39]: 1 myTuple = ("John", "Peter", "Vicky")


2 x = "#".join(myTuple)
3 print(x)

John#Peter#Vicky
In [40]: 1 myDict = {"name": "rakesh", "country": "india","age":25}
2 mySeparator = " "
3 x = mySeparator.join(myDict)
4 print(x)

name country age

12. format():
string.format(value1, value2...)

value1, value2... :
Required. One or more values that should be formatted
and inserted in the string.
The values are either a list of values separated by c
ommas, a key=value list, or a combination of both.
The values can be of any data type.

The format() method formats the specified value(s) and insert them inside the string's
placeholder.
The placeholder is defined using curly brackets: {}. Read more about the placeholders in
the Placeholder section below.
The format() method returns the formatted string.

In [43]: 1 # The placeholders can be identified using named indexes {price}, numbere
2 txt1 = "My name is {fname}, I'm {age}".format(fname = "John", age = 36)
3 txt2 = "My name is {0}, I'm {1}".format("John",36)
4 txt3 = "My name is {}, I'm {}".format("John",36)
5 ​
6 print(txt1)
7 print(txt2)
8 print(txt3)

My name is John, I'm 36


My name is John, I'm 36
My name is John, I'm 36

13. lower():
The lower() method returns a string where all characters are lower case.

In [45]: 1 txt = "Hello my FRIENDS"


2 x = txt.lower()
3 print(x)

hello my friends
14. upper():
The upper() method returns a string where all characters are in upper case.

In [46]: 1 txt = "Hello my FRIENDS"


2 x = txt.upper()
3 print(x)

HELLO MY FRIENDS

15. rjust():
string.rjust(length, character)

The rjust() method will right align the string, using a specified character (space is default)
as the fill character.

In [8]: 1 txt = "Python"


2 print(txt,len(txt))
3 txt1 = txt.rjust(20)
4 print(txt1,len(txt1))
5 print(txt.rjust(20,"%"),len(txt.rjust(20,"%")))

Python 6
Python 20
%%%%%%%%%%%%%%Python 20

16. ljust():
string.ljust(length, character)

The ljust() method will left align the string, using a specified character (space is default) as
the fill character.

In [49]: 1 txt = "Python"


2 print(txt,len(txt))
3 txt1 = txt.ljust(20)
4 print(txt1,len(txt1))
5 print(txt.ljust(20,"%"),len(txt.ljust(20,"%")))

Python 6
Python 20
Python%%%%%%%%%%%%%% 20

17. center():
string.center(length, character)
The center() method will center align the string, using a specified character (space is
default) as the fill character.

In [50]: 1 txt = "Python"


2 print(txt,len(txt))
3 txt1 = txt.center(20)
4 print(txt1,len(txt1))
5 print(txt.center(20,"%"),len(txt.center(20,"%")))

Python 6
Python 20
%%%%%%%Python%%%%%%% 20

18. rstrip():
string.rstrip(characters)

The rstrip() method removes any trailing characters (characters at the end a string), space
is the default trailing character to remove.

In [51]: 1 txt = " python "


2 print(txt.rstrip())

python

In [52]: 1 txt = ",,,,,ssaaww.....banana"


2 x = txt.rstrip("an.b")
3 print(x)

,,,,,ssaaww

In [53]: 1 txt = "banana,,,,,ssqqqww....."


2 x = txt.rstrip(",.qsw")
3 print(x)

banana

19. lstrip():
string.lstrip(characters)

The lstrip() method removes any leading characters (space is the default leading character
to remove)
In [55]: 1 txt = " python "
2 print(txt.lstrip())

python

In [60]: 1 txt = ",,,,,ssaaww.....banana"


2 x = txt.lstrip(",.as")
3 print(x)

ww.....banana

In [59]: 1 txt = ",,,,,ssaaww.....banana"


2 x = txt.lstrip(",.asw")
3 print(x)

banana

20. strip():
string.strip(characters)

The strip() method removes any leading, and trailing whitespaces.


Leading means at the beginning of the string, trailing means at the end.
You can specify which character(s) to remove, if not, any whitespaces will be removed.

In [61]: 1 txt = " banana "


2 print(txt.strip())

banana

In [62]: 1 txt = ",,,,,rrttgg.....banana....rrr"


2 x = txt.strip(",.grt")
3 print(x)

banana

In [63]: 1 txt = ",,,,,rrttgg.....banana....rrr"


2 x = txt.strip(",.rt")
3 print(x)

gg.....banana

21. replace():
string.replace(oldvalue, newvalue, count)

It returns a copy of the string in which the occurrences of old have been replaced with
new, optionally restricting the number of replacements to max.
All occurrences of the specified phrase will be replaced, if nothing else is specified.

In [65]: 1 s = "I like coding"


2 print(s.replace('coding',"Gaming"))

I like Gaming

In [66]: 1 #Replace all occurrence of the word "one":


2 txt = "one one was a race horse, two two was one too."
3 x = txt.replace("one", "three")
4 print(x)

three three was a race horse, two two was three too.

In [67]: 1 #Replace the two first occurrence of the word "one":


2 txt = "one one was a race horse, two two was one too."
3 x = txt.replace("one", "three", 2)
4 print(x)

three three was a race horse, two two was one too.

In [68]: 1 #If given sub-string not found then it will provide old string as output
2 s = "I like coding"
3 print(s.replace('C',"Gaming"))

I like coding

22. split():
string.split(separator, maxsplit)

separator : Optional. Specifies the separator to use when splitting the string. By default any
whitespace is a separator
maxsplit : Optional. Specifies how many splits to do. Default value is -1, which is "all
occurrences"

The split() method splits a string into a list.


You can specify the separator, default separator is any whitespace.
Note: When maxsplit is specified, the list will contain the specified number of elements
plus one.

In [70]: 1 txt = "welcome to the jungle"


2 x = txt.split()
3 print(x)

['welcome', 'to', 'the', 'jungle']


In [81]: 1 #Split the string, using comma, followed by a space, as a separator:
2 txt = "hello, my name is Peter, I am 26 years old"
3 x = txt.split(", ")
4 print(x)

['hello', 'my name is Peter', 'I am 26 years old']

In [72]: 1 #Use a hash character as a separator:


2 txt = "apple#banana#cherry#orange"
3 x = txt.split("#")
4 print(x)

['apple', 'banana', 'cherry', 'orange']

In [73]: 1 #Split the string into a list with max 2 items:


2 txt = "apple#banana#cherry#orange"
3 # setting the maxsplit parameter to 1, will return a list with 2 elements
4 x = txt.split("#", 1)
5 print(x)

['apple', 'banana#cherry#orange']

23. rsplit():
string.rsplit(separator, maxsplit)

separator : Optional. Specifies the separator to use when splitting the string. By default any
whitespace is a separator
maxsplit : Optional. Specifies how many splits to do. Default value is -1, which is "all
occurrences"

The rsplit() method splits a string into a list, starting from the right.
If no "max" is specified, this method will return the same as the split() method.
Note: When maxsplit is specified, the list will contain the specified number of elements
plus one.

In [74]: 1 txt = "apple, banana, cherry"


2 x = txt.rsplit(", ")
3 print(x)

['apple', 'banana', 'cherry']

In [75]: 1 txt = "welcome to the jungle"


2 x = txt.rsplit()
3 print(x)

['welcome', 'to', 'the', 'jungle']


In [82]: 1 #Split the string, using comma, followed by a space, as a separator:
2 txt = "hello, my name is Peter, I am 26 years old"
3 x = txt.rsplit(", ")
4 print(x)

['hello', 'my name is Peter', 'I am 26 years old']

In [77]: 1 #Split the string into a list with maximum 2 items:


2 txt = "apple, banana, cherry"
3 # setting the maxsplit parameter to 1, will return a list with 2 elements
4 x = txt.rsplit(", ", 1)
5 print(x)

['apple, banana', 'cherry']

24. splitlines():
string.splitlines(keeplinebreaks)

keeplinebreaks : Optional. Specifies if the line breaks should be included (True), or not (False).
Default value is False

The splitlines() method splits a string into a list. The splitting is done at line breaks.

In [83]: 1 txt = "Thank you for the music\nWelcome to the jungle"


2 x = txt.splitlines()
3 print(x)

['Thank you for the music', 'Welcome to the jungle']

In [84]: 1 #Split the string, but keep the line breaks:


2 txt = "Thank you for the music\nWelcome to the jungle"
3 x = txt.splitlines(True)
4 print(x)

['Thank you for the music\n', 'Welcome to the jungle']

25. title():
The title() method returns a string where the first character in every word is upper case.
Like a header, or a title.
If the word contains a number or a symbol, the first letter after that will be converted to
upper case.
In [88]: 1 # Make the first letter in each word upper case:
2 txt = "Welcome to my 2nd world"
3 print(txt.title())

Welcome To My 2Nd World

Note that the first letter after a non-alphabet letter is converted into a upper case letter:

In [89]: 1 txt = "hello b2b2b2 and 3g3g3g"


2 print(txt.title())

Hello B2B2B2 And 3G3G3G

26. zfill():
string.zfill(len)

The zfill() method adds zeros (0) at the beginning of the string, until it reaches the
specified length.
If the value of the len parameter is less than the length of the string, no filling is done.

In [90]: 1 txt1 = "Python is prg lang"


2 txt2 = "Hello"
3 txt3 = "8888"
4 print(txt1.zfill(10))
5 print(txt2.zfill(10))
6 print(txt3.zfill(10))

Python is prg lang


00000Hello
0000008888

27. swapcase():
The swapcase() method returns a string where all the upper case letters are lower case
and vice versa.

In [92]: 1 txt = "Hello My Name Is PETER"


2 print(txt.swapcase())

hELLO mY nAME iS peter

28. isalnum():
The isalnum() method returns True if all the characters are alphanumeric, meaning
alphabet letter (a-z) and numbers (0-9).
Example of characters that are not alphanumeric: (space)!#%&? etc.
In [93]: 1 txt = "Python3"
2 print(txt.isalnum())

True

In [95]: 1 txt = "Python3.9"


2 print(txt.isalnum())

False

In [96]: 1 txt = "Python3 9"


2 print(txt.isalnum())

False

29. isalpha():
The isalpha() method returns True if all the characters are alphabet letters (a-z).
Example of characters that are not alphabet letters: (space)!#%&? etc.

In [98]: 1 txt = "CompanyX"


2 x = txt.isalpha()
3 print(x)

True

In [99]: 1 txt = "Company10"


2 x = txt.isalpha()
3 print(x)

False

30. isascii():
The isascii() method returns True if all the characters are ascii characters (a-z).

In [100]: 1 txt = "Company123"


2 x = txt.isascii()
3 print(x)

True
In [102]: 1 txt = "అమ్మ "
2 x = txt.isascii()
3 print(x)

False

In [103]: 1 txt = "Company123అ"


2 x = txt.isascii()
3 print(x)

False

ASCII Character Set


ASCII stands for the "American Standard Code for Information Interchange".
It was designed in the early 60's, as a standard character set for computers and electronic
devices.
ASCII is a 7-bit character set containing 128 characters.
It contains the numbers from 0-9, the upper and lower case English letters from A to Z,
and some special characters.
The character sets used in modern computers, in HTML, and on the Internet, are all based
on ASCII.
The following tables list the 128 ASCII characters and their equivalent number.

Reference:https://www.w3schools.com/charsets/ref_html_ascii.asp
(https://www.w3schools.com/charsets/ref_html_ascii.asp)

Char Number Description

NUL 0 null character

SOH 1 start of header

STX 2 start of text

ETX 3 end of text

EOT 4 end of transmission

ENQ 5 enquiry

ACK 6 acknowledge

BEL 7 bell (ring)

BS 8 backspace

HT 9 horizontal tab

LF 10 line feed

VT 11 vertical tab

FF 12 form feed

CR 13 carriage return

SO 14 shift out

SI 15 shift in
Char Number Description

DLE 16 data link escape

DC1 17 device control 1

DC2 18 device control 2

DC3 19 device control 3

DC4 20 device control 4

NAK 21 negative acknowledge

SYN 22 synchronize

ETB 23 end transmission block

CAN 24 cancel

EM 25 end of medium

SUB 26 substitute

ESC 27 escape

FS 28 file separator

GS 29 group separator

RS 30 record separator

US 31 unit separator

32 space

! 33 exclamation mark

" 34 quotation mark

# 35 number sign

$ 36 dollar sign

% 37 percent sign

& 38 ampersand

' 39 apostrophe

( 40 left parenthesis

) 41 right parenthesis

* 42 asterisk

+ 43 plus sign

, 44 comma

- 45 hyphen

. 46 period

/ 47 slash

0 48 digit 0

1 49 digit 1

2 50 digit 2

3 51 digit 3
Char Number Description

4 52 digit 4

5 53 digit 5

6 54 digit 6

7 55 digit 7

8 56 digit 8

9 57 digit 9

: 58 colon

; 59 semicolon

< 60 less-than

= 61 equals-to

> 62 greater-than

? 63 question mark

@ 64 at sign

A 65 uppercase A

B 66 uppercase B

C 67 uppercase C

D 68 uppercase D

E 69 uppercase E

F 70 uppercase F

G 71 uppercase G

H 72 uppercase H

I 73 uppercase I

J 74 uppercase J

K 75 uppercase K

L 76 uppercase L

M 77 uppercase M

N 78 uppercase N

O 79 uppercase O

P 80 uppercase P

Q 81 uppercase Q

R 82 uppercase R

S 83 uppercase S

T 84 uppercase T

U 85 uppercase U

V 86 uppercase V

W 87 uppercase W
Char Number Description

X 88 uppercase X

Y 89 uppercase Y

Z 90 uppercase Z

[ 91 left square bracket

\ 92 backslash

] 93 right square bracket

^ 94 caret

_ 95 underscore

` 96 grave accent

a 97 lowercase a

b 98 lowercase b

c 99 lowercase c

d 100 lowercase d

e 101 lowercase e

f 102 lowercase f

g 103 lowercase g

h 104 lowercase h

i 105 lowercase i

j 106 lowercase j

k 107 lowercase k

l 108 lowercase l

m 109 lowercase m

n 110 lowercase n

o 111 lowercase o

p 112 lowercase p

q 113 lowercase q

r 114 lowercase r

s 115 lowercase s

t 116 lowercase t

u 117 lowercase u

v 118 lowercase v

w 119 lowercase w

x 120 lowercase x

y 121 lowercase y

z 122 lowercase z
31. isdecimal():
The isdecimal() method returns True if all the characters are decimals (0-9).
This method can also be used on unicode objects. See example below.

In [105]: 1 txt = "1234"


2 x = txt.isdecimal()
3 print(x)

True

In [114]: 1 #Check if all the characters in the unicode are decimals:


2 ​
3 a = "\u0030" #unicode for 0
4 b = "\u0047" #unicode for G
5 c = "\u0061" ##unicode for a
6 print(a.isdecimal())
7 print(b.isdecimal())
8 print(c.isdecimal())

True
False
False

32. isdigit():
The isdigit() method returns True if all the characters are digits, otherwise False.
Exponents, like ², are also considered to be a digit.

In [115]: 1 s="PYTHON"
2 print(s.isdigit())

False

In [116]: 1 s="12345"
2 print(s.isdigit())

True

In [117]: 1 # even space also it give false


2 s="123 45"
3 print(s.isdigit())

False
In [118]: 1 s="25 is my age"
2 print(s.isdigit())

False

33. isidentifier():
The isidentifier() method returns True if the string is a valid identifier, otherwise False.
A string is considered a valid identifier if it only contains alphanumeric letters (a-z) and (0-
9), or underscores (_). A valid identifier cannot start with a number, or contain any spaces.

In [119]: 1 txt = "Demo"


2 x = txt.isidentifier()
3 print(x)

True

In [122]: 1 txt = "Demo@"


2 x = txt.isidentifier()
3 print(x)

False

In [121]: 1 a = "MyFolder"
2 b = "Demo002"
3 c = "2bring"
4 d = "my demo"
5 ​
6 print(a.isidentifier())
7 print(b.isidentifier())
8 print(c.isidentifier())
9 print(d.isidentifier())

True
True
False
False

34. islower():
Return true if all charcters are in string is lower case,otherwise False.

In [123]: 1 s = "PYTHON"
2 print(s.islower())

False
In [124]: 1 s = "Python"
2 print(s.islower())

False

In [125]: 1 s = "python"
2 print(s.islower())

True

In [126]: 1 s = "python123"
2 print(s.islower())

True

In [127]: 1 s = "python 123"


2 print(s.islower())

True

In [128]: 1 s = "python@"
2 print(s.islower())

True

35. isupper():
Return true if all charcters are in string is upper case,otherwise False.
Numbers, symbols and spaces are not checked, only alphabet characters.

In [129]: 1 s = "PYTHON"
2 print(s.isupper())

True

In [130]: 1 s = "pYTHON"
2 print(s.isupper())

False

In [131]: 1 s = "PYTHON123"
2 print(s.isupper())

True
In [132]: 1 s = "PYTHON123%"
2 print(s.isupper())

True

36. isspace():
The isspace() method returns True if all the characters in a string are whitespaces,
otherwise False.

In [133]: 1 txt = " "


2 x = txt.isspace()
3 print(x)

True

In [134]: 1 txt = ""


2 x = txt.isspace()
3 print(x)

False

In [135]: 1 txt = " "


2 x = txt.isspace()
3 print(x)

True

In [136]: 1 txt = " python "


2 x = txt.isspace()
3 print(x)

False

In [137]: 1 PyStr="\t\t"
2 print(PyStr.isspace())
3 PyStr="\n"
4 print(PyStr.isspace())

True
True

37. isprintable():
The isprintable() method returns True if all the characters are printable, otherwise False.
Example of none printable character can be carriage return and line feed.
In [138]: 1 txt = "Hello! Are you #1?"
2 x = txt.isprintable()
3 print(x)

True

In [139]: 1 txt = "Hello!\nAre you #1?"


2 x = txt.isprintable()
3 print(x)

False

In [140]: 1 txt = "Hello! \t Are you #1?"


2 x = txt.isprintable()
3 print(x)

False

38. isnumeric():
The isnumeric() method returns True if all the characters are numeric (0-9), otherwise
False.
Exponents, like ² and ¾ are also considered to be numeric values.
"-1" and "1.5" are NOT considered numeric values, because all the characters in the string
must be numeric, and the - and the . are not.

In [141]: 1 txt = "565543"


2 x = txt.isnumeric()
3 print(x)

True

In [142]: 1 a = "\u0030" #unicode for 0


2 b = "\u00B2" #unicode for &sup2;
3 c = "10km2"
4 d = "-1"
5 e = "1.5"
6 ​
7 print(a.isnumeric())
8 print(b.isnumeric())
9 print(c.isnumeric())
10 print(d.isnumeric())
11 print(e.isnumeric())

True
True
False
False
False
39. istitle():
The istitle() method returns True if all words in a text start with a upper case letter, AND
the rest of the word are lower case letters, otherwise False.
Symbols and numbers are ignored.

In [143]: 1 txt = "Hello, And Welcome To My World!"


2 x = txt.istitle()
3 print(x)

True

In [144]: 1 a = "HELLO, AND WELCOME TO MY WORLD"


2 b = "Hello"
3 c = "22 Names"
4 d = "This Is %'!?"
5 ​
6 print(a.istitle())
7 print(b.istitle())
8 print(c.istitle())
9 print(d.istitle())

False
True
True
True

40. maketrans():
str.maketrans(x, y, z)

x :
Required. If only one parameter is specified, this has to be a dictio
nary describing how to perform the replace. If two or more parameters
are specified, this parameter has to be a string specifying the chara
cters you want to replace.<br>
y :
Optional. A string with the same length as parameter x. Each characte
r in the first parameter will be replaced with the corresponding char
acter in this string.<br>
z :
Optional. A string describing which characters to remove from the ori
ginal string.

The maketrans() method returns a mapping table that can be used with the translate()
method to replace specified characters.
In [159]: 1 #Create a mapping table, and use it in the translate() method to replace
2 ​
3 txt = "Hello Sam!"
4 mytable = txt.maketrans("S", "P")
5 print(txt.translate(mytable))

Hello Pam!

In [160]: 1 #Use a mapping table to replace many characters:


2 ​
3 txt = "Hi Sam!"
4 x = "mSa"
5 y = "eJo"
6 mytable = txt.maketrans(x, y)
7 print(txt.translate(mytable))

Hi Joe!

In [161]: 1 txt = "Hi Sam!"


2 x = "Sma"
3 y = "eJo"
4 mytable = txt.maketrans(x, y)
5 print(txt.translate(mytable))

Hi eoJ!

In [162]: 1 txt = "Hi Sam!"


2 x = "Sma"
3 y = "eJo0"
4 mytable = txt.maketrans(x, y)
5 print(txt.translate(mytable))

---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
Input In [162], in <cell line: 4>()
2 x = "Sma"
3 y = "eJo0"
----> 4 mytable = txt.maketrans(x, y)
5 print(txt.translate(mytable))

ValueError: the first two maketrans arguments must have equal length
In [164]: 1 #The third parameter in the mapping table describes characters that you w
2 ​
3 txt = "Good night Sam!"
4 x = "mSa"
5 y = "eJo"
6 z = "odnght"
7 mytable = txt.maketrans(x, y, z)
8 print(txt.translate(mytable))

G i Joe!

In [165]: 1 txt = "Good night Samnnnnnnnnnn!"


2 x = "mSa"
3 y = "eJo"
4 z = "odnght"
5 mytable = txt.maketrans(x, y, z)
6 print(txt.translate(mytable))

G i Joe!

In [166]: 1 #The maketrans() method itself returns a dictionary describing each repla
2 ​
3 txt = "Good night Sam!"
4 x = "mSa"
5 y = "eJo"
6 z = "odnght"
7 print(txt.maketrans(x, y, z))

{109: 101, 83: 74, 97: 111, 111: None, 100: None, 110: None, 103: None, 104:
None, 116: None}

41. translate():
string.translate(table)

table : Required. Either a dictionary, or a mapping table describing how to perform the replace

The translate() method returns a string where some specified characters are replaced with
the character described in a dictionary, or in a mapping table.
Use the maketrans() method to create a mapping table.
If a character is not specified in the dictionary/table, the character will not be replaced.
If you use a dictionary, you must use ascii codes instead of characters.

In [170]: 1 #use a dictionary with ascii codes to replace 83 (S) with 80 (P):
2 mydict = {83: 80}
3 txt = "Hello Sam!"
4 print(txt.translate(mydict))

Hello Pam!
In [175]: 1 print(chr(83))
2 print(chr(80))

S
P

In [185]: 1 #Use a mapping table to replace "S" with "P":


2 ​
3 txt = "Hello Sam!"
4 mytable = txt.maketrans("S", "P")
5 print(txt.translate(mytable))

Hello Pam!

In [184]: 1 #Use a mapping table to replace many characters:


2 ​
3 txt = "Hi Sam!"
4 x = "mSa"
5 y = "eJo"
6 mytable = txt.maketrans(x, y)
7 print(txt.translate(mytable))

Hi Joe!

In [183]: 1 #The third parameter in the mapping table describes characters that you w
2 ​
3 txt = "Good night Sam!"
4 x = "mSa"
5 y = "eJo"
6 z = "odnght"
7 mytable = txt.maketrans(x, y, z)
8 print(txt.translate(mytable))

G i Joe!

In [182]: 1 txt = "Good night Sam!"


2 x = "mSa"
3 y = "eJo"
4 z = "odnght"
5 print(txt.maketrans(x, y, z))

{109: 101, 83: 74, 97: 111, 111: None, 100: None, 110: None, 103: None, 104:
None, 116: None}

In [181]: 1 #The same example as above, but using a dictionary instead of a mapping t
2 ​
3 txt = "Good night Sam!"
4 mydict = {109: 101, 83: 74, 97: 111, 111: None, 100: None, 110: None, 103
5 print(txt.translate(mydict))

G i Joe!
42. partition():
string.partition(value)

value : Required. The string to search for

The partition() method searches for a specified string, and splits the string into a tuple
containing three elements.
The first element contains the part before the specified string.
The second element contains the specified string.
The third element contains the part after the string.
Note: This method searches for the first occurrence of the specified string.

In [188]: 1 # Search for the word "bananas", and return a tuple with three elements:
2 # 1 - everything before the "match"
3 # 2 - the "match"
4 # 3 - everything after the "match"
5 ​
6 txt = "I could eat bananas all day, bananas are my favorite fruit"
7 x = txt.partition("bananas")
8 print(x)

('I could eat ', 'bananas', ' all day, bananas are my favorite fruit')

In [190]: 1 # If the specified value is not found, the partition() method returns a t
2 # 1 - the whole string
3 # 2 - an empty string
4 # 3 - an empty string:
5 ​
6 txt = "I could eat bananas all day, bananas are my favorite fruit"
7 x = txt.partition("apples")
8 print(x)

('I could eat bananas all day, bananas are my favorite fruit', '', '')

43. rpartition():
string.rpartition(value)

value : Required. The string to search for

The rpartition() method searches for the last occurrence of a specified string, and splits the
string into a tuple containing three elements.
The first element contains the part before the specified string.
The second element contains the specified string.
The third element contains the part after the string.
In [189]: 1 # Search for the last occurrence of the word "bananas", and return a tupl
2 ​
3 # 1 - everything before the "match"
4 # 2 - the "match"
5 # 3 - everything after the "match"
6 ​
7 txt = "I could eat bananas all day, bananas are my favorite fruit"
8 x = txt.rpartition("bananas")
9 print(x)

('I could eat bananas all day, ', 'bananas', ' are my favorite fruit')

In [191]: 1 # If the specified value is not found, the rpartition() method returns a
2 # 1 - an empty string
3 # 2 - an empty string
4 # 3 - the whole string:
5 ​
6 txt = "I could eat bananas all day, bananas are my favorite fruit"
7 x = txt.rpartition("apples")
8 print(x)

('', '', 'I could eat bananas all day, bananas are my favorite fruit')

Booleans
Booleans represent one of two values: True or False.
In programming you often need to know if an expression is True or False.
You can evaluate any expression in Python, and get one of two answers, True or False.
When you compare two values, the expression is evaluated and Python returns the
Boolean answer:

In [193]: 1 print(10 > 9)


2 print(10 == 9)
3 print(10 < 9)

True
False
False

When you run a condition in an if statement, Python returns True or False:


In [194]: 1 #Example : Print a message based on whether the condition is True or Fals
2 ​
3 a = 200
4 b = 33
5 ​
6 if b > a:
7 print("b is greater than a")
8 else:
9 print("b is not greater than a")

b is not greater than a

Evaluate Values and Variables


The bool() function allows you to evaluate any value, and give you True or False in return,

In [195]: 1 print(bool("Hello"))
2 print(bool(15))

True
True

In [196]: 1 x = "Hello"
2 y = 15
3 ​
4 print(bool(x))
5 print(bool(y))

True
True

Most Values are True

Almost any value is evaluated to True if it has some sort of content.


Any string is True, except empty strings.
Any number is True, except 0.
Any list, tuple, set, and dictionary are True, except empty ones.

Some Values are False

In fact, there are not many values that evaluate to False, except empty values, such as (), [], {},
"", the number 0, and the value None.
In [198]: 1 # True values
2 print(bool("abc"))
3 print(bool(123))
4 print(bool(["apple", "cherry", "banana"]))

True
True
True

In [201]: 1 # False value


2 print(bool(False))
3 print(bool(None))
4 print(bool(0))
5 print(bool(""))
6 print(bool(()))
7 print(bool([]))
8 print(bool({}))

False
False
False
False
False
False
False

Functions can Return a Boolean

You can create functions that returns a Boolean Value:

In [202]: 1 def myFunction() :


2 return True
3 ​
4 print(myFunction())

True

You can execute code based on the Boolean answer of a function:

In [204]: 1 #Example : Print "YES!" if the function returns True, otherwise print "NO
2 ​
3 def myFunction() :
4 return True
5 ​
6 if myFunction():
7 print("YES!")
8 else:
9 print("NO!")

YES!
Python also has many built-in functions that return a boolean value, like the isinstance()
function, which can be used to determine if an object is of a certain data type:

In [206]: 1 #Example : Check if an object is an integer or not:


2 x = 200
3 print(isinstance(x, int))

True

You might also like