Unit 1-1
Unit 1-1
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 IN PYTHON
Identifier is a user-defined name given to a variable, function, class, module, etc. The
identifier is a combination of character digits and an underscore. They are case-sensitive i.e.,
„num‟ and „Num‟ and „NUM‟ are three different identifiers in python. It is a good
programming practice to give meaningful names to identifiers to make the code
understandable.
Valid identifiers:
var1
_var1
_1_var
var_1
Invalid Identifiers:
!var1
1var
1_var
var#1
var 1
UNIT - I Page 1
PYTHON PROGRAMMING – CCS 62
Example :
myVariable="hello world"
print(myVariable)
var1=1
print(var1)
var2=2
print(var2)
OUTPUT:
KEYWORDS IN PYTHON
Python keywords are reserved words that have a special meaning associated with them
Python has a set of keywords that are reserved words that cannot be used as variable names,
function names, or any other identifiers:
UNIT - I Page 2
PYTHON PROGRAMMING – CCS 62
if import in is
yield
As of Python 3.9.6, there are 36 keywords available. This number can vary slightly over
time.
We can use the following two ways to get the list of keywords in Python
keyword module: The keyword is the buil-in module to get the list of keywords. Also,
this module allows a Python program to determine if a string is a keyword.
help() function: Apart from a keyword module, we can use the help() function to get the
list of keywords
Example: keyword module
import keyword
print(keyword.kwlist)
Output
UNIT - I Page 3
PYTHON PROGRAMMING – CCS 62
All the keywords except, True, False, and None, must be written in a lowercase alphabet symbol.
help("keywords")
Output:
Here is a list of the Python keywords. Enter any keyword to get more help.
STATEMENTS IN PYTHON
In Python, statements are used to instruct the interpreter to perform a specific action. A
statement is a single line of code or a group of lines that perform a specific task. Every line of
code in Python is a statement, and Python programs are essentially a sequence of statements.
There are several types of statements in Python:
Assignment statements: Used to assign values to variables. For example, x = 5 assigns the
value 5 to the variable x.
x=5
y = "hello"
Conditional statements: Used to execute different blocks of code based on a condition. For
example, the if-else statement if x > 10: print("x is greater than 10") else: print("x is less
UNIT - I Page 4
PYTHON PROGRAMMING – CCS 62
than or equal to 10") executes the first block of code if x is greater than 10, and the second
block of code otherwise.
if x > 10:
print("x is greater than 10")
else:
print("x is less than or equal to 10")
Loop statements: Used to execute a block of code repeatedly. For example, the for loop for i in
range(10): print(i) prints the numbers 0 through 9.
for i in range(10):
print(i)
Function definition statements: Used to define a new function. For example, def square(x):
return x * x defines a function called square that takes one argument x and returns its square.
def square(x):
return x * x
Import statements: Used to import modules or specific functions from modules. For example,
import math imports the entire math module, while from random import randint imports the
randint function from the random module.
import math
from random import randint
Class definition statements: Used to define a new class. For example, class MyClass: def
__init__(self, x): self.x = x defines a class called MyClass with a constructor that takes one
argument x and initializes an instance variable called x with its value.
class MyClass:
def __init__(self, x):
self.x = x
def square(self):
return self.x * self.x
EXPRESSIONS IN PYTHON
UNIT - I Page 5
PYTHON PROGRAMMING – CCS 62
1. Constant Expressions: These are the expressions that have constant values only.
Example:
Python3
# Constant Expressions
x = 15 + 1.3
print(x)
Output
16.3
+ x+y Addition
– x–y Subtraction
* x*y Multiplication
/ x/y Division
// x // y Quotient
% x%y Remainder
UNIT - I Page 6
PYTHON PROGRAMMING – CCS 62
** 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
UNIT - I Page 7
PYTHON PROGRAMMING – CCS 62
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
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.
UNIT - I Page 8
PYTHON PROGRAMMING – CCS 62
and P and Q It returns true if both P and Q are true otherwise returns 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
UNIT - I Page 9
PYTHON PROGRAMMING – CCS 62
x = a >> 2
y = a << 1
print(x, y)
Output
3 24
Example:
# Combinational Expressions
a = 16
b = 12
c = a + (b >> 1)
print(c)
Output
22
VARIABLES IN PYTHON
Python Variable is containers which store values. Python is not “statically typed”. A
variable is created the moment we first assign a value to it. A Python variable is a name given to
a memory location. It is the basic unit of storage in a program.
Var = "Geeksforgeeks"
print(Var)
Output:
Geeksforgeeks
UNIT - I Page 10
PYTHON PROGRAMMING – CCS 62
# 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
# display
print( Number)
Output:
100
We can re-declare the python variable once we have declared the variable already.
UNIT - I Page 11
PYTHON PROGRAMMING – CCS 62
# display
print("Before declare: ", Number)
Output:
Before declare: 100
After re-declare: 120.3
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
UNIT - I Page 12
PYTHON PROGRAMMING – CCS 62
a, b, c = 1, 20.2, "GeeksforGeeks"
print(a)
print(b)
print(c)
Output:
1
20.2
GeeksforGeeks
OPERATORS IN PYTHON
The operator is a symbol that performs a certain operation between two operands, according
to one definition. In a particular programming language, operators serve as the foundation upon
which logic is constructed in a programme. The different operators that Python offers are listed
here.
o Arithmetic operators
o Comparison operators
o Assignment Operators
o Logical Operators
o Bitwise Operators
o Membership Operators
o Identity Operators
o Arithmetic Operators
In Python 3.x the result of division is a floating-point while in Python 2.x division of 2
integers was an integer. To obtain an integer result in Python 3.x floored (// integer) is used.
UNIT - I Page 13
PYTHON PROGRAMMING – CCS 62
Modulus: returns the remainder when the first operand is divided by the
% second x%y
x **
** Power: Returns first raised to power second y
Division Operators
Division Operators allow you to divide two numbers and return a quotient, i.e., the first
number or number at the left is divided by the second number or number at the right and returns
the quotient.
Float division
The quotient returned by this operator is always a float number, no matter if two numbers
are integers.
For example:
Output:
1.0
5.0
UNIT - I Page 14
PYTHON PROGRAMMING – CCS 62
-5.0
10.0
The quotient returned by this operator is dependent on the argument being passed. If any
of the numbers is float, it returns output in float. It is also known as Floor division because, if
any number is negative, then the output will be floored.
For example:
Output:
3
-3
2.0
-3.0
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:
UNIT - I Page 15
PYTHON PROGRAMMING – CCS 62
# Addition of numbers
add = a + b
# Subtraction of numbers
sub = a - b
# Multiplication of number
mul = a * b
# Power
p = a ** b
# print results
print(add)
print(sub)
print(mul)
print(mod)
print(p)
Output:
13
5
36
1
6561
> Greater than: True if the left operand is greater than the right x>y
UNIT - I Page 16
PYTHON PROGRAMMING – CCS 62
< Less than: True if the left operand is less than the right x<y
x ==
== Equal to: True if both operands are equal y
Greater than or equal to True if the left operand is greater than or equal to x >=
>= the right y
Less than or equal to True if the left operand is less than or equal to the x <=
<= right y
In python, the comparison operators have lower precedence than the arithmetic operators.
All the operators within comparison operators have same precedence order.
# 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)
UNIT - I Page 17
PYTHON PROGRAMMING – CCS 62
# a >= b is False
print(a >= b)
# a <= b is True
print(a <= b)
Output
False
True
False
True
False
True
Python Logical operators perform Logical AND, Logical OR, and Logical
NOT operations. It is used to combine conditional statements.
Operator Description
and The condition will also be true if the expression is true. If the two expressions a
and b are the same, then a and b must both be true.
or The condition will be true if one of the phrases is true. If a and b are the two
expressions, then an or b must be true if and is true and b is false.
not If an expression a is true, then not (a) will be false and vice versa.
UNIT - I Page 18
PYTHON PROGRAMMING – CCS 62
Logical not
logical and
logical or
# Print a or b is True
print(a or b)
Output
False
True
False
Python Bitwise operators act on bits and perform bit-by-bit operations. These are used to
operate on binary numbers.
Operator Description
& (binary A 1 is copied to the result if both bits in two operands at the same location
and) are 1. If not, 0 is copied.
| (binary or) The resulting bit will be 0 if both the bits are zero; otherwise, the resulting bit
will be 1.
^ (binary xor) If the two bits are different, the outcome bit will be 1, else it will be 0.
UNIT - I Page 19
PYTHON PROGRAMMING – CCS 62
~ (negation) The operand's bits are calculated as their negations, so if one bit is 0, the
next bit will be 1, and vice versa.
<< (left shift) The number of bits in the right operand is multiplied by the leftward shift of
the value of the left operand.
>> (right The left operand is moved right by the number of bits present in the right
shift) operand.
Output
0
14
-11
14
2
40
UNIT - I Page 20
PYTHON PROGRAMMING – CCS 62
Assign the value of the right side of the expression to the left side
= operand x=y+z
Subtract AND: Subtract right operand from left operand and then
-= assign to left operand a-=b a=a-b
Multiply AND: Multiply right operand with left operand and then
*= assign to left operand a*=b a=a*b
Divide AND: Divide left operand with right operand and then
/= assign to left operand a/=b a=a/b
Modulus AND: Takes modulus using left and right operands and a%=b
%= assign the result to left operand a=a%b
UNIT - I Page 21
PYTHON PROGRAMMING – CCS 62
Performs Bitwise right shift on operands and assign value to left a>>=b
>>= operand a=a>>b
Performs Bitwise left shift on operands and assign value to left a <<= b a=
<<= operand a << b
# Assign value
b=a
print(b)
Output
10
20
10
100
102400
UNIT - I Page 22
PYTHON PROGRAMMING – CCS 62
OPERATOR PRECEDENCE: This is used in an expression with more than one operator with
different precedence to determine which operation to perform first.
Example: Solve
10 + 20 * 30
Code:
print(expr)
Output:
610
Example: Now, let‟s see an example on logical „or„ & logical „and„ operator. „if„ block is
executed even if the age is 0. Because precedence of logical „and„ is greater than the logical „or„.
UNIT - I Page 23
PYTHON PROGRAMMING – CCS 62
Output:
Hello! Welcome.
Hence, To run the „else„ block we can use parenthesis( ) as their precedence is highest
among all the operators.
Output:
Good Bye!!
Example: „*‟ and „/‟ have the same precedence and their associativity is Left to Right, so the
expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.
UNIT - I Page 24
PYTHON PROGRAMMING – CCS 62
Code:
# 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)
UNIT - I Page 25
PYTHON PROGRAMMING – CCS 62
Output:
100
6
0
512
Operators Precedence and Associativity are two main characteristics of operators that
determine the evaluation order of sub-expressions in absence of brackets.
Example: Solve
100 + 200 / 10 - 3 * 10
Code:
Output:
90.0
UNIT - I Page 26
PYTHON PROGRAMMING – CCS 62
This table lists all operators from the highest precedence to the lowest precedence.
() Parentheses left-to-right
** Exponent right-to-left
* / % Multiplication/division/modulus left-to-right
+ – Addition/subtraction left-to-right
or Logical OR left-to-right
= Assignment
+= -= Addition/subtraction assignment
*= /= Multiplication/division assignment right-to-left
UNIT - I Page 27
PYTHON PROGRAMMING – CCS 62
A variable can hold different types of values. For example, a person's name must be
stored as a string whereas its id must be stored as an integer.
Python provides various standard data types that define the storage method on each of them.
The data types defined in Python are given below.
1. Numbers
2. Sequence Type
3. Boolean
4. Set
5. Dictionary
UNIT - I Page 28
PYTHON PROGRAMMING – CCS 62
NUMBERS
Number stores numeric values. The integer, float, and complex values belong to a Python
Numbers data-type. Python provides the type() function to know the data-type of the variable.
Similarly, the isinstance() function is used to check an object belongs to a particular class.
Python creates Number objects when a number is assigned to a variable. For example;
1. a = 5
2. print("The type of a", type(a))
3. b = 40.5
4. print("The type of b", type(b))
5. c = 1+3j
6. print("The type of c", type(c))
7. print(" c is a complex number", isinstance(1+3j,complex))
Output:
1. Int - Integer value can be any length such as integers 10, 2, 29, -20, -150 etc. Python has
no restriction on the length of an integer. Its value belongs to int
2. Float - Float is used to store floating-point numbers like 1.9, 9.902, 15.2, etc. It is
accurate upto 15 decimal points.
3. complex - A complex number contains an ordered pair, i.e., x + iy where x and y denote
the real and imaginary parts, respectively. The complex numbers like 2.14j, 2.0 + 2.3j,
etc.
Python numeric data types store numeric values. Number objects are created when you assign a
value to them. For example −
var1 = 1
var2 = 10
var3 = 10.023
UNIT - I Page 29
PYTHON PROGRAMMING – CCS 62
Example
Following is an example to show the usage of Integer, Float and Complex numbers:
# integer variable.
a=100
print("The type of variable having value", a, " is ", type(a))
# float variable.
b=20.345
print("The type of variable having value", b, " is ", type(b))
# complex variable.
c=10+3j
print("The type of variable having value", c, " is ", type(c))
STRING
The string can be defined as the sequence of characters represented in the quotation
marks. In Python, we can use single, double, or triple quotes to define a string.
In the case of string handling, the operator + is used to concatenate two strings as the
operation "hello"+" python" returns "hello python".
Example - 1
UNIT - I Page 30
PYTHON PROGRAMMING – CCS 62
3. s = '''''A multiline
4. string'''
5. print(s)
Output:
Example - 2
Output:
he
o
hello javatpointhello javatpoint
hello javatpoint how are you
BOOLEAN
Boolean type provides two built-in values, True and False. These values are used to
determine the given statement true or false. It denotes by the class bool. True can be represented
by any non-zero value or 'T' whereas false can be represented by the 0 or 'F'. Consider the
following example.
UNIT - I Page 31
PYTHON PROGRAMMING – CCS 62
Output:
<class 'bool'>
<class 'bool'>
NameError: name 'false' is not defined
Examples
Following is a program which prints the value of boolean variables a and b −
a = True
# display the value of a
print(a)
# display the data type of a
print(type(a))
Following is another program which evaluates the expressions and prints the return values:
# Returns false as a is not equal to b
a=2
b=4
print(bool(a==b))
# Following also prints the same
print(a==b)
# Returns False as a is None
a = None
print(bool(a))
# Returns false as a is an empty sequence
a = ()
print(bool(a))
UNIT - I Page 32
PYTHON PROGRAMMING – CCS 62
# Returns false as a is 0
a = 0.0
print(bool(a))
# Returns false as a is 10
a = 10
print(bool(a))
INDENTATION IN PYTHON
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.
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.
UNIT - I Page 33
PYTHON PROGRAMMING – CCS 62
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.
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 !
Example 2
To indicate a block of code in Python, you must indent each line of the block by the same
whitespace. The two lines of code in the while loop are both indented four spaces. It is required
for indicating what block of code a statement belongs to. For example, j=1 and while(j<=5): is
not indented, and so it is not within the Python while block. So, Python code structures by
indentation.
j=1
while(j<= 5):
print(j)
j=j+1
Output:
1
2
3
UNIT - I Page 34
PYTHON PROGRAMMING – CCS 62
4
5
COMMENTS IN PYTHON
In Python, comments are used to add explanations or annotations to the code. They are
ignored by the interpreter and do not affect the execution of the program. There are two types of
comments in Python: single-line comments and multi-line comments.
Single-line comments: These are comments that occupy only one line in the code. They are
created by using the hash symbol (#) at the beginning of the line. Any text following the hash
symbol on that line is considered a comment and is ignored by the interpreter.
Example :
# This is a single-line comment
print("Hello, World!") # This is another single-line comment
OUTPUT :
Multi-line comments: These are comments that span multiple lines in the code. They are
created by enclosing the text of the comment in triple quotes (""") at the beginning and end of the
comment.
Example :
"""
"""
print("Hello, World!")
UNIT - I Page 35
PYTHON PROGRAMMING – CCS 62
OUTPUT :
Multi-line comments are often used to provide documentation for functions, classes, and
modules. They can be accessed using the __doc__ attribute of the object.
For example, consider the following function with a docstring:
Example :
def add_numbers(x, y):
"""
This function adds two numbers and returns the result.
"""
return x + y
You can access the docstring of the above function using the __doc__ attribute:
Example :
print(add_numbers.__doc__)
OUTPUT :
In Python, you can use the input() function to read input from the user and the print()
function to display output to the user.
Reading input:
The input() function allows the user to enter a value from the keyboard. The value
entered by the user is returned as a string. If you need to use the entered value as an integer or
float, you can convert it using the int() or float() function.
Example :
UNIT - I Page 36
PYTHON PROGRAMMING – CCS 62
OUTPUT :
Printing output:
The print() function is used to display output to the user. You can pass one or more
values to the print() function, separated by commas, to display them on the screen. By default,
the print() function adds a newline character at the end of the output. You can change this
behavior by specifying the end parameter.
Example :
name = "John"
age = 25
height = 1.75
print("Name:", name, "Age:", age, "Height:", height)
print("Name: " + name + ", Age: " + str(age) + ", Height: " + str(height))
print("Name: {}\nAge: {}\nHeight: {}".format(name, age, height))
OUTPUT :
UNIT - I Page 37
PYTHON PROGRAMMING – CCS 62
In the first example, we use commas to separate the values and let print() handle the
formatting.
In the second example, we concatenate the values using string concatenation and convert
the integer and float values to strings using the str() function.
In the third example, we use the format() method to format the output. The curly braces
{} are replaced with the corresponding values passed to the format() method. The \n character is
used to add a newline after each value.
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:
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'>
UNIT - I Page 38
PYTHON PROGRAMMING – CCS 62
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.
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.
# initializing string
s = "10010"
Output:
After converting to integer base 2 : 18
After converting to float : 10010.0
UNIT - I Page 39
PYTHON PROGRAMMING – CCS 62
# initializing integer
s = '4'
Output:
After converting character to integer : 52
After converting 56 to hexadecimal string : 0x38
After converting 56 to octal string : 0o70
UNIT - I Page 40
PYTHON PROGRAMMING – CCS 62
# initializing string
s = 'geeks'
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.
# initializing integers
a=1
b=2
# initializing tuple
UNIT - I Page 41
PYTHON PROGRAMMING – CCS 62
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.
print(a)
print(b)
Output:
L
M
Python type() returns the type of the specified object if a single argument is passed to the
type(). If three arguments are passed, it returns a new type of object.
UNIT - I Page 42
PYTHON PROGRAMMING – CCS 62
Signature
Parameters
object: The type() returns the type of this object if one parameter is specified.
dict (optional): It specifies the namespace with the definition for the class.
Return
It returns the type of the specified object if a single argument is passed to the type(). If
three arguments are passed, it returns a new type of object.
1. List = [4, 5]
2. print(type(List))
3. Dict = {4: 'four', 5: 'five'}
4. print(type(Dict))
5. class Python:
6. a=0
7. InstanceOfPython = Python()
8. print(type(InstanceOfPython))
Output:
<class 'list'>
<class 'dict'>
<class '__main__.Python'>
In the above example, we have taken a List that contains some values, and in return, it
prints the type of the List.
In the second case, we have taken a Dict that contains some values, and in return, it prints
the type of the Dict.
UNIT - I Page 43
PYTHON PROGRAMMING – CCS 62
IS OPERATORS IN PYTHON
In Python, is and is not operators are called identity operators. Each object in computer's
memory is assigned a unique identification number (id) by Python interpreter. ]
Identity operators check if id() of two objects is same. 'is' operator returns false of id() values are
different and true if they are same.
The is operator is used to test whether two variables or objects refer to the same object in
memory. For example:
x = [1, 2, 3]
y = [1, 2, 3]
z=x
It is important to note that the is operator tests for identity (whether two objects are the
same object in memory), while the == operator tests for equality (whether two objects have the
same value).
Example :
>>> a=10
>>> b=a
>>> id(a), id(b)
(490067904, 490067904)
>>> a is b
True
>>> a=10
>>> b=20
>>> id(a), id(b)
UNIT - I Page 44
PYTHON PROGRAMMING – CCS 62
(490067904, 490068064)
>>> a is b
False
Python is a dynamically typed language, which means that the type of a variable is
determined at runtime, based on the value that is assigned to it. This allows for more flexibility
and ease of use, as variables can be reassigned to different types throughout the program.
x=5
print(type(x)) # Output: <class 'int'>
x = "hello"
print(type(x)) # Output: <class 'str'>
In this example, the variable x is assigned an integer value at first, but later it is
reassigned a string value. This is possible because Python is dynamically typed and does not
require the type of the variable to be declared ahead of time.
Python is also a strongly typed language, which means that the type of a variable is
enforced at all times. This means that operations performed on variables must be compatible
with their data types, and Python will not automatically convert the data types for you.
For example, the following code will result in a TypeError because Python cannot add a
string and an integer together:
x=5
y = "hello"
print(x + y) # Output: TypeError: unsupported operand type(s) for +: 'int' and 'str'
In this example, Python enforces strong typing and does not allow adding an integer and
a string together. This is because the two data types are not compatible and cannot be
automatically converted.
UNIT - I Page 45