Unit-1 2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 39

Python- UNIT 1

Python is a popular programming language. It was created by Guido van Rossum, and
released in 1991.

It is used for:

 web development (server-side),


 software development,
 mathematics,
 system scripting.

What can Python do?

 Python can be used on a server to create web applications.


 Python can be used alongside software to create workflows.
 Python can connect to database systems. It can also read and modify files.
 Python can be used to handle big data and perform complex mathematics.
 Python can be used for rapid prototyping, or for production-ready software
development.

Python Syntax compared to other programming languages

 Python was designed for readability, and has some similarities to the English
language with influence from mathematics.
 Python uses new lines to complete a command, as opposed to other programming
languages which often use semicolons or parentheses.
 Python relies on indentation, using whitespace, to define scope; such as the scope of
loops, functions and classes. Other programming languages often use curly-brackets
for this purpose.

Why to Learn Python?

Python is consistently rated as one of the world's most popular programming languages.
Python is fairly easy to learn, so if you are starting to learn any programming language then
Python could be your great choice. Today various Schools, Colleges and Universities are
teaching Python as their primary programming language. There are many other good reasons
which makes Python as the top choice of any programmer:

 Python is Open Source which means its available free of cost.


 Python is simple and so easy to learn
 Python is versatile and can be used to create many different things.
 Python has powerful development libraries include AI, ML etc.
 Python is much in demand and ensures high salary
Python is a MUST for students and working professionals to become a great Software
Engineer specially when they are working in Web Development Domain. I will list down
some of the key advantages of learning Python:

 Python is Interpreted − Python is processed at runtime by the interpreter. You do


not need to compile your program before executing it. This is similar to PERL and
PHP.
 Python is Interactive − You can actually sit at a Python prompt and interact with the
interpreter directly to write your programs.
 Python is Object-Oriented − Python supports Object-Oriented style or technique of
programming that encapsulates code within objects.
 Python is a Beginner's Language − Python is a great language for the beginner-level
programmers and supports the development of a wide range of applications from
simple text processing to WWW browsers to games.

Applications of Python

The latest release of Python is 3.x. As mentioned before, Python is one of the most widely
used language over the web. I'm going to list few of them here:

 Easy-to-learn − Python has few keywords, simple structure, and a clearly defined
syntax. This allows the student to pick up the language quickly.
 Easy-to-read − Python code is more clearly defined and visible to the eyes.
 Easy-to-maintain − Python's source code is fairly easy-to-maintain.
 A broad standard library − Python's bulk of the library is very portable and cross-
platform compatible on UNIX, Windows, and Macintosh.
 Interactive Mode − Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.
 Portable − Python can run on a wide variety of hardware platforms and has the same
interface on all platforms.
 Extendable − You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more efficient.
 Databases − Python provides interfaces to all major commercial databases.
 GUI Programming − Python supports GUI applications that can be created and
ported to many system calls, libraries and windows systems, such as Windows MFC,
Macintosh, and the X Window system of Unix.
 Scalable − Python provides a better structure and support for large programs than
shell scripting.

Integrated Development Environment


You can run Python from a Graphical User Interface (GUI) environment as well, if you have
a GUI application on your system that supports Python.
 Unix − IDLE is the very first Unix IDE for Python.
 Windows − PythonWin is the first Windows interface for Python and is an
IDE with a GUI.
 Macintosh − The Macintosh version of Python along with the IDLE IDE is
available from the main website, downloadable as either MacBinary or
BinHex'd files.
If you are not able to set up the environment properly, then you can take help from your
system admin. Make sure the Python environment is properly set up and working perfectly
fine.
We have provided Python Online Compiler/Interpreter which helps you
to Edit and Execute the code directly from your browser. Try to click the icon  to run the
following Python code to print conventional "Hello, World!".

Python Variables

Python Variable is containers which store values. Python is not “statically typed”. We do not
need to declare variables before using them or declare their type. A variable is created the
moment we first assign a value to it. A Python variable is a name given to a memory location.
It is the basic unit of storage in a program.

Example of Python Variables

Var = "Geeksforgeeks"
VAR= “A “
print(Var)

Output:
Geeksforgeeks
Notes:
 The value stored in a variable can be changed during program execution.
 A Python Variables is only a name given to a memory location, all the operations
done on the variable effects that memory location.

Rules for creating variables in Python


 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 (name, Name and NAME are three different
variables).
 The reserved words(keywords) cannot be used naming the variable.

Let’s see the simple variable creation:


# An integer assignment
age = 45
 
# A floating point
salary = 1456.8
 
# A string
name = "John"
 
print(age)
print(salary)
print(name)

Output:
45
1456.8
John

Declare the Variable


Let’s see how to declare the variable and print the variable.

# declaring the var


Number = 100
 # display
print( Number)

Output:
100

Re-declare the Variable


We can re-declare the python variable once we have declared the variable already.

# declaring the var


Number = 100
 
# display
print("Before declare: ", Number)
 
# re-declare the var
Number = 120.3
   
print("After re-declare:", Number)

Output:
Before declare: 100
After re-declare: 120.3

Assigning a single value to multiple variables

Also, Python allows assigning a single value to several variables simultaneously with “=”
operators. 
For example: 

a = b = c = 10
print(a)
print(b)
print(c)

Output:
10
10
10
Assigning different values to multiple variables
Python allows adding different values in a single line with “,”operators.

a, b, c = 1, 20.2, "GeeksforGeeks"
print(a)
print(b)
print(c)

Output:
1
20.2
GeeksforGeeks

Can we use the same name for different types? 


If we use the same name, the variable starts referring to a new value and type. 

a = 10
a = "GeeksforGeeks"
 print(a)

Output:
GeeksforGeeks

How does + operator work with variables? 

a = 10
b = 20
print(a+b)
a = "Geeksfor"
b = "Geeks"
print(a+b)

Output
30
GeeksforGeeks
Can we use + for different types also? 
No use for different types would produce an error. 

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

Global and Local Python Variables

Local variables are the ones that are defined and declared inside a function. We can not call
this variable outside the function.

# This function uses global variable


def f():
    s = "Welcome geeks"
    print(s)
f()

Output:
Welcome geeks
Global variables are the ones that are defined and declared outside a function, and we need
to use them inside a function.

# This function has a variable with


# name same as s.
def f():
    print(s)
 # Global scope
s = "I love Geeksforgeeks"
f()

Output:
I love Geeksforgeeks

Global keyword in Python


 Global keyword is a keyword that allows a user to modify a variable outside of the
current scope. It is used to create global variables from
 a non-global scope i.e inside a function. Global keyword is used inside a function only
when we want to do assignments or when we want to change a variable. Global is not
needed for printing and accessing.

Rules of global keyword:


 If a variable is assigned a value anywhere within the function’s body, it’s assumed
to be a local unless explicitly declared as global.
 Variables that are only referenced inside a function are implicitly global.
 We Use global keyword to use a global variable inside a function.
 There is no need to use global keyword outside a function.
Example:

# Python program to modify a global


# value inside a function
 x = 15
def change():
  # using a global keyword
    global x
    # increment value of a by 5
    x = x + 5
    print("Value of x inside a function :", x)
 change()
print("Value of x outside a function :", x)

Output:
Value of x inside a function : 20
Value of x outside a function : 20

Object References

Let, we assign a variable x to value 5, and 


x=5

Another variable is y to the variable x.


x=y
When Python looks at the first statement, what it does is that, first, it creates an object to
represent the value 5. Then, it creates the variable x if it doesn’t exist and made it a reference
to this new object 5. The second line causes Python to create the variable y, and it is not
assigned with x, rather it is made to reference that object that x does. The net effect is that the
variables x and y wind up referencing the same object. This situation, with multiple names
referencing the same object, is called a Shared Reference in Python.
Now, if we write:
x = 'Geeks'
This statement makes a new object to represent ‘Geeks’ and makes x to reference this new
object.

 Now if we assign the new value in Y, then the previous object refers to the garbage values.
y = "Computer

Python Data Types

Variables can hold values, and every value has a data-type. Python is a dynamically typed
language; hence we do not need to define the type of the variable while declaring it. The
interpreter implicitly binds the value with its type.

a = 5  

The variable a holds integer value five and we did not define its type. Python interpreter will
automatically interpret variables a as an integer type.

Python enables us to check the type of the variable used in the program. Python provides us
the type() function, which returns the type of the variable passed.

Consider the following example:

a=10 

b="Hi Python"  
c = 10.5  
print(type(a))  
print(type(b))  
print(type(c))  

Output:

<type 'int'>
<type 'str'>
<type 'float'>

Standard data types

A variable can hold different types of values. For example, a person's name must be stored as
a string whereas its id must be stored as an integer.

Python provides various standard data types that define the storage method on each of them.
The data types defined in Python are given below.

1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary

In this section of the tutorial, we will give a brief introduction of the above data-types. We
will discuss each one of them in detail later in this tutorial.
Numbers

Number stores numeric values. The integer, float, and complex values belong to a Python
Numbers data-type. Python provides the type() function to know the data-type of the
variable. Similarly, the isinstance() function is used to check an object belongs to a particular
class.

Python creates Number objects when a number is assigned to a variable. For example;

1. a = 5  
2. print("The type of a", type(a))  
3.   
4. b = 40.5  
5. print("The type of b", type(b))  
6.   
7. c = 1+3j  
8. print("The type of c", type(c))  
9. print(" c is a complex number", isinstance(1+3j,complex))  

Output:

The type of a <class 'int'>


The type of b <class 'float'>
The type of c <class 'complex'>
c is complex number: True

Python supports three types of numeric data.

1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python
has no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y
denote the real and imaginary parts, respectively. The complex numbers like 2.14j,
2.0 + 2.3j, etc.

Sequence Type

String

The string can be defined as the sequence of characters represented in the quotation marks. In
Python, we can use single, double, or triple quotes to define a string.

String handling in Python is a straightforward task since Python provides built-in functions
and operators to perform operations in the string.

In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
The operator * is known as a repetition operator as the operation "Python" *2 returns 'Python
Python'.

The following example illustrates the string in Python.

Example - 1

str = "string using double quotes"  
print(str)  
s = '''''A multiline 
string'''”
print(s)  

Output:

string using double quotes


A multiline
string

Consider the following example of string handling.

Example - 2

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

Output:

he
o
hello javatpointhello javatpoint
hello javatpoint how are you

List

Python Lists are similar to arrays in C. However, the list can contain data of different types.
The items stored in the list are separated with a comma (,) and enclosed within square
brackets [].

We can use slice [:] operators to access the data of the list. The concatenation operator (+)
and repetition operator (*) works with the list in the same way as they were working with the
strings.

Consider the following example.

list1  = [1, "hi", "Python", 2]    
#Checking type of given list  
print(type(list1))  
  
#Printing the list1  
print (list1)  
  
# List slicing  
print (list1[3:])  
  
# List slicing  
print (list1[0:2])   
  
# List Concatenation using + operator  
print (list1 + list1)  
  
# List repetation using * operator  
print (list1 * 3)  

Output:

[1, 'hi', 'Python', 2]


[2]
[1, 'hi']
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
[1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2, 1, 'hi', 'Python', 2]
# Python3 program to show the
# working of upper() function
text = 'geeKs For geEkS'
 
# upper() function to convert
# string to upper case
print("\nConverted String:")
print(text.upper())
 
# lower() function to convert
# string to lower case
print("\nConverted String:")
print(text.lower())
 
# converts the first character to
# upper case and rest to lower case
print("\nConverted String:")
print(text.title())
 
#swaps the case of all characters in the string
# upper case character to lowercase and viceversa
print("\nConverted String:")
print(text.swapcase())
 
# original string never changes
print("\nOriginal String")
print(text)

Tuple

A tuple is similar to the list in many ways. Like lists, tuples also contain the collection of the
items of different data types. The items of the tuple are separated with a comma (,) and
enclosed in parentheses ().

A tuple is a read-only data structure as we can't modify the size and value of the items of a
tuple.

Let's see a simple example of the tuple.

1. tup  = ("hi", "Python", 2)    
2. # Checking type of tup  
3. print (type(tup))    
4. #Printing the tuple  
5. print (tup)  
6. # Tuple slicing  
7. print (tup[1:])    
8. print (tup[0:1])    
9. # Tuple concatenation using + operator  
10. print (tup + tup)    
11. # Tuple repatation using * operator  
12. print (tup * 3)     
13. # Adding value to tup. It will throw an error.  
14. tup[2] = "hi"  

Output:

<class 'tuple'>
('hi', 'Python', 2)
('Python', 2)
('hi',)
('hi', 'Python', 2, 'hi', 'Python', 2)
('hi', 'Python', 2, 'hi', 'Python', 2, 'hi', 'Python', 2)

Traceback (most recent call last):


File "main.py", line 14, in <module>
t[2] = "hi";
TypeError: 'tuple' object does not support item assignment
Dictionary

Dictionary is an unordered set of a key-value pair of items. It is like an associative array or a


hash table where each key stores a specific value. Key can hold any primitive data type,
whereas value is an arbitrary Python object.

The items in the dictionary are separated with the comma (,) and enclosed in the curly braces
{}.

Consider the following example.

1. d = {1:'Jimmy', 2:'Alex', 3:'john', 4:'mike'}     
2. # Printing dictionary  
3. print (d)  
4. # Accesing value using keys  
5. print("1st name is "+d[1])   
6. print("2nd name is "+ d[4])    
7. print (d.keys())    
8. print (d.values())    

Output:

1st name is Jimmy


2nd name is mike
{1: 'Jimmy', 2: 'Alex', 3: 'john', 4: 'mike'}
dict_keys([1, 2, 3, 4])
dict_values(['Jimmy', 'Alex', 'john', 'mike'])

Boolean

Boolean type provides two built-in values, True and False. These values are used to
determine the given statement true or false. It denotes by the class bool. True can be
represented by any non-zero value or 'T' whereas false can be represented by the 0 or 'F'.
Consider the following example.

1. # Python program to check the boolean type  
2. print(type(True))  
3. print(type(False))  
4. print(false)  

Output:

<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined

Set

Python Set is the unordered collection of the data type. It is iterable, mutable(can modify
after creation), and has unique elements. In set, the order of the elements is undefined; it may
return the changed sequence of the element. The set is created by using a built-in
function set(), or a sequence of elements is passed in the curly braces and separated by the
comma. It can contain various types of values. Consider the following example.

1. # Creating Empty set  
2. set1 = set()  
3. set2 = {'James', 2, 3,'Python'}  
4. #Printing Set value  
5. print(set2)  
6. # Adding element to the set  
7. set2.add(10)  
8. print(set2)  
9. #Removing element from the set  
10. set2.remove(2)  
11. print(set2)  

Output:

{3, 'Python', 'James', 2}


{'Python', 'James', 3, 2, 10}
{'Python', 'James', 3, 10}

Difference Between List and Tuple (Table)

Following are the difference between list and tuple - 

Python Lists Python Tuples

1 Tuples are immutable


List are mutable

2 Iterations are time-consuming Iterations are comparatively Faster

Inserting and deleting items is easier Accessing the elements is best


3
with a list. accomplished with a tuple data type.
4 Lists consume more memory Tuple consumes less than the list

A tuple does not have many built-in


5 Lists have several built-in methods.
methods because of immutability

A unexpected change or error is In a tuple, changes and errors don't usually


6
more likely to occur in a list. occur because of immutability.

Sets in Python
A Set is an unordered collection data type that is iterable, mutable, and has no duplicate
elements. 
Set are represented by { } (values enclosed in curly braces)
The major advantage of using a set, as opposed to a list, is that it has a highly optimized
method for checking whether a specific element is contained in the set. This is based on a
data structure known as a hash table. Since sets are unordered, we cannot access items using
indexes as we do in lists.

var = {"Geeks", "for", "Geeks"}


type(var)

Output:
set

Python set() method is used for type casting in Pytho

# typecasting list to set


myset = set(["a", "b", "c"])
print(myset)
 
# Adding element to the set
myset.add("d")
print(myset)

Output:
{'c', 'b', 'a'}
{'d', 'c', 'b', 'a'}
Python Frozen Sets
Frozen sets in Python are immutable objects that only support methods and operators that
produce a result without affecting the frozen set or sets to which they are applied. It can be
done with frozenset() method in Python.
While elements of a set can be modified at any time, elements of the frozen set remain the
same after creation. 
If no parameters are passed, it returns an empty frozenset.

# Python program to demonstrate differences


# between normal and frozen set
 
# Same as {"a", "b","c"}
normal_set = set(["a", "b","c"])
 
print("Normal Set")
print(normal_set)
 
# A frozen set
frozen_set = frozenset(["e", "f", "g"])
 
print("\nFrozen Set")
print(frozen_set)
 
# Uncommenting below line would cause error as
# we are trying to add element to a frozen set
# frozen_set.add("h")

Output:
Normal Set
{'a', 'c', 'b'}

Frozen Set
{'e', 'g', 'f'}
 
Methods for Sets

Adding elements to Python Sets

Insertion in set is done through set.add() function, where an appropriate record value is
created to store in the hash table. Same as checking for an item, i.e., O(1) on average.
However, in worst case it can become O(n).

# A Python program to
# demonstrate adding elements
# in a set
 
# Creating a Set
people = {"Jay", "Idrish", "Archi"}
 
print("People:", end = " ")
print(people)
 
# This will add Daxit
# in the set
people.add("Daxit")
 
# Adding elements to the
# set using iterator
for i in range(1, 6):
    people.add(i)
 
print("\nSet after adding element:", end = " ")
print(people)

Output:
People: {'Idrish', 'Archi', 'Jay'}

Set after adding element: {1, 2, 3, 4, 5, 'Idrish', 'Archi', 'Jay', 'Daxit'}

Union operation on Python Sets

Two sets can be merged using union() function or | operator. Both Hash Table values are
accessed and traversed with merge operation perform on them to combine the elements, at the
same time duplicates are removed. The Time Complexity of this is O(len(s1) +
len(s2)) where s1 and s2 are two sets whose union needs to be done.
 

# Python Program to
# demonstrate union of
# two sets
 
people = {"Jay", "Idrish", "Archil"}
vampires = {"Karan", "Arjun"}
dracula = {"Deepanshu", "Raju"}
 
# Union using union()
# function
population = people.union(vampires)
 
print("Union using union() function")
print(population)
 
# Union using "|"
# operator
population = people|dracula
 
print("\nUnion using '|' operator")
print(population)

Output:
Union using union() function
{'Karan', 'Idrish', 'Jay', 'Arjun', 'Archil'}

Union using '|' operator


{'Deepanshu', 'Idrish', 'Jay', 'Raju', 'Archil'}

Intersection operation on Python Sets

This can be done through intersection() or & operator. Common Elements are selected. They
are similar to iteration over the Hash lists and combining the same values on both the Table.
Time Complexity of this is O(min(len(s1), len(s2)) where s1 and s2 are two sets whose union
needs to be done.

# Python program to
# demonstrate intersection
# of two sets
 
set1 = set()
set2 = set()
 
for i in range(5):
    set1.add(i)
 
for i in range(3,9):
    set2.add(i)
 
# Intersection using
# intersection() function
set3 = set1.intersection(set2)
 
print("Intersection using intersection() function")
print(set3)
 
# Intersection using
# "&" operator
set3 = set1 & set2
 
print("\nIntersection using '&' operator")
print(set3)

Output:
Intersection using intersection() function
{3, 4}

Intersection using '&' operator


{3, 4}

Finding Difference of Sets in Python

To find difference in between sets. Similar to find difference in linked list. This is done
through difference() or – operator. Time complexity of finding difference s1 – s2 is
O(len(s1))

# Python program to
# demonstrate difference
# of two sets
 
set1 = set()
set2 = set()
 
for i in range(5):
    set1.add(i)
 
for i in range(3,9):
    set2.add(i)
 
# Difference of two sets
# using difference() function
set3 = set1.difference(set2)
 
print(" Difference of two sets using difference() function")
print(set3)
 
# Difference of two sets
# using '-' operator
set3 = set1 - set2
 
print("\nDifference of two sets using '-' operator")
print(set3)

Output:
Difference of two sets using difference() function
{0, 1, 2}
Difference of two sets using '-' operator
{0, 1, 2}

Clearing Python Sets

Set Clear() method empties the whole set inplace.

# Python program to
# demonstrate clearing
# of set
 
set1 = {1,2,3,4,5,6}
 
print("Initial set")
print(set1)
 
# This method will remove
# all the elements of the set
set1.clear()
 
print("\nSet after using clear() function")
print(set1)

Output:
Initial set
{1, 2, 3, 4, 5, 6}

Set after using clear() function


set()
However, there are two major pitfalls in Python sets: 
1. The set doesn’t maintain elements in any particular order.
2. Only instances of immutable types can be added to a Python set.

Operators for Sets


Sets and frozen sets support the following operators:

Operators Notes

key in s containment check

key not in non-containment check


Operators Notes

s1 == s2 s1 is equivalent to s2

s1 != s2 s1 is not equivalent to s2

s1 <= s2 s1 is subset of s2

s1 < s2 s1 is proper subset of s2

s1 >= s2 s1 is superset of s2

s1 > s2 s1 is proper superset of s2

s1 | s2 the union of s1 and s2

s1 & s2 the intersection of s1 and s2

s1 – s2 the set of elements in s1 but not s2

s1 ˆ s2 the set of elements in precisely one of s1 or s2

Code Snippet to illustrate all Set operations in Python

# Python program to demonstrate working# of


# Set in Python
 
# Creating two sets
set1 = set()
set2 = set()
 
# Adding elements to set1
for i in range(1, 6):
    set1.add(i)
 
# Adding elements to set2
for i in range(3, 8):
    set2.add(i)
 
print("Set1 = ", set1)
print("Set2 = ", set2)
print("\n")
 
# Union of set1 and set2
set3 = set1 | set2# set1.union(set2)
print("Union of Set1 & Set2: Set3 = ", set3)
 
# Intersection of set1 and set2
set4 = set1 & set2# set1.intersection(set2)
print("Intersection of Set1 & Set2: Set4 = ", set4)
print("\n")
 
# Checking relation between set3 and set4
if set3 > set4: # set3.issuperset(set4)
    print("Set3 is superset of Set4")
else if set3 < set4: # set3.issubset(set4)
    print("Set3 is subset of Set4")
else : # set3 == set4
    print("Set3 is same as Set4")
 
# displaying relation between set4 and set3
if set4 < set3: # set4.issubset(set3)
    print("Set4 is subset of Set3")
    print("\n")
 
# difference between set3 and set4
set5 = set3 - set4
print("Elements in Set3 and not in Set4: Set5 = ", set5)
print("\n")
 
# check if set4 and set5 are disjoint sets
if set4.isdisjoint(set5):
    print("Set4 and Set5 have nothing in common\n")
 
# Removing all the values of set5
set5.clear()
 
print("After applying clear on sets Set5: ")
print("Set5 = ", set5)

Output:
('Set1 = ', set([1, 2, 3, 4, 5]))
('Set2 = ', set([3, 4, 5, 6, 7]))
('Union of Set1 & Set2: Set3 = ', set([1, 2, 3, 4, 5, 6, 7]))
('Intersection of Set1 & Set2: Set4 = ', set([3, 4, 5]))

Set3 is superset of Set4


Set4 is subset of Set3

('Elements in Set3 and not in Set4: Set5 = ', set([1, 2, 6, 7]))

Set4 and Set5 have nothing in common

After applying clear on sets Set5:


('Set5 = ', set([]))

Python operators

Operators are the constructs which can manipulate the value of operands.
Consider the expression 4 + 5 = 9. Here, 4 and 5 are called operands and + is called operator.

Types of Operator

Python language supports the following types of operators.


 Arithmetic Operators
 Comparison (Relational) Operators
 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators
Let us have a look on all operators one by one.

Python Arithmetic Operators


Assume variable a holds 10 and variable b holds 20, then −
[ Show Example ]

Operator Description Example

+ Addition Adds values on either side of the operator. a + b = 30

- Subtraction Subtracts right hand operand from left hand operand. a – b = -10

* Multiplication Multiplies values on either side of the operator a * b = 200

/ Division Divides left hand operand by right hand operand b/a=2

% Modulus Divides left hand operand by right hand operand and b%a=0
returns remainder

** Exponent Performs exponential (power) calculation on operators a**b =10 to the


power 20

// Floor Division - The division of operands where the 9//2 = 4 and


result is the quotient in which the digits after the 9.0//2.0 = 4.0, -
decimal point are removed. But if one of the operands is 11//3 = -4, -11.0//3
negative, the result is floored, i.e., rounded away from = -4.0
zero (towards negative infinity) −

Python Comparison Operators

These operators compare the values on either sides of them and decide the relation among
them. They are also called Relational operators.
Assume variable a holds 10 and variable b holds 20, then −
[ Show Example ]

Operator Description Example

== If the values of two operands are equal, then the condition (a == b) is not true.
becomes true.

!= If values of two operands are not equal, then condition (a != b) is true.


becomes true.
<> If values of two operands are not equal, then condition (a <> b) is true.
becomes true. This is similar to !=
operator.

> If the value of left operand is greater than the value of right (a > b) is not true.
operand, then condition becomes true.

< If the value of left operand is less than the value of right (a < b) is true.
operand, then condition becomes true.

>= If the value of left operand is greater than or equal to the value (a >= b) is not true.
of right operand, then condition becomes true.

<= If the value of left operand is less than or equal to the value of (a <= b) is true.
right operand, then condition becomes true.

Python Assignment Operators

Assume variable a holds 10 and variable b holds 20, then −


[ Show Example ]

Operator Description Example

= Assigns values from right side operands to left side c = a + b assigns


operand value of a + b into
c

+= Add AND It adds right operand to the left operand and assign c += a is
the result to left operand equivalent to c = c
+a

-= Subtract AND It subtracts right operand from the left operand and c -= a is equivalent
assign the result to left operand to c = c - a

*= Multiply AND It multiplies right operand with the left operand and c *= a is
assign the result to left operand equivalent to c = c
*a

/= Divide AND It divides left operand with the right operand and c /= a is equivalent
assign the result to left operand to c = c / a
%= Modulus AND It takes modulus using two operands and assign the c %= a is
result to left operand equivalent to c = c
%a

**= Exponent Performs exponential (power) calculation on c **= a is


AND operators and assign value to the left operand equivalent to c = c
** a

//= Floor Division It performs floor division on operators and assign c //= a is
value to the left operand equivalent to c =
c // a

Python Bitwise Operators

Bitwise operator works on bits and performs bit by bit operation. Assume if a = 60; and b =
13; Now in the binary format their values will be 0011 1100 and 0000 1101 respectively.
Following table lists out the bitwise operators supported by Python language with an example
each in those, we use the above two variables (a and b) as operands −
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a  = 1100 0011
There are following Bitwise operators supported by Python language
[ Show Example ]

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in both (a & b) (means 0000
operands 1100)

| Binary OR It copies a bit if it exists in either operand. (a | b) = 61 (means


0011 1101)

^ Binary XOR It copies the bit if it is set in one operand but not (a ^ b) = 49 (means
both. 0011 0001)
~ Binary Ones (~a ) = -61 (means
Complement 1100 0011 in 2's
It is unary and has the effect of 'flipping' bits. complement form due
to a signed binary
number.

<< Binary Left The left operands value is moved left by the number a << 2 = 240 (means
Shift of bits specified by the right operand. 1111 0000)

>> Binary The left operands value is moved right by the a >> 2 = 15 (means
Right Shift number of bits specified by the right operand. 0000 1111)

Python Logical Operators

There are following logical operators supported by Python language. Assume variable a holds
10 and variable b holds 20 then
[ Show Example ]

Operator Description Example

and Logical If both the operands are true then condition becomes true. (a and b)
AND is true.

or Logical OR If any of the two operands are non-zero then condition becomes (a or b)
true. is true.

not Logical NOT Used to reverse the logical state of its operand. Not(a
and b) is
false.

Python Membership Operators

Python’s membership operators test for membership in a sequence, such as strings, lists, or
tuples. There are two membership operators as explained below −
[ Show Example ]

Operator Description Example

in Evaluates to true if it finds a variable in the x in y, here in results in a 1 if x is a


specified sequence and false otherwise. member of sequence y.
not in Evaluates to true if it does not finds a x not in y, here not in results in a 1 if
variable in the specified sequence and false x is not a member of sequence y.
otherwise.

Python Identity Operators

Identity operators compare the memory locations of two objects. There are two Identity
operators explained below −
[ Show Example ]

Operator Description Example

is Evaluates to true if the variables on either side of the x is y, here is results in


operator point to the same object and false otherwise. 1 if id(x) equals id(y).

is not Evaluates to false if the variables on either side of the x is not y, here is
operator point to the same object and true otherwise. not results in 1 if id(x)
is not equal to id(y).

Python Operators Precedence

The following table lists all operators from highest precedence to lowest.
[ Show Example ]

Sr.No. Operator & Description

1 **
Exponentiation (raise to the power)

2 ~+-
Complement, unary plus and minus (method names for the last two are +@ and -@)

3 * / % //
Multiply, divide, modulo and floor division

4 +-
Addition and subtraction

5 >> <<
Right and left bitwise shift

6 &
Bitwise 'AND'

7 ^|
Bitwise exclusive `OR' and regular `OR'

8 <= < > >=


Comparison operators

9 <> == !=
Equality operators

10 = %= /= //= -= += *= **=
Assignment operators

11 is is not
Identity operators

12 in not in
Membership operators

13 not or and
Logical operators

Identity Operators
a=3
b=3
c=4
print a is b # prints True
print a is not b # prints False
print a is not c # prints True

x=1
y=x
z=y
print z is 1 # prints True
print z is x # prints True

str1 = "FreeCodeCamp"
str2 = "FreeCodeCamp"

print str1 is str2 # prints True


print "Code" is str2 # prints False

a = [10,20,30]
b = [10,20,30]

print a is b # prints False (since lists are mutable in Python)

Membership Operators
a = [1,2,3,4,5]

#Is 3 in the list a?


print 3 in a # prints True

#Is 12 not in list a?


print 12 not in a # prints True

str = "Hello World"

#Does the string str contain World?


print "World" in str # prints True

#Does the string str contain world? (note: case sensitive)


print "world" in str # prints False

print "code" not in str # prints True

Unit 2:
Python If ... Else

Python Conditions and If statements

Python supports the usual logical conditions from mathematics:

 Equals: a == b
 Not Equals: a != b
 Less than: a < b
 Less than or equal to: a <= b
 Greater than: a > b
 Greater than or equal to: a >= b

These conditions can be used in several ways, most commonly in "if statements" and loops.

An "if statement" is written by using the if keyword.

If statement:
a = 33
b = 200
if b > a:
print("b is greater than a")

In this example we use two variables, a and b, which are used as part of the if statement to
test whether b is greater than a. As a is 33, and b is 200, we know that 200 is greater than 33,
and so we print to screen that "b is greater than a".

Indentation

Python relies on indentation (whitespace at the beginning of a line) to define scope in the
code. Other programming languages often use curly-brackets for this purpose.

Example

If statement, without indentation (will raise an error):

a = 33
b = 200
if b > a:
print("b is greater than a") # you will get an error

Elif

The elif keyword is Python's way of saying "if the previous conditions were not true, then try
this condition".

Example
a = 33
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
In this example a is equal to b, so the first condition is not true, but the elif condition is true,
so we print to screen that "a and b are equal".

Else

The else keyword catches anything which isn't caught by the preceding conditions.

Example
a = 200
b = 33
if b > a:
  print("b is greater than a")
elif a == b:
  print("a and b are equal")
else:
  print("a is greater than b")

In this example a is greater than b, so the first condition is not true, also the elif condition is
not true, so we go to the else condition and print to screen that "a is greater than b".

You can also have an else without the elif:

a = 200
b = 33
if b > a:
  print("b is greater than a")
else:
  print("b is not greater than a")

Short Hand If

If you have only one statement to execute, you can put it on the same line as the if statement.

Example

One line if statement:

if a > b: print("a is greater than b")

Short Hand If ... Else


If you have only one statement to execute, one for if, and one for else, you can put it all on
the same line:

Example

One line if else statement:

a = 2
b = 330
print("A") if a > b else print("B")

This technique is known as Ternary Operators, or Conditional Expressions.

You can also have multiple else statements on the same line:

Example

One line if else statement, with 3 conditions:

a = 330
b = 330
print("A") if a > b else print("=") if a == b else print("B")

And

The and keyword is a logical operator, and is used to combine conditional statements:

Example

Test if a is greater than b, AND if c is greater than a:

a = 200
b = 33
c = 500
if a > b and c > a:
  print("Both conditions are True")

Or

The or keyword is a logical operator, and is used to combine conditional statements:

Example

Test if a is greater than b, OR if a is greater than c:

a = 200
b = 33
c = 500
if a > b or a > c:
  print("At least one of the conditions is True")

Not

The not keyword is a logical operator, and is used to reverse the result of the conditional
statement:

Example

Test if a is NOT greater than b:

a = 33
b = 200
if not a > b:
  print("a is NOT greater than b")

Nested If

You can have if statements inside if statements, this is called nested if statements.

Example
x = 41

if x > 10:
  print("Above ten,")
  if x > 20:
    print("and also above 20!")
  else:
    print("but not above 20.")

The pass Statement

if statements cannot be empty, but if you for some reason have an if statement with no
content, put in the pass statement to avoid getting an error.

Example
a = 33
b = 200

if b > a:
  pass
break Statement

With the break statement we can stop the loop even if the while condition is true:

Example

Exit the loop when i is 3:

i = 1
while i < 6:
  print(i)
  if i == 3:
    break
  i += 1
1. # Initiating the loop  
2. for string in "Python Loops":  
3.     if string == 'n':  
4.          break  
5.     print('Current Letter: ', string)  

continue Statement

With the continue statement we can stop the current iteration, and continue with the next:

Example

# Python program to show how to use continue loop control  
  
# Initiating the loop  
for string in "While Loops":  
    if string == "o" or string == "i" or string == "e":  
         continue  
    print('Current Letter:', string)

Python has two primitive loop commands:

 while loops
 for loops

The while Loop

With the while loop we can execute a set of statements as long as a condition is true.

Example
Print i as long as i is less than 6:

i = 1
while i < 6:
  print(i)
  i += 1

The while loop requires relevant variables to be ready, in this example we need to define an


indexing variable, i, which we set to 1.

With the else statement we can run a block of code once when the condition no longer is true:

Print a message once the condition is false:

i = 1
while i < 6:
  print(i)
  i += 1
else:
  print("i is no longer less than 6")

For loop:

Generally, a 'for' loop is used to repeat a code N number of times, where N is the number of
items in the sequence or collection. In Python, we can use for loop to iterate over a list,
a tuple, a dictionary, a set, or a string.
Quick Reference

chars = ["a", "b", "c"]

for c in chars:

print(c)

1. Syntax

The syntax to use a for loop is:

for val in sequence:

statement(s)
Here, the variable val represents a value from the sequence, for the current iteration. After
each iteration. the value points to the next available value in the sequence. Once all the values
have been iterated, the for loop terminates.

PlayNext
Unmute
Current Time 0:00
/
Duration 1:45
Loaded: 3.80%
 
Fullscreen
Backward Skip 10sPlay VideoForward Skip 10s

2. Python for Loop Examples

2.1. Looping through a List

Python program to iterate over a list of items using for loop. This program prints all the
names stored in the list.

names = ["alex", "brian", "charles"]

for x in names:

print(x)

2.2. Looping through a String

In Python, strings are iterable. They are a sequence of characters, so we can iterate over the
characters as follows:

name = "alex"

for x in name:

print(x)

2.3. Looping through a Dictionary


A dictionary is a collection data type and we can iterate over its key-value pairs as follows:

colors_dict = {'color': 'blue', 'fruit': 'apple', 'pet': 'dog'}

for key in colors_dict.keys():

print(key)

for item in colors_dict.items():

print(item)

You might also like