0% found this document useful (0 votes)
32 views42 pages

01.basics Understanding and Data Types, Variables & Operators - Jupyter Notebook

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)
32 views42 pages

01.basics Understanding and Data Types, Variables & Operators - Jupyter Notebook

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/ 42

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

You might also like