Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Python Unit I (2023-26)

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

St.

Charles College of Arts and Science, Eraiyur – 607 201


Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

St. CHARLES COLLEGE OF ARTS AND SCIENCE


Eraiyur– 607 201

DEPARTMENT OF COMPUTER SCIENCE – III CS


Subject Code: CCS62
Subject Name: PYTHON PROGRAMMING
Prepared By
Prof.J. Gomathi, MCA.,M.Phil.,NET
Asst. Professor & Head, Department of Computer Science

Prof.J. Gomathi, AP & Head, CS 1


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

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.

MODEL QUESTIONS
10M
01. Discuss in details about the operators used in Python Programming.

5M
01. How do you read input and print output in Python Programming?
02. What is Type Conversion? Explain with suitable examples.
03. Discuss about i) int() function ii) float() function iii) str() function iv) chr() function
04. What is called dynamic and strongly typed language? Briefly explain.
2M
01. What is Python?
02. Define Identifiers.
03. What are keywords?
04. Define Variable.
05. What is called indentation?
06. Distinguish between single line comment and multi-line comment.

Prof.J. Gomathi, AP & Head, CS 2


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

UNIT-I – Python Programming Notes

Python History and Versions


 Python laid its foundation in the late 1980s.
 The implementation of Python was started in December 1989 by Guido Van Rossum at CWI in
Netherland.
 In February 1991, Guido Van Rossum published the code (labeled version 0.9.0) to alt.sources.
 In 1994, Python 1.0 was released with new features like lambda, map, filter, and reduce.
 Python 2.0 added new features such as list comprehensions, garbage collection systems.
 On December 3, 2008, Python 3.0 (also called "Py3K") was released. It was designed to rectify the
fundamental flaw of the language.
 ABC programming language is said to be the predecessor of Python language, which was capable of
Exception Handling and interfacing with the Amoeba Operating System.

The following programming languages influence Python:


 ABC language.
 Modula-3

Why the Name Python?


There is a fact behind choosing the name Python. Guido van Rossum was reading the script of a popular
BBC comedy series "Monty Python's Flying Circus". It was late on-air 1970s.

Van Rossum wanted to select a name which unique, sort, and little-bit mysterious. So he decided to select
naming Python after the "Monty Python's Flying Circus" for their newly created programming language.

The comedy series was creative and well random. It talks about everything. Thus it is slow and
unpredictable, which made it very interesting.

Python is also versatile and widely used in every technical field, such as Machine Learning, Artificial
Intelligence, Web Development, Mobile Application, Desktop Application, Scientific Calculation, etc.

Prof.J. Gomathi, AP & Head, CS 3


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

Python Identifiers and Keywords


Identifier

Prof.J. Gomathi, AP & Head, CS 4


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

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 characters ( #, @, $, %, ! ) in identifiers.

Examples of valid identifiers:


var1
_var1
_1_var
var_1

Examples of invalid identifiers


!var1
1var
1_var
var#1

Keywords
Keywords are some predefined and reserved words in python that have special meanings. Keywords
are used to define the syntax of the coding. The keyword cannot be used as an identifier, function, and
variable name. All the keywords in python are written in lower case except True and False. There are 33
keywords in Python.
Python Keywords
Keywords               Description

This is a logical operator it returns true if both the operands are true else return
and
false.

This is also a logical operator it returns true if anyone operand is true else
Or
return false.

This is again a logical operator it returns True if the operand is false else return
not
false.

if This is used to make a conditional statement.

Elif is a condition statement used with an if statement the elif statement is


elif
executed if the previous conditions were not true

else Else is used with if and elif conditional statement the else block is executed if

Prof.J. Gomathi, AP & Head, CS 5


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

Keywords               Description

the given condition is not true.

for This is created for a loop.

while This keyword is used to create a while loop.

break This is used to terminate the loop.

as This is used to create an alternative.

def It helps us to define functions.

lambda It is used to define the anonymous function.

1: Example of and, or, not, True, False keywords.


print("example of True, False, and, or not keywords")
# compare two operands using and operator
print(True and True)
# compare two operands using or operator
print(True or False)
# use of not operator
print(not False)

Output:
example of True, False, and, or not keywords
True
True
True
2: Example of a break, continue.
# execute for loop
for i in range(1, 11):
# print the value of i
print(i)
# check the value of i is less than 5
# if i lessthan 5 then continue loop
if i < 5:
continue

Prof.J. Gomathi, AP & Head, CS 6


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

# if i greater than 5 then break loop


else:
break
Output:
1
2
3
4
5

Statements and Expressions in Python


Python Statements
 A statement in Python is used for creating variables or for displaying values.
 A statement in Python is not evaluated for some results.
 The execution of a statement changes the state of the variable.
 A statement can be an expression.
Example : x = 3
Output : 3
Python Expressions
An expression is a combination of operators and operands that is interpreted to produce some other
value. In any programming language, an expression is evaluated as per the precedence of its operators. So
that if there is more than one operator in an expression, their precedence decides which operation will be
performed first. We have many different types of expressions in Python. Let’s discuss all types along with
some exemplar codes :
1. Constant Expressions: These are the expressions that have constant values only.
Example:
# Constant Expressions
x = 15 + 1.3
print(x)

Output
16.3

2. Arithmetic Expressions: An arithmetic expression is a combination of numeric values, operators,


and sometimes parenthesis. The result of this type of expression is also a numeric value. The operators
used in these expressions are arithmetic operators like addition, subtraction, etc. Here are some arithmetic
operators in Python:
Operators Syntax Functioning

Prof.J. Gomathi, AP & Head, CS 7


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

+ x+y Addition
– x–y Subtraction
* x*y Multiplication
/ x/y Division
// x // y Quotient
% x%y Remainder
** x ** y Exponentiation

Example:
# Arithmetic Expressions
x = 40
y = 12
add = x + y
sub = x - y
pro = x * y
div = x / y
print(add)
print(sub)
print(pro)
print(div)
Output
52
28
480
3.3333333333333335

3. Integral Expressions: These are the kind of expressions that produce only integer results after all
computations and type conversions.
Example:
# Integral Expressions
a = 13
b = 12.0
c = a + int(b)
print(c)
Output
25
4. Floating Expressions: These are the kind of expressions which produce floating point numbers as
result after all computations and type conversions.

Example:
# Floating Expressions
a = 13

Prof.J. Gomathi, AP & Head, CS 8


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

b=5
c=a/b
print(c)
Output
2.6

5. Relational Expressions: In these types of expressions, arithmetic expressions are written on both
sides of relational operator (> , < , >= , <=). Those arithmetic expressions are evaluated first, and then
compared as per relational operator and produce a boolean output in the end. These expressions are also
called Boolean expressions.
Example:
# Relational Expressions
a = 21
b = 13
c = 40
d = 37
p = (a + b) >= (c - d)
print(p)
Output
True

6. Logical Expressions: These are kinds of expressions that result in either True or False. It basically
specifies one or more conditions. For example, (10 == 9) is a condition if 10 is equal to 9. As we know it is
not correct, so it will return False. Studying logical expressions, we also come across some logical operators
which can be seen in logical expressions most often. Here are some logical operators in Python:
Operator Syntax Functioning
and P and Q It returns true if both P and Q are true otherwise returns false
or P or Q It returns true if at least one of P and Q is true
not not P It returns true if condition P is false

Example:
P = (10 == 9)
Q = (7 > 5)
# Logical Expressions
R = P and Q
S = P or Q
T = not P
print(R)
print(S)
print(T)

Output

Prof.J. Gomathi, AP & Head, CS 9


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

False
True
True

7. Bitwise Expressions: These are the kind of expressions in which computations are performed at bit
level.
Example:
# Bitwise Expressions
a = 12
x = a >> 2
y = a << 1
print(x, y)

Output
3 24

8. Combinational Expressions: We can also use different types of expressions in a single expression,
and that will be termed as combinational expressions.
Example:
# Combinational Expressions
a = 16
b = 12
c = a + (b >> 1)
print(c)

Output
22

But when we combine different types of expressions or use multiple operators in a single expression,
operator precedence comes into play.

Multiple operators in expression (Operator Precedence)


Operator Precedence simply defines the priority of operators that which operator is to be executed
first. Here we see the operator precedence in Python, where the operator higher in the list has more
precedence or priority:

Precedence Name Operator

1 Parenthesis    ()[]{}

2 Exponentiation  **

Prof.J. Gomathi, AP & Head, CS 10


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

Precedence Name Operator

3 Unary plus or minus, complement  -a , +a , ~a

4 Multiply, Divide, Modulo   /  *  //  %

5 Addition & Subtraction  +  –

6 Shift Operators >>  <<

7 Bitwise AND &

8 Bitwise XOR ^

9 Bitwise OR |

10 Comparison Operators >=  <=  >  <

11 Equality Operators ==  !=

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

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

14 Logical Operators    and, or, not

So, if we have more than one operator in an expression, it is evaluated as per operator precedence. For
example, if we have the expression “10 + 3 * 4”. Going without precedence it could have given two
different outputs 22 or 52. But now looking at operator precedence, it must yield 22.

# Multi-operator expression
a = 10 + 3 * 4
print(a)

b = (10 + 3) * 4
print(b)

c = 10 + (3 * 4)

Prof.J. Gomathi, AP & Head, CS 11


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

print(c)

Output
22
52
22
Hence, operator precedence plays an important role in the evaluation of a Python expression.

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
The expression in Python produces some value or
A statement in Python is used for creating
result after being interpreted by the Python
variables or for displaying values.
interpreter.
A statement in Python is not evaluated for An expression in Python is evaluated for some
some results. results.
The execution of a statement changes the The expression evaluation does not result in any
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

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

Example of Python Variables


Var = "Geeksforgeeks"
print(Var)
Output:
Geeksforgeeks

Rules for creating variables in Python


 A variable name must start with a letter or the underscore character.
 A variable name cannot start with a number.
 A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ).

Prof.J. Gomathi, AP & Head, CS 12


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

 Variable names are case-sensitive (name, Name and NAME are three different variables).
 The reserved words(keywords) cannot be used naming the variable.
Example:
# An integer assignment
age = 45
# A floating point
salary = 1456.8
# A string
name = "John"
print(age)
print(salary)
print(name)
Output:
45
1456.8
John

Declare the Variable


# declaring the var
Number = 100
# display
print( Number)
Output:
100

Re-declare the Variable


We can re-declare the python variable once we have declared the variable already.
# declaring the var
Number = 100
# display
print("Before declare: ", Number)
# re-declare the var
Number = 120.3
print("After re-declare:", Number)

Output:
Before declare: 100
After re-declare: 120.3
Assigning a single value to multiple variables
Also, Python allows assigning a single value to several variables simultaneously with “=” operators.
For example:
a = b = c = 10

Prof.J. Gomathi, AP & Head, CS 13


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

print(a)
print(b)
print(c)
Output:
10
10
10

Assigning different values to multiple variables


Python allows adding different values in a single line with “,”operators.
a, b, c = 1, 20.2, "GeeksforGeeks"
print(a)
print(b)
print(c)
Output:
1
20.2
GeeksforGeeks

Can we use the same name for different types?


If we use the same name, the variable starts referring to a new value and type.
a = 10
a = "GeeksforGeeks"
print(a)
Output:
GeeksforGeeks

How does + operator work with variables?


a = 10
b = 20
print(a+b)

a = "Geeksfor"
b = "Geeks"
print(a+b)
Output
30
GeeksforGeeks
Can we use + for different types also?
No use for different types would produce an error.
a = 10
b = "Geeks"

Prof.J. Gomathi, AP & Head, CS 14


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

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

Global and Local Python Variables


Local Variables
 Local variables are the ones that are defined and declared inside a function.
 We cannot call this variable outside the function.
# This function uses global variable s
def f():
s = "Welcome geeks"
print(s)
f()
Output:
Welcome geeks

Global Variables
Global variables are the ones that are defined and declared outside a function, and we need to use
them inside a function.
# This function has a variable with
# name same as s.
def f():
print(s)
# Global scope
s = "I love Geeksforgeeks"
f()
Output:
I love Geeksforgeeks

Global keyword in Python


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

Rules of global keyword:


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

Prof.J. Gomathi, AP & Head, CS 15


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

Example:
# Python program to modify a global
# value inside a function
x = 15

def change():
# using a global keyword
global x

# increment value of a by 5
x=x+5
print("Value of x inside a function :", x)

change()
print("Value of x outside a function :", x)
Output:
Value of x inside a function : 20
Value of x outside a function : 20

Variable type in Python


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


 Numeric
 Sequence Type
 Boolean
 Set
 Dictionary

Examples:
# numeric
var = 123
print("Numeric data : ", var)

# Sequence Type
String1 = 'Welcome to the Geeks World'
print("String with the use of Single Quotes: ")
print(String1)

Prof.J. Gomathi, AP & Head, CS 16


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

# Boolean
print(type(True))
print(type(False))

# Creating a Set with


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

# Creating a Dictionary
# with Integer Keys
Dict = {1: 'Geeks', 2: 'For', 3: 'Geeks'}
print("\nDictionary with the use of Integer Keys: ")
print(Dict)
Output:
Numeric data : 123

String with the use of Single Quotes:


Welcome to the Geeks World

<class 'bool'>
<class 'bool'>

Set with the use of String:


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

Dictionary with the use of Integer Keys:


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

Object References
Let, we assign a variable x to value 5, and
x=5

Another variable is y to the variable x.


x=y

Prof.J. Gomathi, AP & Head, CS 17


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

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

Now, if we write:
x = 'Geeks'
This statement makes a new object to represent ‘Geeks’ and makes x to reference this new object.

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

Creating objects (or variables of a class type)


# Python program to show that the variables with a value
# assigned in class declaration, are class variables and
# variables inside methods and constructors are instance
# variables.

# Class for Computer Science Student


class CSStudent:

# Class Variable
stream = 'cse'
# The init method or constructor
def __init__(self, roll):

Prof.J. Gomathi, AP & Head, CS 18


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

# Instance Variable
self.roll = roll

# Objects of CSStudent class


a = CSStudent(101)
b = CSStudent(102)

print(a.stream) # prints "cse"


print(b.stream) # prints "cse"
print(a.roll) # prints 101

# Class variables can be accessed using class


# name also
print(CSStudent.stream) # prints "cse"
Output
cse
cse
101
cse

Python 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
OPERATORS: Are the special symbols. Eg- + , * , /, etc.

OPERAND: It is the value on which the operator is applied.

Arithmetic Operators
Arithmetic operators are used to performing mathematical operations like addition, subtraction,
multiplication, and division.

Note: In Python 3.x the result of division is a floating-point while in Python 2.x division of 2 integer was an
integer and to obtain an integer result in Python 3.x floored (// integer) is used.
Operator Description Syntax
+ Addition: adds two operands x+y
– Subtraction: subtracts two operands x–y
* Multiplication: multiplies two operands x*y
/ Division (float): divides the first operand by the second x/y
// Division (floor): divides the first operand by the second x // y
% Modulus: returns the remainder when the first operand is divided by x % y

Prof.J. Gomathi, AP & Head, CS 19


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

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

PRECEDENCE:
P – Parentheses
E – Exponentiation
M – Multiplication (Multiplication and division have the same precedence)
D – Division
A – Addition (Addition and subtraction have the same precedence)
S – Subtraction
The modulus operator helps us extract the last digit/s of a number. For example:
x % 10 -> yields the last digit
x % 100 -> yield last two digits

# Examples of Arithmetic Operators in Python


a=9
b=4
# Addition of numbers
add = a + b
# Subtraction of numbers
sub = a - b
# Multiplication of number
mul = a * b
# Division(float) of number
div1 = a / b
# Division(floor) of number
div2 = a // b
# Modulo of both number
mod = a % b
# Power
p = a ** b

# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
print(p)
Output
13
5

Prof.J. Gomathi, AP & Head, CS 20


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

36
2.25
2
1
6561
Note: Refer to Differences between / and // for some interesting facts about these two operators.

Comparison Operators
Comparison of Relational operators compares the values. It either returns True or False according to
the condition.
Operator Description Syntax
> Greater than: True if the left operand is greater than the right x>y
< Less than: True if the left operand is less than the right x<y
== Equal to: True if both operands are equal x == y
!= Not equal to – True if operands are not equal x != y
>= Greater than or equal to True if the left operand is greater than or equal to the right x >= y
<= Less than or equal to True if the left operand is less than or equal to the right x <= y
is x is the same as y x is y
is not x is not the same as y x is not y

= is an assignment operator and == comparison operator.


# Examples of Relational Operators
a = 13
b = 33
# a > b is False
print(a > b)
# a < b is True
print(a < b)
# a == b is False
print(a == b)
# a != b is True
print(a != b)
# a >= b is False
print(a >= b)
# a <= b is True
print(a <= b)
Output
False
True
False
True
False

Prof.J. Gomathi, AP & Head, CS 21


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

True

Logical Operators
Logical operators perform Logical AND, Logical OR, and Logical NOT operations. It is used to combine
conditional statements.
Operator Description Syntax
and Logical AND: True if both the operands are true x and y
or Logical OR: True if either of the operands is true x or y
not Logical NOT: True if the operand is false not x

# Examples of Logical Operator


a = True
b = False
# Print a and b is False
print(a and b)
# Print a or b is True
print(a or b)
# Print not a is False
print(not a)
Output
False
True
False

Bitwise Operators
Bitwise operators act on bits and perform the bit-by-bit operations. These are used to operate on
binary numbers.
Operator Description Syntax
& Bitwise AND x&y
| Bitwise OR x|y
~ Bitwise NOT ~x
^ Bitwise XOR x^y
>> Bitwise right shift x>>
<< Bitwise left shift x<<
# Examples of Bitwise operators
a = 10
b=4
# Print bitwise AND operation
print(a & b)
# Print bitwise OR operation
print(a | b)
# Print bitwise NOT operation

Prof.J. Gomathi, AP & Head, CS 22


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

print(~a)
# print bitwise XOR operation
print(a ^ b)
# print bitwise right shift operation
print(a >> 2)
# print bitwise left shift operation
print(a << 2)
Output
0
14
-11
14
2
40

Assignment Operators
Assignment operators are used to assign values to the variables.
Operator Description Syntax
= Assign value of right side of expression to left side operand x=y+z
+= Add AND: Add right-side operand with left side operand and then a+=b a=a+b
assign to left operand
-= Subtract AND: Subtract right operand from left operand and then a-=b a=a-b
assign to left operand
*= Multiply AND: Multiply right operand with left operand and then a*=b a=a*b
assign to left operand
/= Divide AND: Divide left operand with right operand and then assign to a/=b a=a/b
left operand
%= Modulus AND: Takes modulus using left and right operands and a%=b a=a%b
assign the result to left operand
//= Divide(floor) AND: Divide left operand with right operand and then a//=b a=a//b
assign the value(floor) to left operand
**= Exponent AND: Calculate exponent(raise power) value using operands a**=b a=a**b
and assign value to left operand
&= Performs Bitwise AND on operands and assign value to left operand a&=b a=a&b
|= Performs Bitwise OR on operands and assign value to left operand a|=b a=a|b
^= Performs Bitwise xOR on operands and assign value to left operand a^=b a=a^b
>>= Performs Bitwise right shift on operands and assign value to left a>>=b a=a>>b
operand
<<= Performs Bitwise left shift on operands and assign value to left operand a <<= b a= a << b
# Examples of Assignment Operators
a = 10
# Assign value

Prof.J. Gomathi, AP & Head, CS 23


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

b=a
print(b)
# Add and assign value
b += a
print(b)
# Subtract and assign value
b -= a
print(b)
# multiply and assign
b *= a
print(b)

# bitwise lishift operator


b <<= a
print(b)
Output
10
20
10
100
102400

Identity Operators
is and is not are the identity operators both are used to check if two values are located on the same
part of the memory. Two variables that are equal do not imply that they are identical.
is True if the operands are identical
is not True if the operands are not identical

Example: Identity Operator


a = 10
b = 20
c=a
print(a is not b)
print(a is c)
Output
True
True

Membership Operators
in and not in are the membership operators; used to test whether a value or variable is in a sequence.
in True if value is found in the sequence

Prof.J. Gomathi, AP & Head, CS 24


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

not in True if value is not found in the sequence

# Python program to illustrate


# not 'in' operator
x = 24
y = 20
list = [10, 20, 30, 40, 50]
if (x not in list):
print("x is NOT present in given list")
else:
print("x is present in given list")
if (y in list):
print("y is present in given list")
else:
print("y is NOT present in given list")
Output
x is NOT present in given list
y is present in given list

Precedence and Associativity of Operators


Operator precedence and associativity determine the priorities of the operator.

Operator Precedence
This is used in an expression with more than one operator with different precedence to determine which
operation to perform first.
# Examples of Operator Precedence

# Precedence of '+' & '*'


expr = 10 + 20 * 30
print(expr)

# Precedence of 'or' & 'and'


name = "Alex"
age = 0

if name == "Alex" or name == "John" and age >= 2:


print("Hello! Welcome.")
else:
print("Good Bye!!")
Output
610
Hello! Welcome.

Prof.J. Gomathi, AP & Head, CS 25


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

Operator Associativity
If an expression contains two or more operators with the same precedence then Operator Associativity is
used to determine. It can either be Left to Right or from Right to Left.
# Examples of Operator Associativity

# Left-right associativity
# 100 / 10 * 10 is calculated as
# (100 / 10) * 10 and not
# as 100 / (10 * 10)
print(100 / 10 * 10)

# Left-right associativity
# 5 - 2 + 3 is calculated as
# (5 - 2) + 3 and not
# as 5 - (2 + 3)
print(5 - 2 + 3)

# left-right associativity
print(5 - (2 + 3))

# right-left associativity
# 2 ** 3 ** 2 is calculated as
# 2 ** (3 ** 2) and not
# as (2 ** 3) ** 2
print(2 ** 3 ** 2)

Output
100.0
6
0
512

Python Data Types


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

Prof.J. Gomathi, AP & Head, CS 26


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

Text Type: str


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

Getting the Data Type


We can get the data type of any object by using the type() function:
Example
# 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))

# Python Program for Creation of String


# Creating a String with single Quotes
String1 = 'Welcome to the Geeks World'

Prof.J. Gomathi, AP & Head, CS 27


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

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

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

Setting the Data Type


In Python, the data type is set when you assign a value to a variable:
Example Data Type
x = "Hello World" str
x = 20 int
x = 20.5 float
x = 1j complex

Prof.J. Gomathi, AP & Head, CS 28


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

x = ["apple", "banana", "cherry"] list


x = ("apple", "banana", "cherry") tuple
x = range(6) range
x = {"name" : "John", "age" : 36} dict
x = {"apple", "banana", "cherry"} set
x = frozenset({"apple", "banana", "cherry"}) frozenset
x = True bool
x = b"Hello" bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview
x = None NoneType

Setting the Specific Data Type


If we want to specify the data type, we can use the following constructor functions:
Example Data Type
x = str("Hello World") str
x = int(20) int
x = float(20.5) float
x = complex(1j) complex
x = list(("apple", "banana", "cherry")) list
x = tuple(("apple", "banana", "cherry")) tuple
x = range(6) range
x = dict(name="John", age=36) dict
x = set(("apple", "banana", "cherry")) set
x = frozenset(("apple", "banana", "cherry")) frozenset
x = bool(5) bool
x = bytes(5) bytes
x = bytearray(5) bytearray
x = memoryview(bytes(5)) memoryview

Python Indentation
 Indentation refers to the spaces at the beginning of a code line.
 Where in other programming languages the indentation in code is for readability only, the
indentation in Python is very important.
 Python uses indentation to indicate a block of code.

Example
if 5 > 2:
print("Five is greater than two!")

Prof.J. Gomathi, AP & Head, CS 29


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

Python will give you an error if you skip the indentation:


Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
The number of spaces is up to you as a programmer, but it has to be at least one.

Example
if 5 > 2:
print("Five is greater than two!")
if 5 > 2:
print("Five is greater than two!")
We have to use the same number of spaces in the same block of code, otherwise Python will give you
an error:

Example
Syntax Error:
if 5 > 2:
print("Five is greater than two!")
print("Five is greater than two!")

Python Comments
 Comments can be used to explain Python code.
 Comments can be used to make the code more readable.
 Comments can be used to prevent execution when testing code.

Creating a Comment
Comments starts with a #, and Python will ignore them:
Example
#This is a comment
print("Hello, World!")

Comments can be placed at the end of a line, and Python will ignore the rest of the line:
Example
print("Hello, World!") #This is a comment

A comment does not have to be text that explains the code, it can also be used to prevent Python from
executing code:
Example
#print("Hello, World!")
print("Cheers, Friends!")

Prof.J. Gomathi, AP & Head, CS 30


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

Multiline Comments
 Python does not really have syntax for multiline comments.
 To add a multiline comment you could insert a # for each line:

Example
#This is a comment
#written in
#more than just one line
print("Hello, World!")
Or, not quite as intended, you can use a multiline string.

Since Python will ignore string literals that are not assigned to a variable, you can add a multiline
string (triple quotes) in your code, and place your comment inside it:

Example
"""
This is a comment
written in
more than just one line
"""
print("Hello, World!")

Reading input in Python

Python provides us with two inbuilt functions to read the input from the keyboard.
 input ( prompt )
 raw_input ( prompt )

input ():
 This function first takes the input from the user and converts it into a string.
 The type of the returned object always will be <type ‘str’>.
 It does not evaluate the expression it just returns the complete statement as String.

Syntax:
inp = input('STATEMENT')

# Python program showing a use of input()


val = input("Enter your value: ")
print(val)

Prof.J. Gomathi, AP & Head, CS 31


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

Taking String as an input:


name = input('What is your name?\n') # \n ---> newline ---> It causes a line break
print(name)

Output:
What is your name?
Ram
Ram

How the input function works in Python :


When input() function executes program flow will be stopped until the user has given input.
 The text or message displayed on the output screen to ask a user to enter an input value is optional
i.e. the prompt, which will be printed on the screen is optional.
 Whatever we enter as input, the input function converts it into a string. if we enter an integer value
still input() function converts it into a string.
 We need to explicitly convert it into an integer in your code using typecasting.

# Program to check input type in Python

num = input ("Enter number :")


print(num)
name1 = input("Enter name : ")
print(name1)

# Printing type of input value


print ("type of number", type(num))
print ("type of name", type(name1))
Output:

Prof.J. Gomathi, AP & Head, CS 32


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

raw_input(): This function works in older version (like Python 2.x). This function takes exactly what is
typed from the keyboard, converts it to string, and then returns it to the variable in which we want to store it.

# Python program showing a use of raw_input()


g = raw_input("Enter your name : ")
print g

Here, g is a variable that will get the string value, typed by the user during the execution of the program.
Typing of data for the raw_input() function is terminated by enter key. We can use raw_input() to enter
numeric data also. In that case, we use typecasting.
Note: input() function takes all the input as a string only

There are various function that are used to take as desired input few of them are : –
 int(input())
 float(input())

num = int(input("Enter a number: "))


print(num, " ", type(num))

floatNum = float(input("Enter a decimal number: "))


print(floatNum, " ", type(floatNum))

Output:

Print Output in Python


Python print() Function

Example
Print a message onto the screen:
 print("Hello World")

Prof.J. Gomathi, AP & Head, CS 33


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

Definition and Usage


 The print() function prints the specified message to the screen, or other standard output device.
 The message can be a string, or any other object, the object will be converted into a string before written
to the screen.
Syntax
print(object(s), sep=separator, end=end, file=file, flush=flush)

Parameter Values
Parameter Description

object(s) Any object, and as many as you like. Will be converted to string before printed

sep='separator' Optional. Specify how to separate the objects, if there is more than one. Default
is ' '

end='end' Optional. Specify what to print at the end. Default is '\n' (line feed)

file Optional. An object with a write method. Default is sys.stdout

flush Optional. A Boolean, specifying if the output is flushed (True) or buffered


(False). Default is False

Print more than one object:


print("Hello", "how are you?")

Example
Print a tuple:
x = ("apple", "banana", "cherry")
print(x)

Example
Print two messages, and specify the separator:
print("Hello", "how are you?", sep="---")

Example for flush argument


import time
count_seconds = 3
for i in reversed(range(count_seconds + 1)):
if i > 0:
print(i, end='>>>', flush = True)
time.sleep(1)
else:
print('Start')

Prof.J. Gomathi, AP & Head, CS 34


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

Separator
The print() function can accept any number of positional arguments. To separate these positional
arguments , keyword argument “sep” is used.
a=12
b=12
c=2022
print(a,b,c,sep="-")

Output:
12-12-2022

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

There are two types of Type Conversion in Python:


 Implicit Type Conversion
 Explicit Type Conversion

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.
Example:
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'>

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

Prof.J. Gomathi, AP & Head, CS 35


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

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.

01. 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.
02. float(): This function is used to convert any data type to a floating-point number.

# 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

03. ord() : This function is used to convert a character to integer.


04. hex() : This function is to convert integer to hexadecimal string.
05. oct() : This function is to convert integer to octal string.

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

Prof.J. Gomathi, AP & Head, CS 36


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

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
06. tuple() : This function is used to convert to a tuple.
07. set() : This function returns the type after converting to set.
08. list() : This function is used to convert any data type to a list type.

# Python code to demonstrate Type conversion


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

# initializing string
s = 'geeks'

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

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

# Python code to demonstrate Type conversion


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

Prof.J. Gomathi, AP & Head, CS 37


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

a=1
b=2
# initializing tuple
tup = (('a', 1) ,('f', 2), ('g', 3))
# printing integer converting to complex number
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.

# Convert ASCII value to characters


a = chr(76)
b = chr(77)
print(a)
print(b)
Output:
L
M

type() function in Python


The type() function is mostly used for debugging purposes. Two different types of arguments can be
passed to type() function, single and three arguments. If a single argument type(obj) is passed, it
returns the type of the given object. If three arguments type(object, bases, dict) is passed, it returns a
new type object.

Applications:
 type() function is basically used for debugging purposes. errors,
 type() function can be used at that point to determine the type of text extracted and then change it to
other forms of string before we use string functions or any other operations on it.

Prof.J. Gomathi, AP & Head, CS 38


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

 type() with three arguments can be used to dynamically initialize classes or existing classes with
attributes. It is also used to register database tables with SQL.

Syntax of type() function


type(object, bases, dict)

Parameters :
 object: Required. If only one parameter is specified, the type() function returns the type of this object
 bases : tuple of classes from which the current class derives. Later corresponds to the __bases__
attribute.
 dict : a dictionary that holds the namespaces for the class. Later corresponds to the __dict__ attribute.

Return: returns a new type class or essentially a metaclass.

Example 1: type() with Object parameter


Here we are checking the object type using the type() function.
a = ("Geeks", "for", "Geeks")
b = ["Geeks", "for", "Geeks"]
c = {"Geeks": 1, "for":2, "Geeks":3}
d = "Hello World"
e = 10.23
f = 11.22

print(type(a))
print(type(b))
print(type(c))
print(type(d))
print(type(e))
print(type(f))
Output:
<class 'tuple'>
<class 'list'>
<class 'dict'>
<class 'str'>
<class 'float'>
<class 'float'>

Example 2: Check object parameter


In this example, we are testing the object using conditions, and printing the boolean.
print(type([]) is list)
print(type([]) is not list)
print(type(()) is tuple)

Prof.J. Gomathi, AP & Head, CS 39


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

print(type({}) is dict)
print(type({}) is not list)
Output :
True
False
True
True
True

Example 3: Use of type(name, bases, dict)


Here, print type() function which returns class ‘type’.

# New class(has no base) class with the


# dynamic class initialization of type()
new = type('New', (object, ),
dict(var1='GeeksforGeeks', b=2009))
# Print type() which returns class 'type'
print(type(new))
print(vars(new))

# Base class, incorporated in our new class


class test:
a = "Geeksforgeeks"
b = 2009

# Dynamically initialize Newer class


# It will derive from the base class test
newer = type('Newer', (test, ),
dict(a='Geeks', b=2018))

print(type(newer))
print(vars(newer))
Output :
{'__module__': '__main__', 'var1': 'GeeksforGeeks', '__weakref__': ,
'b': 2009, '__dict__': , '__doc__': None}

{'b': 2018, '__doc__': None, '__module__': '__main__', 'a': 'Geeks'}

Prof.J. Gomathi, AP & Head, CS 40


St. Charles College of Arts and Science, Eraiyur – 607 201
Department of Comp. Science–CCS62–Python Programming – III Yr (VI SEM)

Dynamic and Strongly typed language


Python is strongly typed
 Strong typing means that the type of an object doesn't change in unexpected ways.
 A string containing only digits doesn't magically become a number, as may happen in weakly typed
languages like JavaScript and Perl.
 Every change of type requires an explicit type conversion (i.e casting).

1 + "1" # TypeError in Python


1 + "1" // "11" in JavaScript

Python is dynamically typed


Python variable assignment is different from some of the popular languages like c, c++ and java.
There is no declaration of a variable, just an assignment statement.
 When we declare a variable in C or alike languages, this sets aside an area of memory for holding values
allowed by the data type of the variable.
 The memory allocated will be interpreted as the data type suggests.
 If it’s an integer variable the memory allocated will be read as an integer and so on.
 When we assign or initialize it with some value, that value will get stored at that memory location.
 At compile time, initial value or assigned value will be checked. So we cannot mix types.
 Example: initializing a string value to an int variable is not allowed and the program will not compile.

But Python is a dynamically typed language.


 It doesn’t know about the type of the variable until the code is run. So declaration is of no use.
 What it does is, It stores that value at some memory location and then binds that variable name to that
memory container.
 And makes the contents of the container accessible through that variable name.
 So the data type does not matter. As it will get to know the type of the value at run-time.

# This will store 6 in the memory and binds the name x to it. After it runs, type of x will be int.
x=6
print(type(x))

# This will store 'hello' at some location int the memory and binds name x to it. After it
# runs type of x will be str.
x = 'hello'

print(type(x))
Output:
<class 'int'>
<class 'str'>

Prof.J. Gomathi, AP & Head, CS 41

You might also like