Python Notes (Unit-1)
Python Notes (Unit-1)
PYTHON PROGRAMMING
UNIT I:
Identifiers:
Identifier is a name used to identify a variable, function, class, module, etc. The identifier is a
combination of character digits and underscore. The identifier should start with a character or
Underscore then use a digit. The characters are A-Z or a-z, an Underscore(_), and digit (0-9). We
should not use special character (! #, @, $, %,) in identifiers.
It can have a sequence of letters and digits. However, it must begin with a letter or _. The
first letter of an identifier cannot be a digit.
It's a convention to start an identifier with a letter rather _.
Whitespaces are not allowed.
Keywords
1
Python Programming III-CS [Link] [Link].,[Link].,
Keywords are predefined, reserved words used in Python programming that have special meanings
to the compiler.
We cannot use a keyword as a variable name, function name, or any other identifier. They are used
to define the syntax and structure of the Python language.
All the keywords except True, False and None are in lowercase and they must be
Python Keywords
Here is the list of some reserved keywords in Python that cannot be used as identifiers.
False def if raise
None del import return
True elif in try
and else is while
as except lambda with
assert finally nonlocal yield
break for not await
class form or async
continue global pass
Keyword Description
as To create an alias
2
Python Programming III-CS [Link] [Link].,[Link].,
or A logical operator
3
Python Programming III-CS [Link] [Link].,[Link].,
Statement:
A statement is an instruction that the Python interpreter can execute. We have seen two kinds of
statements: print and assignment.
When you type a statement on the command line, Python executes it and displays the result, if there
is one. The result of a print statement is a value. Assignment statements don't produce a result.
A script usually contains a sequence of statements. If there is more than one statement, the results
appear one at a time as the statements execute.
print 1
x=2
print x
1
2
Expression:
An Expression is a sequence or combination of values, variables, operators and function calls that
always produces or returns a result [Link]: x = 5, y = 3, z = x + y
In the above example x, y and z are variables, 5 and 3 are values, = and + are operators.
4
Python Programming III-CS [Link] [Link].,[Link].,
1. Constant Expressions
A constant expression in Python that contains only constant values is known as a constant
expression. In a constant expression in Python, the operator(s) is a constant. A constant is a value
that cannot be changed after its initialization.
Example :
x = 10 + 15
Example :
x = 10
y=5
addition = x + y
subtraction = x - y
product = x * y
division = x / y
power = x**y
5
Python Programming III-CS [Link] [Link].,[Link].,
An integral expression in Python is used for computations and type conversion (integer to float,
a string to integer, etc.). An integral expression always produces an integer value as a resultant.
Example :
x = 10 # an integer number
y = 5.0 # a floating point number
# we need to convert the floating-point number into an integer or vice versa for summation.
result = x + int(y)
A floating expression in Python is used for computations and type conversion (integer to float,
a string to integer, etc.). A floating expression always produces a floating-point number as a
resultant.
Example:
x = 10 # an integer number
y = 5.0 # a floating-point number
# we need to convert the integer number into a floating-point number or vice versa for summation.
result = float(x) + y
A relational operator produces a boolean result so they are also known as Boolean Expressions.
For example :
10 + 15 > 2010+15>20
6
Python Programming III-CS [Link] [Link].,[Link].,
In this example, first, the arithmetic expressions (i.e. 10 + 1510+15 and 2020) are evaluated, and
then the results are used for further comparison.
Example :
a = 25
b = 14
c = 48
d = 45
# The expression checks if the sum of (a and b) is the same as the difference of (c and d).
result = (a + b) == (c - d)
print("Type:", type(result))
print("The result of the expression is: ", result)
Output :
Type: <class 'bool'>
The result of the expression is: False
6. Logical Expressions
As the name suggests, a logical expression performs the logical computation, and the overall
expression results in either True or False (boolean result). We have three types of logical
expressions in Python, let us discuss them briefly.
and xx and yy The expression return True if both xx and yy are true, else it
returns False.
Note :
In the table specified above, xx and yy can be values or another expression as well.
Example :
from operator import and_
x = (10 == 9)
y = (7 > 5)
and_result = x and y
or_result = x or y
not_x = not x
The expression in which the operation or computation is performed at the bit level is known as
a bitwise expression in Python. The bitwise expression contains the bitwise operators.
Example :
x = 25
left_shift = x << 1
right_shift = x >> 1
As the name suggests, a combination expression can contain a single or multiple expressions
which result in an integer or boolean value depending upon the expressions involved.
Example :
x = 25
y = 35
result = x + (y << 1)
Whenever there are multiple expressions involved then the expressions are resolved based on their
precedence or priority. Let us learn about the precedence of various operators in the following
section.
The operator precedence is used to define the operator's priority i.e. which operator will be executed
first. The operator precedence is similar to the BODMAS rule that we learned in mathematics. Refer
to the list specified below for operator precedence.
1. ()[]{} Parenthesis
2. ** Exponentiation
8
Python Programming III-CS [Link] [Link].,[Link].,
8. ^ Bitwise XOR
result_1 = x + y * z
print("Result of 'x + y + z' is: ", result_1)
result_2 = (x + y) * z
print("Result of '(x + y) * z' is: ", result_2)
result_3 = x + (y * z)
print("Result of 'x + (y * z)' is: ", result_3)
Output :
Result of 'x + y + z' is: 236
Result of '(x + y) * z' is: 416
Result of 'z + (y * z)' is: 236
Difference between Statements and Expressions in Python
We have earlier discussed statement expression in Python, let us learn the differences between
them.
A statement in Python is used for The expression in Python produces some value or
creating variables or for displaying result after being interpreted by the Python
values. interpreter.
The execution of a statement changes The expression evaluation does not result in any
9
Python Programming III-CS [Link] [Link].,[Link].,
variables
Python variables are the reserved memory locations used to store values with in a Python Program.
This means that when you create a variable you reserve some space in the memory.
Based on the data type of a variable, Python interpreter allocates memory and decides what can be
stored in the reserved memory. Therefore, by assigning different data types to Python variables, you
can store integers, decimals or characters in these variables.
Python variables do not need explicit declaration to reserve memory space or you can say to create a
variable. A Python variable is created automatically when you assign a value to it. The equal sign
(=) is used to assign values to variables.
The operand to the left of the = operator is the name of the variable and the operand to the right of
the = operator is the value stored in the variable. For example −
counter =100# Creates an integer variable
miles =1000.0# Creates a floating point variable
name ="Zara Ali"# Creates a string variable
Once we create a Python variable and assign a value to it, we can print it using print() function.
Following is the extension of previous example and shows how to print different variables in
Python:
counter =100# Creates an integer variable
miles =1000.0# Creates a floating point variable
name ="Zara Ali"# Creates a string variable
print(counter)
print(miles)
print(name)
Here, 100, 1000.0 and "Zara Ali" are the values assigned to counter, miles, and name variables,
respectively. When running the above Python program, this produces the following result −
100
1000.0
Zara Ali
10
Python Programming III-CS [Link] [Link].,[Link].,
Python Local Variables are defined inside a function. We can not access variable outside the
function.
example to show the usage of local variables:
defsum(x,y):
sum= x + y
returnsum
print(sum(5,10))
Output:
15
Any variable created outside a function can be accessed within any function and so they have global
scope. Following is an example of global variables:
x =5
y =10
defsum():
sum= x + y
returnsum
print(sum())
This will produce the following result:
15
Operators
Python 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: Are the special symbols. Eg- + , * , /, etc.
OPERAND: It is the value on which the operator is applied.
Arithmetic Operators
Comparison (Relational) Operators
11
Python Programming III-CS [Link] [Link].,[Link].,
Assignment Operators
Logical Operators
Bitwise Operators
Membership Operators
Identity Operators
Python arithmetic operators are used to perform mathematical operations on numerical values.
These operations are Addition, Subtraction, Multiplication, Division, Modulus, Expoents and Floor
Division.
+ Addition 10 + 20 = 30
- Subtraction 20 – 10 = 10
* Multiplication 10 * 20 = 200
/ Division 20 / 10 = 2
% Modulus 22 % 10 = 2
** Exponent 4**2 = 16
Example
Following is an example which shows all the above operations:
a =21
b =10
# Addition
print("a + b : ", a + b)
# Subtraction
print("a - b : ", a - b)
# Multiplication
print("a * b : ", a * b)
# Division
12
Python Programming III-CS [Link] [Link].,[Link].,
print("a / b : ", a / b)
# Modulus
print("a % b : ", a % b)
# Exponent
print("a ** b : ", a ** b)
# Floor Division
print("a // b : ", a // b)
This produce the following result −
a + b : 31
a - b : 11
a * b : 210
a / b : 2.1
a%b: 1
a ** b : 16679880978201
a // b : 2
Python comparison operators compare the values on either sides of them and decide the relation
among them. They are also called relational operators. These operators are equal, not equal, greater
than, less than, greater than or equal to and less than or equal to.
Example
Following is an example which shows all the above comparison operations:
a =4
b =5
# Equal
print("a == b : ", a == b)
13
Python Programming III-CS [Link] [Link].,[Link].,
# Not Equal
print("a != b : ", a != b)
# Greater Than
print("a >b : ", a > b)
# Less Than
print("a <b : ", a < b)
Python assignment operators are used to assign values to variables. These operators include simple
assignment operator, addition assign, subtraction assign, multiplication assign, division and assign
operators etc.
= Assignment Operator a = 10
14
Python Programming III-CS [Link] [Link].,[Link].,
Example
Following is an example which shows all the above assignment operations:
# Assignment Operator
a =10
# Addition Assignment
a +=5
print("a += 5 : ", a)
# Subtraction Assignment
a -=5
print("a -= 5 : ", a)
# Multiplication Assignment
a *=5
print("a *= 5 : ", a)
# Division Assignment
a /=5
print("a /= 5 : ",a)
# Remainder Assignment
a %=3
print("a %= 3 : ", a)
# Exponent Assignment
a **=2
print("a **= 2 : ", a)
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 −
15
Python Programming III-CS [Link] [Link].,[Link].,
a = 0011 1100
b = 0000 1101
--------------------------
a&b = 12 (0000 1100)
a|b = 61 (0011 1101)
a^b = 49 (0011 0001)
~a = -61 (1100 0011)
a << 2 = 240 (1111 0000)
a>>2 = 15 (0000 1111)
There are following Bitwise operators supported by Python language
<< Binary Left Shift Shift left by pushing zeros in from the
right and let the leftmost bits fall off
Example
Following is an example which shows all the above bitwise operations:
a =60# 60 = 0011 1100
b =13# 13 = 0000 1101
# Binary AND
c=a&b # 12 = 0000 1100
print("a &b : ", c)
# Binary OR
c=a|b # 61 = 0011 1101
print("a | b : ", c)
16
Python Programming III-CS [Link] [Link].,[Link].,
# Binary XOR
c=a^b # 49 = 0011 0001
print("a ^ b : ", c)
There are following logical operators supported by Python language. Assume variable a holds 10
and variable b holds 20 then
[ Show Example ]
and Logical If both the operands are true then (a and b) is true.
AND condition becomes true.
not Logical NOT Used to reverse the logical state of its Not(a and b) is false.
operand.
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 ]
17
Python Programming III-CS [Link] [Link].,[Link].,
not in Evaluates to true if it does not finds a x not in y, here not in results in a 1
variable in the specified sequence and if x is not a member of sequence y.
false otherwise.
Identity operators compare the memory locations of two objects. There are two Identity operators
explained below −
[ Show Example ]
The following table lists all operators from highest precedence to lowest.
[ Show Example ]
1 **
Exponentiation (raise to the power)
2 ~+-
Complement, unary plus and minus (method names for the last two are +@ and -
@)
18
Python Programming III-CS [Link] [Link].,[Link].,
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
Data types
Data types are the classification or categorization of data items. It represents the kind of value that
tells what operations can be performed on a particular data. Since everything is an object in
19
Python Programming III-CS [Link] [Link].,[Link].,
Python programming, data types are actually classes and variables are instance (object) of these
classes.
Following are the standard or built-in data type of Pytho
Numeric
In Python, numeric data type represent the data which has numeric value. Numeric value can be
integer, floating number or even complex numbers. These values are defined
as int, float and complex class in Python.
Integers – This value is represented by int class. It contains positive or negative whole
numbers (without fraction or decimal). In Python there is no limit to how long an integer value
can be.
Float – This value is represented by float class. It is a real number with floating point
representation. It is specified by a decimal point. Optionally, the character e or E followed by a
positive or negative integer may be appended to specify scientific notation.
Complex Numbers – Complex number is represented by complex class. It is specified as (real
part) + (imaginary part)j. For example – 2+3j
Note – type() function is used to determine the type of data type.
Python3
# Python program to
# demonstrate numeric value
a=5
print("Type of a: ", type(a))
b = 5.0
print("\nType of b: ", type(b))
c = 2 + 4j
print("\nType of c: ", type(c))
Output:
Type of a: <class 'int'>
20
Python Programming III-CS [Link] [Link].,[Link].,
Sequence Type
In Python, sequence is the ordered collection of similar or different data types. Sequences allows
to store multiple values in an organized and efficient fashion. There are several sequence types in
Python –
String
List
Tuple
String
In Python, Strings are arrays of bytes representing Unicode characters. A string is a collection of
one or more characters put in a single quote, double-quote or triple quote. In python there is no
character data type, a character is a string of length one. It is represented by str class.
Creating String
Strings in Python can be created using single quotes or double quotes or even triple quotes.
Python3
# Python Program for
# Creation of String
# Creating a String
# with single Quotes
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)
# Creating a String
# with double Quotes
String1 = "I'm a Geek"
print("\nString with the use of Double Quotes: ")
print(String1)
print(type(String1))
# Creating a String
# with triple Quotes
String1 = '''I'm a Geek and I live in a world of "Geeks"'''
print("\nString with the use of Triple Quotes: ")
print(String1)
print(type(String1))
21
Python Programming III-CS [Link] [Link].,[Link].,
Python3
# Python Program to Access
# characters of String
String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)
22
Python Programming III-CS [Link] [Link].,[Link].,
s
.
List
Lists are just like the arrays, declared in other languages which is a ordered collection of data. It is
very flexible as the items in a list do not need to be of the same type.
Creating List
Lists in Python can be created by just placing the sequence inside the square brackets[].
Python3
# Python program to demonstrate
# Creation of List
# Creating a List
List = []
print("Initial blank List: ")
print(List)
Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]
23
Python Programming III-CS [Link] [Link].,[Link].,
Tuple
Just like list, tuple is also an ordered collection of Python objects. The only difference between
tuple and list is that tuples are immutable i.e. tuples cannot be modified after it is created. It is
represented by tuple class.
Creating Tuple
In Python, tuples are created by placing a sequence of values separated by „comma‟ with or
without the use of parentheses for grouping of the data sequence. Tuples can contain any number
of elements and of any datatype (like strings, integers, list, etc.).
Note: Tuples can also be created with a single element, but it is a bit tricky. Having one element
in the parentheses is not sufficient, there must be a trailing „comma‟ to make it a tuple.
Python3
24
Python Programming III-CS [Link] [Link].,[Link].,
# Creating a Tuple
# with nested tuples
Tuple1 = (0, 1, 2, 3)
Tuple2 = ('python', 'geek')
Tuple3 = (Tuple1, Tuple2)
print("\nTuple with nested tuples: ")
print(Tuple3)
Output:
Initial empty Tuple:
()
Note – Creation of Python tuple without the use of parentheses is known as Tuple Packing.
25
Python Programming III-CS [Link] [Link].,[Link].,
print(type(True))
print(type(False))
print(type(true))
Output:
<class 'bool'>
<class 'bool'>
Traceback (most recent call last):
26
Python Programming III-CS [Link] [Link].,[Link].,
# Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)
27
Python Programming III-CS [Link] [Link].,[Link].,
# Creating a set
set1 = set(["Geeks", "For", "Geeks"])
print("\nInitial set")
print(set1)
Elements of set:
Geeks For
True
28
Python Programming III-CS [Link] [Link].,[Link].,
Dict = {}
print("Empty Dictionary: ")
print(Dict)
# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
# Creating a Dictionary
# with Mixed keys
Dict = {'Name': 'Geeks', 1: [1, 2, 3, 4]}
print("\nDictionary with the use of Mixed Keys: ")
print(Dict)
# Creating a Dictionary
# with dict() method
Dict = dict({1: 'Geeks', 2: 'For', 3:'Geeks'})
print("\nDictionary with the use of dict(): ")
print(Dict)
# Creating a Dictionary
# with each item as a Pair
Dict = dict([(1, 'Geeks'), (2, 'For')])
print("\nDictionary with each item as a pair: ")
print(Dict)
Output:
Empty Dictionary:
{}
29
Python Programming III-CS [Link] [Link].,[Link].,
# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}
Output:
<class 'int'>
Example 2: Performing arithmetic Operations on int type
a=5
b=6
# Addition
c=a+b
print("Addition:",c)
30
Python Programming III-CS [Link] [Link].,[Link].,
d=9
e=6
# Subtraction
f=d-e
print("Subtraction:",f)
g=8
h=2
# Division
i = g // h
print("Division:",i)
j=3
k=5
# Multiplication
l=j*k
print("Multiplication:",l)
m = 25
n=5
# Modulus
o=m%n
print("Modulus:",o)
p=6
q=2
# Exponent
r = p ** q
print("Exponent:",r)
Output:
Addition: 11
Subtraction: 3
Division: 4
Multiplication: 15
Modulus: 0
Exponent: 36
Float type
This is a real number with floating-point representation. It is specified by a decimal point.
Optionally, the character e or E followed by a positive or negative integer may be appended to
specify scientific notation. . Some examples of numbers that are represented as floats are 0.5 and -
7.823457.
They can be created directly by entering a number with a decimal point, or by using operations
such as division on integers. Extra zeros present at the number‟s end are ignored automatically.
31
Python Programming III-CS [Link] [Link].,[Link].,
num = 6 * 7.0
print(type(num))
Output:
<class 'float'>
Example 2: Performing arithmetic Operations on float type
Python3
a = 5.5
b = 3.2
# Addition
c=a+b
print("Addition:", c)
# Subtraction
c = a-b
print("Subtraction:", c)
# Division
c = a/b
print("Division:", c)
# Multiplication
c = a*b
print("Multiplication:", c)
Output
Addition: 8.7
Subtraction: 2.3
Division: 1.71875
Multiplication: 17.6
Note: The accuracy of a floating-point number is only up to 15 decimal places, the 16th place can
be inaccurate.
Complex type
A complex number is a number that consists of the real and imaginary parts. For example, 2 + 3j
is a complex number where 2 is the real component, and 3 multiplied by j is an imaginary part.
Example 1: Creating Complex and checking type
32
Python Programming III-CS [Link] [Link].,[Link].,
Python3
num = 6 + 9j
print(type(num))
Output:
<class 'complex'>
Example 2: Performing arithmetic operations on complex type
a = 1 + 5j
b = 2 + 3j
# Addition
c=a+b
print("Addition:",c)
d = 1 + 5j
e = 2 - 3j
# Subtraction
f=d-e
print("Subtraction:",f)
g = 1 + 5j
h = 2 + 3j
# Division
i=g/h
print("Division:",i)
j = 1 + 5j
k = 2 + 3j
# Multiplication
l=j*k
print("Multiplication:",l)
Output:
Addition: (3+8j)
Subtraction: (-1+8j)
Division: (1.307692307692308+0.5384615384615384j)
Multiplication: (-13+13j)
Type Conversion between numbers
We can convert one number into the other form by two methods:
Using Arithmetic Operations: We can use operations like addition, subtraction to change the
type of number implicitly(automatically), if one of the operands is float. This method is not
working for complex numbers.
Example: Type conversion using arithmetic operations
a = 1.6
33
Python Programming III-CS [Link] [Link].,[Link].,
b=5
c=a+b
print(c)
Output:
6.6
Using built-in functions: We can also use built-in functions like int(), float() and complex() to
convert into different types explicitly.
Example: Type conversion using built-in functions
Python3
a=2
print(float(a))
b = 5.6
print(int(b))
c = '3'
print(type(int(c)))
d = '5.6'
print(type(float(c)))
e=5
print(complex(e))
f = 6.5
print(complex(f))
Output:
2.0
5
<class 'int'>
<class 'float'>
(5+0j)
(6.5+0j)
When we convert float to int, the decimal part is truncated.
Note:
1. We can‟t convert a complex data type number into int data type and float data type numbers.
2. We can‟t apply complex built-in functions on strings.
Decimal Numbers in Python
Arithmetic operations on the floating number can give some unexpected results. Let‟s consider a
case where we want to add 1.1 to 2.2. You all must be wondering that the result of this operation
should be 3.3 but let‟s see the output given by Python.
Example:
a = 1.1
b = 2.2
34
Python Programming III-CS [Link] [Link].,[Link].,
c = a+b
print(c)
Output:
3.3000000000000003
You can the result is unexpected. Let‟s consider another case where we will subtract 1.2 and 1.0.
Again we will expect the result as 0.2, but let‟s see the output given by Python.
Example:
Python3
a = 1.2
b = 1.0
c = a-b
print(c)
Output:
0.19999999999999996
Example:
Python3
import decimal
a = [Link]('1.1')
b = [Link]('2.2')
c = a+b
print(c)
Output
3.3
Random Numbers in Python
Python provides a random module to generate pseudo-random numbers. This module can create
random numbers, select a random element from a sequence in Python, etc.
Example 1: Creating random value
Python3
import random
print([Link]())
Output
0.9867200671824407
Example 2: Selecting random element from string or list
Python3
import random
s = 'geeksforgeeks'
35
Python Programming III-CS [Link] [Link].,[Link].,
L = [1, 2 ,3, 5, 6, 7, 7, 8, 0]
print([Link](s))
print([Link](L))
Output
f
0
Note: For more information about random numbers, refer to our Random Number tutorial
Python Mathematics
The math module of Python helps to carry different mathematical operations trigonometry,
statistics, probability, logarithms, etc.
Example:
Python3
# importing "math" for mathematical operations
import math
a = 3.5
36
Python Programming III-CS [Link] [Link].,[Link].,
Boolean
Python boolean type is one of the built-in data types provided by Python, which represents one of
the two values i.e. True or False. Generally, it is used to represent the truth values of the
expressions. For example, 1==1 is True whereas 2<1 is False.
Python Boolean Type
The boolean value can be of two types only i.e. either True or False. The output <class
‘bool’> indicates the variable is a boolean data type.
Example: Boolean type
Python3
a = True
type(a)
b = False
type(b)
Output:
<class 'bool'>
<class 'bool'>
Evaluate Variables and Expressions
We can evaluate values and variables using the Python bool() function. This method is used to
return or convert a value to a Boolean value i.e., True or False, using the standard truth testing
procedure.
Syntax:
bool([x])
Example: Python bool() method
Python3
# Python program to illustrate
# built-in method bool()
# Returns False as x is 0
37
Python Programming III-CS [Link] [Link].,[Link].,
x = 0.0
print(bool(x))
# Comparing variables
print(a == b)
Output:
False
Integers and Floats as Booleans
Numbers can be used as bool values by using Python‟s built-in bool() method. Any integer,
floating-point number, or complex number having zero as a value is considered as False, while if
they are having value as any positive or negative number then it is considered as True.
Python3
var1 = 0
print(bool(var1))
var2 = 1
print(bool(var2))
var3 = -9.7
print(bool(var3))
Output:
False
True
True
Boolean Operators
38
Python Programming III-CS [Link] [Link].,[Link].,
Boolean Operations are simple arithmetic of True and False values. These values can be
manipulated by the use of boolean operators which include AND, Or, and NOT. Common
boolean operations are –
or
and
not
== (equivalent)
!= (not equivalent)
Boolean OR Operator
The Boolean or operator returns True if any one of the inputs is True else returns False.
A B A or B
a=1
b=2
c=4
if a > b or b < c:
print(True)
else:
print(False)
if a or b or c:
print("Atleast one number has boolean value as True")
Output
True
Atleast one number has boolean value as True
In the above example, we have used Python boolean with if statement and OR operator that check
if a is greater than b or b is smaller than c and it returns True if any of the condition is True (b<c
in the above example).
The Boolean and operator returns False if any one of the inputs is False else returns True.
39
Python Programming III-CS [Link] [Link].,[Link].,
A B A and B
Python3
# Python program to demonstrate
# and operator
a=0
b=2
c=4
if a and b and c:
print("All the numbers has boolean value as True")
else:
print("Atleast one number has boolean value as False")
Output
False
Atleast one number has boolean value as False
The Boolean Not operator only require one argument and returns the negation of the argument i.e.
returns the True for False and False for True.
A Not A
True False
False True
40
Python Programming III-CS [Link] [Link].,[Link].,
Python3
# Python program to demonstrate
# not operator
a=0
if not a:
print("Boolean value of a is False")
Output
Boolean value of a is False
Boolean == (equivalent) and != (not equivalent) Operator
Both the operators are used to compared two results. == (equivalent operator returns True if two
results are equal and != (not equivalent operator returns True if the two results are not same.
Python3
# Python program to demonstrate
# equivalent an not equivalent
# operator
a=0
b=1
if a == 0:
print(True)
if a == b:
print(True)
if a != b:
print(True)
Output
True
True
is Operator
The is keyword is used to test whether two variables belong to the same object. The test will
return True if the two objects are the same else it will return False even if the two objects are
100% equal.
Example: Python is Operator
Python3
# Python program to demonstrate
41
Python Programming III-CS [Link] [Link].,[Link].,
# is keyword
x = 10
y = 10
if x is y:
print(True)
else:
print(False)
print(x is y)
Output
True
False
in Operator
in operator checks for the membership i.e. checks if the value is present in a list, tuple, range,
string, etc.
Example: in Operator
Python3
# Python program to demonstrate
# in keyword
# Create a list
animals = ["dog", "lion", "cat"]
Python Indentation
42
Python Programming III-CS [Link] [Link].,[Link].,
Python indentation refers to adding white space before a statement to a particular block of code. In
another word, all the statements with the same space to the right, belong to the same code block.
Python3
# Python program showing
# indentation
site = 'gfg'
if site == 'gfg':
print('Logging on to geeksforgeeks...')
else:
print('retype the URL.')
print('All set !')
Output:
Logging on to geeksforgeeks...
All set !
Python Comments
Comments in Python are the lines in the code that are ignored by the interpreter during the
execution of the program. Comments enhance the readability of the code and help the
43
Python Programming III-CS [Link] [Link].,[Link].,
programmers to understand the code very carefully. There are three types of comments in Python
–
Single line Comments
Multiline Comments
Docstring Comments
Example: Comments in Python
Python3
# Python program to demonstrate comments
# sample comment
name = "geeksforgeeks"
print(name)
Output:
geeksforgeeks
In the above example, it can be seen that comments are ignored by the interpreter during the
execution of the program.
Comments are generally used for the following purposes:
Code Readability
Explanation of the code or Metadata of the project
Prevent execution of code
To include resources
Types of Comments in Python
There are three main kinds of comments in Python. They are:
Single-Line Comments
Python single-line comment starts with the hashtag symbol (#) with no white spaces and lasts till
the end of the line. If the comment exceeds one line then put a hashtag on the next line and
continue the comment. Python‟s single-line comments are proved useful for supplying short
explanations for variables, function declarations, and expressions. See the following code snippet
demonstrating single line comment:
Example:
Python3
Output
GeeksforGeeks
Multi-Line Comments
Python does not provide the option for multiline comments. However, there are different ways
through which we can write multiline comments.
44
Python Programming III-CS [Link] [Link].,[Link].,
We can multiple hashtags (#) to write multiline comments in Python. Each and every line will be
considered as a single-line comment.
Example: Multiline comments using multiple hashtags (#)
Python3
Output
Multiline comments
Using String Literals
Python ignores the string literals that are not assigned to a variable so we can use these string
literals as a comment.
Example 1:
Python3
On executing the above code we can see that there will not be any output so we use the strings
with triple quotes(“””) as multiline comments.
Python3
multiline comments"""
print("Multiline comments")
Output
Multiline comments
Python Docstring
Python docstring is the string literals with triple quotes that are appeared right after the
function. It is used to associate documentation that has been written with Python modules,
45
Python Programming III-CS [Link] [Link].,[Link].,
functions, classes, and methods. It is added right below the functions, modules, or classes to
describe what they do. In Python, the docstring is then made available via the __doc__ attribute.
Example:
Python3
def multiply(a, b):
"""Multiplies the value of a and b"""
return a*b
print("x is of type:",type(x))
y = 10.6
print("y is of type:",type(y))
z=x+y
print(z)
print("z is of type:",type(z))
Output:
x is of type: <class 'int'>
y is of type: <class 'float'>
20.6
z is of type: <class 'float'>
46
Python Programming III-CS [Link] [Link].,[Link].,
As we can see the data type of „z‟ got automatically changed to the “float” type while one variable
x is of integer type while the other variable y is of float type. The reason for the float value not
being converted into an integer instead is due to type promotion that allows performing operations
by converting data into a wider-sized data type without any loss of information. This is a simple
case of Implicit type conversion in python.
Explicit Type Conversion
In Explicit Type Conversion in Python, the data type is manually changed by the user as per their
requirement. With explicit type conversion, there is a risk of data loss since we are forcing an
expression to be changed in some specific data type. Various forms of explicit type conversion
are explained below:
1. int(a, base): This function converts any data type to integer. „Base‟ specifies the base in
which string is if the data type is a string.
2. float(): This function is used to convert any data type to a floating-point number.
Python3
Output:
After converting to integer base 2 : 18
After converting to float : 10010.0
3. ord() : This function is used to convert a character to integer.
4. hex() : This function is to convert integer to hexadecimal string.
5. oct() : This function is to convert integer to octal string.
Python3
47
Python Programming III-CS [Link] [Link].,[Link].,
# initializing integer
s = '4'
c = ord(s)
print (c)
c = hex(56)
print (c)
c = oct(56)
print (c)
Output:
After converting character to integer : 52
After converting 56 to hexadecimal string : 0x38
After converting 56 to octal string : 0o70
6. tuple() : This function is used to convert to a tuple.
7. set() : This function returns the type after converting to set.
8. list() : This function is used to convert any data type to a list type.
Python3
# initializing string
s = 'geeks'
48
Python Programming III-CS [Link] [Link].,[Link].,
c = tuple(s)
print (c)
c = set(s)
print (c)
c = list(s)
print (c)
Output:
After converting string to tuple : ('g', 'e', 'e', 'k', 's')
After converting string to set : {'k', 'e', 's', 'g'}
After converting string to list : ['g', 'e', 'e', 'k', 's']
9. dict() : This function is used to convert a tuple of order (key,value) into a dictionary.
10. str() : Used to convert integer into a string.
11. complex(real,imag) : This function converts real numbers to complex(real,imag) number.
Python3
# initializing integers
a=1
b=2
# initializing tuple
49
Python Programming III-CS [Link] [Link].,[Link].,
c = complex(1,2)
print (c)
c = str(a)
print (c)
c = dict(tup)
print (c)
Output:
After converting integer to complex number : (1+2j)
After converting integer to string : 1
After converting tuple to dictionary : {'a': 1, 'f': 2, 'g': 3}
12. chr(number): This function converts number to its corresponding ASCII character.
Python3
a = chr(76)
b = chr(77
print(a)
print(b)
Output:
M
Identity operators or Is Operator
In Python, is and is not are used to check if two values are located on the same part of the memory.
Two variables that are equal does not imply that they are identical.
50
Python Programming III-CS [Link] [Link].,[Link].,
is True if the operands are identical (refer to the same object) x is True
True if the operands are not identical (do not refer to the same x is not
is not
object) True
Here, we see that x1 and y1 are integers of the same values, so they are equal as well as identical.
Same is the case with x2 and y2 (strings).
But x3 and y3 are lists. They are equal but not identical. It is because the interpreter locates them
separately in memory although they are equal.
Dynamic Typing in Python
python being a dynamically typed language it stores the value at some location and then combines
the respective variable name with a container
1. a = 12.0
2. print(type(a))
3. b = 24
4. print(type(b))
5. c = 'data'
6. print(type(c))
7. print (a * 3)
51
Python Programming III-CS [Link] [Link].,[Link].,
8. print (b * 3)
9. print (c * 3)
Output:
<class 'float'>
<class 'int'>
<class 'str'>
36.0
72
datadatadata
Explanation:
1. In the first step, we have initialized the variables a, b, and c with different types.
2. After this, we have checked their type that comes out to be float, integer, and string
respectively.
3. In the next step, three of them are multiplied by three.
4. Since the data type is known at the run time, the operations are performed based on the type.
5. We can observe that the first value in the output is a float value, the next value is an integer,
and a string is multiplied three times.
6. On executing the program, the expected output is displayed.
1. a = 12.0
2. print (type(a))
3. a = 24
4. print(type(a))
5. a = 'data'
6. print (type(a))
7. a = 2+3j
8. print (type(a))
Output:
52
Python Programming III-CS [Link] [Link].,[Link].,
<class 'float'>
<class 'int'>
<class 'str'>
<class 'complex'>
Explanation:
1. We have initialized the variable 'a' with values of different data types.
2. After this, we have checked the type of 'a' in each case.
3. From this, we can infer that-
i. In the first case, a is a reference to a float object.
ii. In the second case, a is a reference to an integer object.
iii. In the third case, a is a reference to a string object.
iv. In the fourth case, a is a reference to a complex object.
Shared References
1. a = 12.0
2. b=a
3. print(a)
4. print(b)
Output:
12.0
12.0
Explanation:
This is nothing but the concept of shared references which says that "Two variables can have the
same reference."
1. a = 12.0
2. b = a
3. a = a * 7
53
Python Programming III-CS [Link] [Link].,[Link].,
4. print(a)
5. print(b)
Output:
84.0
12.0
Explanation:
1. We have initialized the value of a as 12.0, b as a, and then again assigned 'a' with a * 7
2. After this, we have printed the values of both a and b that come out to be 84.0 for a but 12.0
in the case of b because it is still referencing the first value of a.
The feature that makes a language like Java more convenient is that it is statically typed and so the
bugs and the errors are reported at compile-time instead of run-time.
Therefore, it's a major concern for the python developers that the errors are shown during the run-
time and therefore they have to develop strategies to rectify them.
54