0% found this document useful (0 votes)
5 views54 pages

Python Notes (Unit-1)

The document provides an overview of Python programming concepts, including identifiers, keywords, statements, and expressions. It explains the rules for naming identifiers, lists reserved keywords, and differentiates between statements and expressions with examples. Additionally, it covers variable creation, types, and the importance of operator precedence in expressions.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views54 pages

Python Notes (Unit-1)

The document provides an overview of Python programming concepts, including identifiers, keywords, statements, and expressions. It explains the rules for naming identifiers, lists reserved keywords, and differentiates between statements and expressions with examples. Additionally, it covers variable creation, types, and the importance of operator precedence in expressions.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Python Programming III-CS [Link] [Link].,[Link].

PYTHON PROGRAMMING

UNIT I:

Identifiers – Keywords - Statements and Expressions – Variables – Operators – Arithmetic


operators – Assignment operators – Comparison operators – Logical operators – Bitwise operators -
Precedence and Associativity – Data types - Number – Booleans – Strings - Indentation –
Comments – Single line comment – Multiline comments - Reading Input – Print Output – Type
Conversions – int function – float function – str() function – chr() function – complex() function –
ord() function – hex() function – oct() function - type() function and Is operator – Dynamic and
Strongly typed language.

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.

Rules for Naming an Identifier

 Identifiers cannot be a keyword.

 Identifiers are case-sensitive.

 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.

 We cannot use special symbols like !, @, #, $, and so on.

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

and A logical operator

as To create an alias

assert For debugging

break To break out of a loop

class To define a class

continue To continue to the next iteration of a loop

def To define a function

del To delete an object

elif Used in conditional statements, same as else if

else Used in conditional statements

2
Python Programming III-CS [Link] [Link].,[Link].,

except Used with exceptions, what to do when an exception occurs

False Boolean value, result of comparison operations

finally Used with exceptions, a block of code that will be executed no


matter if there is an exception or not

for To create a for loop

from To import specific parts of a module

global To declare a global variable

if To make a conditional statement

import To import a module

in To check if a value is present in a list, tuple, etc.

is To test if two variables are equal

lambda To create an anonymous function

None Represents a null value

nonlocal To declare a non-local variable

not A logical operator

or A logical operator

pass A null statement, a statement that will do nothing

raise To raise an exception

return To exit a function and return a value

3
Python Programming III-CS [Link] [Link].,[Link].,

True Boolean value, result of comparison operations

try To make a try...except statement

while To create a while loop

with Used to simplify exception handling

yield To end a function, returns a generator

Statements and Expressions

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.

For example, the script

print 1
x=2
print x

produces the output

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.

So, the first combination x = 5 is an expression, the second combination y = 3 is an another


expression and at last, z = x + y is also an expression.

– An Expression always evaluates (calculate) to itself.

4
Python Programming III-CS [Link] [Link].,[Link].,

Types of Expression in Python

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

# Here both 10 and 15 are constants but x is a variable.


print("The value of x is: ", x)
Output :
The value of x is: 25
2. Arithmetic Expressions

An expression in Python that contains a combination of operators, operands, and sometimes


parenthesis is known as an arithmetic expression. The result of an arithmetic expression is also a
numeric value just like the constant expression discussed above. Before getting into the example of
an arithmetic expression in Python, let us first know about the various operators used in the
arithmetic expressions.

Operator Syntax Working

+ x+y Addition or summation of x and y.

- x-y Subtraction of y from x.

x xxy Multiplication or product of x and y.

/ x/y Division of x and y.

// x // y Quotient when x is divided by y.

% x%y Remainder when x is divided by y.

** x ** y Exponent (x to the power of y).

Example :
x = 10
y=5

addition = x + y
subtraction = x - y
product = x * y
division = x / y
power = x**y

print("The sum of x and y is: ", addition)


print("The difference between x and y is: ", subtraction)
print("The product of x and y is: ", product)

5
Python Programming III-CS [Link] [Link].,[Link].,

print("The division of x and y is: ", division)


print("x to the power y is: ", power)
Output :
The sum of x and y is: 15
The difference between x and y is: 5
The product of x and y is: 50
The division of x and y is: 2.0
x to the power y is: 100000
3. Integral Expressions

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)

print("The sum of x and y is: ", result)


Output :
The sum of x and y is: 15
4. Floating Expressions

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

print("The sum of x and y is: ", result)


Output :
The sum of x and y is: 15.0
5. Relational Expressions

A relational expression in Python can be considered as a combination of two or more arithmetic


expressions joined using relational operators. The overall expression results in
either True or False (boolean result). We have four types of relational operators in Python (i.e. > ,< ,
>= , <=)(i.e.>,<,>=,<=).

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.

Operator Syntax Working

and xx and yy The expression return True if both xx and yy are true, else it
returns False.

or xx or yy The expression return True if at least one of xx or yy is True.

not not xx The expression returns True if the condition of xx is 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

print("The result of x and y is: ", and_result)


print("The result of x or y is: ", or_result)
print("The not of x is: ", not_x)
Output :
The result of x and y is: False
7
Python Programming III-CS [Link] [Link].,[Link].,

The result of x or y is: True


The not of x is: True
7. Bitwise Expressions

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

print("One right shift of x results: ", right_shift)


print("One left shift of x results: ", left_shift)
Output :
One right shift of x results: 12
One left shift of x results: 50
8. Combinational Expressions

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)

print("Result obtained : ", result)


Output :
Result obtained: 95

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.

Multiple Operators in Expression (Operator Precedence) ?

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.

Precedence Operator Name

1. ()[]{} Parenthesis

2. ** Exponentiation

3. -value , +value , ~value Unary plus or minus, complement

4. / * // % Multiply, Divide, Modulo

8
Python Programming III-CS [Link] [Link].,[Link].,

5. +– Addition & Subtraction

6. >><< Shift Operators

7. & Bitwise AND

8. ^ Bitwise XOR

9. pipe symbol Bitwise OR

10. >= <= >< Comparison Operators

11. == != Equality Operators

12. = += -= /= *= Assignment Operators

13. is, is not, in, not in Identity and membership operators

14. and, or, not Logical Operators

Let us take an example to understand the precedence better :


x = 12
y = 14
z = 16

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.

Statement in Python Expression in Python

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.

A statement in Python is not An expression in Python is evaluated for some


evaluated for some results. results.

The execution of a statement changes The expression evaluation does not result in any

9
Python Programming III-CS [Link] [Link].,[Link].,

the state of the variable. state change.

A statement can be an expression. An expression is not a statement.

Example : x = 3x=3. Example: x = 3 + 6x=3+6.


Output : 33 Output : 99

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.

Creating Python 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

Printing Python Variables

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

Variable Types in Python

10
Python Programming III-CS [Link] [Link].,[Link].,

1. Local Variable in Python


2. Global Variable in Python

Python Local Variable

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

Python Global Variable

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.

Types of Python Operators

Python language supports the following types of operators.

 Arithmetic Operators
 Comparison (Relational) Operators

11
Python Programming III-CS [Link] [Link].,[Link].,

 Assignment Operators
 Logical Operators
 Bitwise Operators
 Membership Operators
 Identity Operators

Let us have a quick look on all these operators one by one.

Python Arithmetic 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.

Operator Name Example

+ Addition 10 + 20 = 30

- Subtraction 20 – 10 = 10

* Multiplication 10 * 20 = 200

/ Division 20 / 10 = 2

% Modulus 22 % 10 = 2

** Exponent 4**2 = 16

// Floor Division 9//2 = 4

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

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.

Operator Name Example

== Equal 4 == 5 is not true.

!= Not Equal 4 != 5 is true.

> Greater Than 4 > 5 is not true.

< Less Than 4 < 5 is true.

>= Greater than or Equal to 4 >= 5 is not true.

<= Less than or Equal to 4 <= 5 is true.

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)

# Greater Than or Equal to


print("a >= b : ", a >= b)

# Less Than or Equal to


print("a <= b : ", a <= b)
This produce the following result −
a == b : False
a != b : True
a >b : False
a <b : True
a >= b : False
a <= b : True

Python Assignment Operators

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.

Operator Name Example

= Assignment Operator a = 10

+= Addition Assignment a += 5 (Same as a = a + 5)

-= Subtraction Assignment a -= 5 (Same as a = a - 5)

*= Multiplication Assignment a *= 5 (Same as a = a * 5)

/= Division Assignment a /= 5 (Same as a = a / 5)

%= Remainder Assignment a %= 5 (Same as a = a % 5)

**= Exponent Assignment a **= 2 (Same as a = a ** 2)

14
Python Programming III-CS [Link] [Link].,[Link].,

//= Floor Division Assignment a //= 3 (Same as a = a // 3)

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)

# Floor Division Assignment


a //=3
print("a //= 3 : ", a)
This produce the following result −
a += 5 : 105
a -= 5 : 100
a *= 5 : 500
a /= 5 : 100.0
a %= 3 : 1.0
a **= 2 : 1.0
a //= 3 : 0.0

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 −

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

Operator Name Example

& Binary AND Sets each bit to 1 if both bits are 1

| Binary OR Sets each bit to 1 if one of two bits is 1

^ Binary XOR Sets each bit to 1 if only one of two bits is


1

~ Binary Ones Complement Inverts all the bits

<< Binary Left Shift Shift left by pushing zeros in from the
right and let the leftmost bits fall off

>> Binary Right Shift Shift right by pushing copies of the


leftmost bit in from the left, and let the
rightmost 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)

# Binary Ones Complement


c =~a;# -61 = 1100 0011
print("~a : ", c)

# Binary Left Shift


c = a <<2;# 240 = 1111 0000
print("a <<2 : ", c)

# Binary Right Shift


c = a >>2;# 15 = 0000 1111
print("a >>2 : ", c)
This produce the following result −
a &b : 12
a | b : 61
a ^ b : 49
~a : -61
a >>2 : 240
a >>2 : 15

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 (a and b) is true.
AND condition becomes true.

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


then condition becomes true.

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

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 ]

17
Python Programming III-CS [Link] [Link].,[Link].,

Operator Description Example

in Evaluates to true if it finds a variable in


x in y, here in results in a 1 if x is a
the specified sequence and false
member of sequence y.
otherwise.

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.

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


x is y, here is results in 1
the operator point to the same object and false
if id(x) equals id(y).
otherwise.

is not Evaluates to false if the variables on either side x is not y, here is


of the operator point to the same object and true not results in 1 if id(x) is
otherwise. not equal to id(y).

Python Operators Precedence

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

[Link]. Operator & Description

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'>

Type of b: <class 'float'>

Type of c: <class 'complex'>

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))

# Creating String with triple


# Quotes allows multiple lines
String1 = '''Geeks
For
Life'''
print("\nCreating a multiline String: ")
print(String1)
Output:
String with the use of Single Quotes:
Welcome to the Geeks World

21
Python Programming III-CS [Link] [Link].,[Link].,

String with the use of Double Quotes:


I'm a Geek
<class 'str'>

String with the use of Triple Quotes:


I'm a Geek and I live in a world of "Geeks"
<class 'str'>

Creating a multiline String:


Geeks
For
Life

Accessing elements of String


In Python, individual characters of a String can be accessed by using the method of Indexing.
Indexing allows negative address references to access characters from the back of the String, e.g. -
1 refers to the last character, -2 refers to the second last character and so on.

Python3
# Python Program to Access
# characters of String

String1 = "GeeksForGeeks"
print("Initial String: ")
print(String1)

# Printing First character


print("\nFirst character of String is: ")
print(String1[0])

# Printing Last character


print("\nLast character of String is: ")
print(String1[-1])
Output:
Initial String:
GeeksForGeeks

First character of String is:


G

Last character of String is:

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)

# Creating a List with


# the use of a String
List = ['GeeksForGeeks']
print("\nList with the use of String: ")
print(List)

# Creating a List with


# the use of multiple values
List = ["Geeks", "For", "Geeks"]
print("\nList containing multiple values: ")
print(List[0])
print(List[2])

# Creating a Multi-Dimensional List


# (By Nesting a list inside a List)
List = [['Geeks', 'For'], ['Geeks']]
print("\nMulti-Dimensional List: ")
print(List)
Output:
Initial blank List:
[]

List with the use of String:


['GeeksForGeeks']

List containing multiple values:


Geeks
Geeks

Multi-Dimensional List:
[['Geeks', 'For'], ['Geeks']]

23
Python Programming III-CS [Link] [Link].,[Link].,

Accessing elements of List


In order to access the list items refer to the index number. Use the index operator [ ] to access an
item in a list. In Python, negative sequence indexes represent positions from the end of the array.
Instead of having to compute the offset as in List[len(List)-3], it is enough to just write List[-3].
Negative indexing means beginning from the end, -1 refers to the last item, -2 refers to the
second-last item, etc.
Python3
# Python program to demonstrate
# accessing of element from list

# Creating a List with


# the use of multiple values
List = ["Geeks", "For", "Geeks"]

# accessing a element from the


# list using index number
print("Accessing element from the list")
print(List[0])
print(List[2])

# accessing a element using


# negative indexing
print("Accessing element using negative indexing")

# print the last element of list


print(List[-1])

# print the third last element of list


print(List[-3])
Output:
Accessing element from the list
Geeks
Geeks
Accessing element using negative indexing
Geeks
Geeks

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].,

# Python program to demonstrate


# creation of Set

# Creating an empty tuple


Tuple1 = ()
print("Initial empty Tuple: ")
print (Tuple1)

# Creating a Tuple with


# the use of Strings
Tuple1 = ('Geeks', 'For')
print("\nTuple with the use of String: ")
print(Tuple1)

# Creating a Tuple with


# the use of list
list1 = [1, 2, 4, 5, 6]
print("\nTuple using List: ")
print(tuple(list1))

# Creating a Tuple with the


# use of built-in function
Tuple1 = tuple('Geeks')
print("\nTuple with the use of function: ")
print(Tuple1)

# 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:
()

Tuple with the use of String:


('Geeks', 'For')

Tuple using List:


(1, 2, 4, 5, 6)

Tuple with the use of function:


('G', 'e', 'e', 'k', 's')

Tuple with nested tuples:


((0, 1, 2, 3), ('python', 'geek'))

Note – Creation of Python tuple without the use of parentheses is known as Tuple Packing.
25
Python Programming III-CS [Link] [Link].,[Link].,

Accessing elements of Tuple


In order to access the tuple items refer to the index number. Use the index operator [ ] to access an
item in a tuple. The index must be an integer. Nested tuples are accessed using nested indexing.
Python3
# Python program to
# demonstrate accessing tuple

tuple1 = tuple([1, 2, 3, 4, 5])

# Accessing element using indexing


print("First element of tuple")
print(tuple1[0])

# Accessing element from last


# negative indexing
print("\nLast element of tuple")
print(tuple1[-1])

print("\nThird last element of tuple")


print(tuple1[-3])
Output:
First element of tuple
1

Last element of tuple


5

Third last element of tuple


3
Boolean
Data type with one of the two built-in values, True or False. Boolean objects that are equal to True
are truthy (true), and those equal to False are falsy (false). But non-Boolean objects can be
evaluated in Boolean context as well and determined to be true or false. It is denoted by the
class bool.
Note – True and False with capital „T‟ and „F‟ are valid booleans otherwise python will throw an
error.
Python3
# Python program to
# demonstrate boolean type

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].,

File "/home/[Link]", line 8, in


print(type(true))
NameError: name 'true' is not defined
Set
In Python, Set is an unordered collection of data type that is iterable, mutable and has no duplicate
elements. The order of elements in a set is undefined though it may consist of various elements.
Creating Sets
Sets can be created by using the built-in set() function with an iterable object or a sequence by
placing the sequence inside curly braces, separated by „comma‟. Type of elements in a set need
not be the same, various mixed-up data type values can also be passed to the set.
Python3
# Python program to demonstrate
# Creation of Set in Python

# Creating a Set
set1 = set()
print("Initial blank Set: ")
print(set1)

# Creating a Set with


# the use of a String
set1 = set("GeeksForGeeks")
print("\nSet with the use of String: ")
print(set1)

# Creating a Set with


# the use of a List
set1 = set(["Geeks", "For", "Geeks"])
print("\nSet with the use of List: ")
print(set1)

# Creating a Set with


# a mixed type of values
# (Having numbers and strings)
set1 = set([1, 2, 'Geeks', 4, 'For', 6, 'Geeks'])
print("\nSet with the use of Mixed Values")
print(set1)
Output:
Initial blank Set:
set()

Set with the use of String:


{'F', 'o', 'G', 's', 'r', 'k', 'e'}

Set with the use of List:


{'Geeks', 'For'}

Set with the use of Mixed Values


{1, 2, 4, 6, 'Geeks', 'For'}

27
Python Programming III-CS [Link] [Link].,[Link].,

Accessing elements of Sets


Set items cannot be accessed by referring to an index, since sets are unordered the items has no
index. But you can loop through the set items using a for loop, or ask if a specified value is
present in a set, by using the in keyword.
Python3
# Python program to demonstrate
# Accessing of elements in a set

# Creating a set
set1 = set(["Geeks", "For", "Geeks"])
print("\nInitial set")
print(set1)

# Accessing element using


# for loop
print("\nElements of set: ")
for i in set1:
print(i, end =" ")

# Checking the element


# using in keyword
print("Geeks" in set1)
Output:
Initial set:
{'Geeks', 'For'}

Elements of set:
Geeks For

True

Note – To know more about sets, refer Python Sets.


Dictionary
Dictionary in Python is an unordered collection of data values, used to store data values like a
map, which unlike other Data Types that hold only single value as an element, Dictionary
holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Each
key-value pair in a Dictionary is separated by a colon :, whereas each key is separated by a
„comma‟.
Creating Dictionary
In Python, a Dictionary can be created by placing a sequence of elements within curly {} braces,
separated by „comma‟. Values in a dictionary can be of any datatype and can be duplicated,
whereas keys can‟t be repeated and must be immutable. Dictionary can also be created by the
built-in function dict(). An empty dictionary can be created by just placing it to curly braces{}.
Note – Dictionary keys are case sensitive, same name but different cases of Key will be treated
distinctly.
Python3
# Creating an empty Dictionary

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:
{}

Dictionary with the use of Integer Keys:


{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with the use of Mixed Keys:


{1: [1, 2, 3, 4], 'Name': 'Geeks'}

Dictionary with the use of dict():


{1: 'Geeks', 2: 'For', 3: 'Geeks'}

Dictionary with each item as a pair:


{1: 'Geeks', 2: 'For'}

Accessing elements of Dictionary


In order to access the items of a dictionary refer to its key name. Key can be used inside square
brackets. There is also a method called get() that will also help in accessing the element from a
dictionary.
Python3

29
Python Programming III-CS [Link] [Link].,[Link].,

# Python program to demonstrate


# accessing a element from a Dictionary

# Creating a Dictionary
Dict = {1: 'Geeks', 'name': 'For', 3: 'Geeks'}

# accessing a element using key


print("Accessing a element using key:")
print(Dict['name'])

# accessing a element using get()


# method
print("Accessing a element using get:")
print([Link](3))
Output:
Accessing a element using key:
For
Accessing a element using get:
Geeks
Number
Number data types store numeric values. They are immutable data types, which means that
changing the value of a number data type results in a newly allocated object.
Different types of Number data types are :
 int
 float
 complex
Let‟s see each one of them:
Int type
int (Integers) are the whole number, including negative numbers but not fractions. In Python, there
is no limit to how long an integer value can be.
Example 1: Creating int and checking type
num = -8

# print the data type


print(type(num))

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].,

Example 1: Creating float and checking type


num = 3/4

# print the data type


print(type(num))
Output:
<class 'float'>
As we have seen, dividing any two integers produces a float.
A float is also produced by running an operation on two floats, or a float and an integer.

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

# returning the ceil of 3.5


print ("The ceil of 3.5 is : ", end="")
print ([Link](a))

# returning the floor of 3.5


print ("The floor of 3.5 is : ", end="")
print ([Link](a))

# find the power


print ("The value of 3.5**2 is : ",end="")
print (pow(a,2))

# returning the log2 of 16


print ("The value of log2 of 3.5 is : ", end="")
print (math.log2(a))

# print the square root of 3.5


print ("The value of sqrt of 3.5 is : ", end="")
print([Link](a))

# returning the value of sine of 3.5


print ("The value of sine of 3.5 is : ", end="")
print ([Link](a))
Output
The ceil of 3.5 is : 4
The floor of 3.5 is : 3
The value of 3.5**2 is : 12.25
The value of log2 of 3.5 is : 1.8073549220576042
The value of sqrt of 3.5 is : 1.8708286933869707
The value of sine of 3.5 is : -0.35078322768961984

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 not equal to y


x=5
y = 10
print(bool(x==y))

# Returns False as x is None


x = None
print(bool(x))

# Returns False as x is an empty sequence


x = ()
print(bool(x))

# Returns False as x is an empty mapping


x = {}
print(bool(x))

# Returns False as x is 0

37
Python Programming III-CS [Link] [Link].,[Link].,

x = 0.0
print(bool(x))

# Returns True as x is a non empty string


x = 'GeeksforGeeks'
print(bool(x))
Output
False
False
False
False
False
True
We can also evaluate expression without using the bool() function also. The Booleans values will
be returned as a result of some sort of comparison. In the example below the variable res will store
the boolean value of False after the equality comparison takes place.
Example: Boolean value from the expression
 Python3
# Declaring variables
a = 10
b = 20

# 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

True True True

True False True

False True True

False False False

Example: Python Boolean OR Operator


 Python3
# Python program to demonstrate
# or operator

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).

Boolean And Operator

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

True True True

True False False

False True False

False False False

Example: Python Boolean And Operator

 Python3
# Python program to demonstrate
# and operator

a=0
b=2
c=4

if a > b and b<c:


print(True)
else:
print(False)

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

Boolean Not Operator

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].,

Example: Python Boolean Not Operator

 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.

Example: Python Boolean == (equivalent) and != (not equivalent) Operator

 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)

x = ["a", "b", "c", "d"]


y = ["a", "b", "c", "d"]

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"]

# Check if lion in list or not


if "lion" in animals:
print(True)
Output
True

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.

Example of Python Indentation


 Statement (line 1), if condition (line 2), and statement (last line) belongs to the same block
which means that after statement 1, if condition will be executed. and suppose the if condition
becomes False then the Python will jump to the last statement for execution.
 The nested if-else belongs to block 2 which means that if nested if becomes False, then Python
will execute the statements inside the else condition.
 Statements inside nested if-else belong to block 3 and only one statement will be executed
depending on the if-else condition.
Python indentation is a way of telling a Python interpreter that the group of statements belongs to
a particular block of code. A block is a combination of all these statements. Block can be regarded
as the grouping of statements for a specific purpose. Most programming languages like C, C++,
and Java use braces { } to define a block of code. Python uses indentation to highlight the blocks
of code. Whitespace is used for indentation in Python. All statements with the same distance to the
right belong to the same block of code. If a block has to be more deeply nested, it is simply
indented further to the right. You can understand it better by looking at the following lines of
code.
Example 1
The lines print(„Logging on to geeksforgeeks…‟) and print(„retype the URL.‟) are two separate
code blocks. The two blocks of code in our example if-statement are both indented four spaces.
The final print(„All set!‟) is not indented, so it does not belong to the else 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

# Print “GeeksforGeeks !” to console


print("GeeksforGeeks")

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].,

Using Multiple Hashtags (#)

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

# Python program to demonstrate


# multiline comments
print("Multiline comments")

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

'This will be ignored by Python'

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.

Example 2: Multiline comments using string literals

 Python3

""" Python program to demonstrate

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 the docstring of multiply function


print(multiply.__doc__)
Output:
Multiplies the value of a and b
Type Conversion in Python
Python defines type conversion functions to directly convert one data type to another which is
useful in day-to-day and competitive programming. This article is aimed at providing information
about certain conversion functions.
There are two types of Type Conversion in Python:
1. Implicit Type Conversion
2. Explicit Type Conversion
Let‟s discuss them in detail.
Implicit Type Conversion
In Implicit type conversion of data types in Python, the Python interpreter automatically converts
one data type to another without any user involvement. To get a more clear view of the topic see
the below examples.
Example:
 Python3
x = 10

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

# Python code to demonstrate Type conversion


# using int(), float()
# initializing string
s = "10010"
# printing string converting to int base 2
c = int(s,2)
print ("After converting to integer base 2 : ", end="")
print (c)
# printing string converting to float
e = float(s)
print ("After converting to float : ", end="")
print (e)

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].,

# Python code to demonstrate Type conversion

# using ord(), hex(), oct()

# initializing integer

s = '4'

# printing character converting to integer

c = ord(s)

print ("After converting character to integer : ",end="")

print (c)

# printing integer converting to hexadecimal string

c = hex(56)

print ("After converting 56 to hexadecimal string : ",end="")

print (c)

# printing integer converting to octal string

c = oct(56)

print ("After converting 56 to octal string : ",end="")

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

# Python code to demonstrate Type conversion

# using tuple(), set(), list()

# initializing string

s = 'geeks'

48
Python Programming III-CS [Link] [Link].,[Link].,

# printing string converting to tuple

c = tuple(s)

print ("After converting string to tuple : ",end="")

print (c)

# printing string converting to set

c = set(s)

print ("After converting string to set : ",end="")

print (c)

# printing string converting to list

c = list(s)

print ("After converting string to list : ",end="")

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

# Python code to demonstrate Type conversion

# using dict(), complex(), str()

# initializing integers

a=1

b=2

# initializing tuple

tup = (('a', 1) ,('f', 2), ('g', 3))

# printing integer converting to complex number

49
Python Programming III-CS [Link] [Link].,[Link].,

c = complex(1,2)

print ("After converting integer to complex number : ",end="")

print (c)

# printing integer converting to string

c = str(a)

print ("After converting integer to string : ",end="")

print (c)

# printing tuple converting to expression dictionary

c = dict(tup)

print ("After converting tuple to dictionary : ",end="")

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

# Convert ASCII value to characters

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].,

Operator Meaning Example

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

Example 4: Identity operators in Python


x1 = 5
y1 = 5
x2 = 'Hello'
y2 = 'Hello'
x3 = [1,2,3]
y3 = [1,2,3]

print(x1 is not y1) # prints False

print(x2 is y2) # prints True

print(x3 is y3) # prints False

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

The data type is determined at the run time.

Consider the program given below-

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:

Let's have a look at the explanation of this program-

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.

Relationship Between Objects, Variables and References.

The following sequence of steps happens when we assign a variable in Python-

1. We create an object in the memory that contains a value.


2. If the variable name doesn't exist already, we can create it.
3. The reference is assigned to the object to the variable.

Consider the program given below-

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:

Let's understand what happened in the above program.

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

Before starting with this, let's have a look at the program-

1. a = 12.0
2. b=a
3. print(a)
4. print(b)

Output:

12.0
12.0

Explanation:

It's time to understand what exactly happened here-

1. We have initialized the value of a as 12.0 and b as a.


2. After this, we have printed the values of both a and b that comes out to be 12.0

This is nothing but the concept of shared references which says that "Two variables can have the
same reference."

One more example would make it clearer.

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:

Let's have a look at the explanation of this program-

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 Disadvantage of Dynamically Typed Languages

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

You might also like