Python Unit I (2023-26)
Python Unit I (2023-26)
Python Unit I (2023-26)
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.
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.
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.
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.
else Else is used with if and elif conditional statement the else block is executed if
Keywords Description
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
Output
16.3
+ 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
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
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.
1 Parenthesis ()[]{}
2 Exponentiation **
8 Bitwise XOR ^
9 Bitwise OR |
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)
print(c)
Output
22
52
22
Hence, operator precedence plays an important role in the evaluation of a Python expression.
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.
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
Output:
Before declare: 100
After re-declare: 120.3
Assigning a single value to multiple variables
Also, Python allows assigning a single value to several variables simultaneously with “=” operators.
For example:
a = b = c = 10
print(a)
print(b)
print(c)
Output:
10
10
10
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"
print(a+b)
Output :
TypeError: unsupported operand type(s) for +: 'int' and 'str'
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
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
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)
# Boolean
print(type(True))
print(type(False))
# 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
<class 'bool'>
<class 'bool'>
Object References
Let, we assign a variable x to value 5, and
x=5
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"
# Class Variable
stream = 'cse'
# The init method or constructor
def __init__(self, roll):
# Instance Variable
self.roll = roll
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.
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
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
# print results
print(add)
print(sub)
print(mul)
print(div1)
print(div2)
print(mod)
print(p)
Output
13
5
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
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
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
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
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)
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
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
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
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 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!")
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!")
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!")
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')
Output:
What is your name?
Ram
Ram
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.
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())
Output:
Example
Print a message onto the screen:
print("Hello World")
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)
Example
Print a tuple:
x = ("apple", "banana", "cherry")
print(x)
Example
Print two messages, and specify the separator:
print("Hello", "how are you?", sep="---")
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
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.
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
# 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)
# initializing string
s = 'geeks'
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.
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.
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.
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.
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.
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'>
print(type({}) is dict)
print(type({}) is not list)
Output :
True
False
True
True
True
print(type(newer))
print(vars(newer))
Output :
{'__module__': '__main__', 'var1': 'GeeksforGeeks', '__weakref__': ,
'b': 2009, '__dict__': , '__doc__': None}
# 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'>