Python Programming Unit-1
Python Programming Unit-1
Python Basics
Python Objects:
Python uses the object model abstraction for data storage. Any construct which contains
any type of value is an object. Although Python is classified as an "object-oriented
programming language," OOP is not required to create perfectly working Python
applications. You can certainly write a useful Python script without the use of classes
and instances.
All Python objects have the following three characteristics: an identity, a type, and a
value.
IDENTITY: Unique identifier that differentiates an object from all others. Any object's
identifier can be obtained using the id() built-in function. This value is as close as you
will get to a "memory address" in Python.
TYPE: An object's type indicates what kind of values an object can hold, what
operations can be applied to such objects, and what behavioral rules these objects are
subject to. You can use the type() built-in function to reveal the type of a Python object.
VALUE: Data item that is represented by an object.
Standard Types:
Python is a dynamically typed language, meaning variables are not explicitly declared
with a data type. Instead, the data type is inferred at runtime based on the value assigned.
Python provides a rich set of standard data types that make it easy to work with different
kinds of data.
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, Python data types are classes and
variables are instances (objects) of these classes. The following are the standard or built-
in data types in Python:
1. Numeric Types:
These are used to represent numbers.
Integer type (int): This value is represented by int class. It contains positive or negative
whole numbers (without fractions or decimals). In Python, there is no limit to how long
an integer value can be.
Example: 5, -10, 100
Floating-point type (float): This value is represented by the float class. It is a real
number with a floating-point representation. It is specified by a decimal point.
Example: 3.14, -0.001, 2.0
Complex Numbers (complex): A complex number is represented by a complex class.
It is specified as (real part) + (imaginary part)j
Example: 3 + 4j
2. Sequence Types:
The sequence Data Type in Python is the ordered collection of similar or different
Python data types. Sequences allow storing of multiple values in an organized and
efficient fashion. There are several sequence data types of Python:
String (str): Python Strings are arrays of bytes representing Unicode characters. In
Python, there is no character data type Python, a character is a string of length one. It is
represented by str class. Strings in Python can be created using single quotes, double
quotes, or even triple quotes.
Example: "hello", 'Python'
list: A list is a built-in dynamic sized array (automatically grows and shrinks) that is
used to store an ordered collection of items. A list can hold elements of different types.
Example: [1, 2, 'apple', 3.5]
tuple: An immutable sequence of items. Just like a list, a tuple is also an ordered
collection of Python objects and can hold elements of different types. The only
difference between a tuple and a list is that tuples are immutable. Tuples cannot be
modified after it is created.
Example: (1, 2, 3)
range: A Python range is an immutable sequence of numbers which is typically used
to iterate through a specific number of items. It is represented by the Range class. The
constructor of this class accepts a sequence of numbers starting from 0 and increments
to 1 until it reaches a specified number.
Example: range(5) produces 0, 1, 2, 3, 4
3. Set Types:
Sets are unordered collections of unique items.
set: Mutable and unordered, no duplicate elements.
Example: {1, 2, 3, 3} becomes {1, 2, 3}
4. Mapping Type:
Mappings store key-value pairs.
dict: A dictionary in Python is an unordered collection of data values, used to store data
values like a map, unlike other Python Data Types that hold only a single value as an
element, a Dictionary holds a key: value pair. A dictionary can be mutable. Values in a
dictionary can be of any datatype and can be duplicated.
Example: {'key': 'value', 'age': 25}
5. Boolean Type:
Python boolean type is one of built-in data types which represents one of the two values
either True or False.
bool: Boolean values are True or False.
Example: True, False
6. Binary Types:
A binary data type in Python is a way to represent data as a series of binary digits, which
are 0's and 1's. It is like a special language computers understand to store and process
information efficiently.
bytes: Immutable sequence of bytes. The byte data type in Python represents a sequence
of bytes. Each byte is an integer value between 0 and 255. It is commonly used to store
binary data, such as images, files, or network packets.
Example: b'hello'
b1 = bytes([65, 66, 67, 68, 69])
print(b1)
The result obtained is as follows −
b'ABCDE'
bytearray:
Mutable sequence of bytes. The bytearray data type in Python is quite similar to the
bytes data type, but with one key difference: it is mutable, meaning you can modify the
values stored in it after it is created.
Example: bytearray(b'hello')
memoryview:
A view of memory for binary data. In Python, a memoryview is a built-in object that
provides a view into the memory of the original object, generally objects that support
the buffer protocol, such as byte arrays (bytearray) and bytes (bytes).
Example:
data = bytearray(b'Hello, world!')
view = memoryview(data)
print(view)
7. None Type:
Represents the absence of a value or a null value.
NoneType: Used as a placeholder for "no value."
Example: None
Other Built-in Types:
Type
File
Function
Module
Class
Class Instance or Object
Method
These are some of the other types you will interact with as you develop as a Python
programmer.
Internal Types:
We will briefly introduce these internal types here. The general application programmer
would typically not interact with these objects directly, but we include them here for
completeness.
Code
Frame
Traceback
Slice
Ellipsis
Xrange
In case you were wondering about exceptions, they are now implemented as classes not
types. In older versions of Python, exceptions were implemented as strings.
Code Objects:
Code objects are executable pieces of Python source that are byte-compiled, usually as
return values from calling the compile() built-in function or Code objects Represents
compiled bytecode of a Python function and Contains information like bytecode,
constants, and variable names. Such objects are appropriate for execution by either exec
or by the eval() built-in function.
Frames:
These are objects representing execution stack frames in Python. Frame objects contain
all the information the Python interpreter needs to know during a runtime execution
environment. Some of its attributes include a link to the previous stack frame, the code
object (see above) that is being executed, dictionaries for the local and global
namespaces, and the current instruction. Each function call results in a new frame
object, and for each frame object, a stack frame is created as well. One place where you
can access a frame object is in a traceback object.
Tracebacks:
When you make an error in Python, an exception is raised. If exceptions are not caught
or "handled," the interpreter exits with some diagnostic information similar to the output
shown below:
Traceback (innermost last):
File "<stdin>", line N?, in ???
ErrorName: error reason
The traceback object is just a data item that holds the stack trace information for an
exception and is created when an exception occurs. If a handler is provided for an
exception, this handler is given access to the traceback object.
Slice Objects:
Slice objects are created when using the Python extended slice syntax. This extended
syntax allows for different types of indexing. These various types of indexing include
stride indexing, multi-dimensional indexing, and indexing using the Ellipsis type. The
syntax for multi-dimensional indexing is sequence[start1 : end1, start2 : end2], or using
the ellipsis, sequence[…, start1 : end1]. Slice objects can also be generated by the slice()
built-in function. Extended slice syntax is currently supported only in external third
party modules such as the NumPy module and JPython.
Stride indexing for sequence types allows for a third slice element that allows for "step"-
like access with a syntax of sequence[starting_index : ending_index : stride].
Example:
>>> foostr = 'abcde'
>>> foostr[::-1]
'edcba'
>>> foostr[::-2]
'eca'
>>> foolist = [123, 'xba', 342.23, 'abc']
>>> foolist[::-1]
['abc', 342.23, 'xba', 123]
Ellipsis:
The Ellipsis object in Python is represented by three dots (...). It is a singleton object of
the type EllipsisType. Like the Null object, ellipsis objects also have a single name,
Ellipsis, and has a Boolean true value at all times.
Ellipsis is often used as a placeholder for incomplete code or data. This indicates that
some part of the implementation is intentionally left blank.
Example:
def calculate_average(numbers):
Xrange:
In Python 2, xrange was a built-in function that provided a way to generate a sequence
of numbers lazily, as opposed to range, which generated the entire list of numbers in
memory.
Key Differences Between range in Python 3 and xrange in Python 2
Feature Python 2 xrange Python 3 range
Type xrange object range object
Lazy Evaluation Yes Yes
Memory Usage Efficient Efficient
Supports Slicing No Yes
Ex:
a=10
b=2
print(a+b)
print(a-b)
print(a*b)
print(a/b)
print(a//b)
print(a%b)
print(a**b)
Output:
12
8
20
5.0
5
0
100
Ex:
a=10.5
b=2
print(a/b)
print(a//b)
Output:
5.25
5.0
// Returns int if both values are int. Returns float, if at least one is float.
/ Always returns float.
+ It can be applied for str type also, which is considered as string concatenation
operator. If we are applying + to strings, both values should be strings.
Ex:
>>> 'cyber'+3
TypeError: can only concatenate str (not "int") to str
>>> 'cyber'+'3'
'cyber3'
>>> 'cyber'+ str(3)
'cyber3'
*It can be applied for str type also. If we applying * to strings, then one value should be
int and other value should be str type.
Ex:
>>> 2*'cyber'
'cybercyber’
>>> 'cyber'*2
'cybercyber'
>>> 'cyber'*2.0
TypeError: can't multiply sequence by non-int of type 'float'
Ex:
Expression Description
10/0 ZeroDivisionError: division by zero
10/0.0 ZeroDivisionError: float division by zero
10%0 ZeroDivisionError: integer division or modulo by zero
10//0 ZeroDivisionError: integer division or modulo by zero
0/0 ZeroDivisionError: division by zero
0.0/0 ZeroDivisionError: float division by zero
0/0.0 ZeroDivisionError: float division by zero
0//0.0 ZeroDivisionError: float divmod()
0.0//0 ZeroDivisionError: float divmod()
10**0 1
Ex:
a=10
b=20
print('a>b',a>b)
print('a<b',a<b)
print('a>=b',a>=b)
print('a<=b',a<=b)
print('a==b',a==b)
print('a!=b',a!=b)
Output:
a>b False
a<b True
a>=b False
a<=b True
a==b False
a!=b True
Output:
a>b: True
a<b: False
a>=b: True
a<=b: False
a==b: False
a!=b: True
Here, it will compare Unicode of the individual characters of the strings. So, first it will
compare s and r. According to Unicode, r's Unicode is less than s's Unicode.
If both characters are same, then it will check next character and so on.
Ex:
a='siva'
b='shiva'
print('a>b:',a>b)
print('a<b:',a<b)
print('a>=b:',a>=b)
print('a<=b:',a<=b)
print('a==b:',a==b)
print('a!=b:',a!=b)
Output:
a>b: True
a<b: False
a>=b: True
a<=b: False
a==b: False
a!=b: True
First it will compare s and s, both are same. So, it will compare i's Unicode and h's
Unicode.
Python is case sensitive. So, upper case and lower case characters will have
different unicodes.
Ex:
a='SIVA'
b='siva'
print('a>b:',a>b)
print('a<b:',a<b)
print('a>=b:',a>=b)
print('a<=b:',a<=b)
print('a==b:',a==b)
print('a!=b:',a!=b)
Output:
a>b: False
a<b: True
a>=b: False
a<=b: True
a==b: False
a!=b: True
3) Logical Operators:
Logical operators are the and, or, not operators. We can apply these operators for all
types.
Ex:
>>> True and False
False
>>> True or False
True
>>> not True
False
Ex:
>>> 10 and 20
20
>>> 0 and 10
0
>>> 10 and 0
0
>>> 10 and 20
20
>>> 0 and 20
0
>>> 10 and 'cyber'
'cyber'
>>> 0 and 'cyber'
0
>>> 'cyber' and 'security'
'security'
Ex:
>>> 10 or 20
10
>>> 0 or 20
20
>>> 0 or True
True
>>> '' or 'cyber'
'cyber'
>>> 'cyber' or 'security'
''cyber''
>>> 10 or 10/0
10
>>> 0 or 10/0
ZeroDivisionError: division by zero
Ex:
>>> not 10
False
>>> not 0
True
>>> not ''
True
>>> not 'cyber'
False
4) Bitwise Operators:
Bitwise operators act on operands as if they were strings of binary digits. They operate
bit by bit, as name indicates bitwise. These operators are applicable only for int and
boolean types.
Operator Meaning Example(x=10,y=4)
& Bitwise AND x & y = 0 (0000 0000)
| Bitwise OR x | y = 14 (0000 1110)
~ Bitwise NOT ~x = -11 (1111 0101)
^ Bitwise XOR x ^ y = 14 (0000 1110)
>> Bitwise right shift x >> 2 = 2 (0000 0010)
<< Bitwise left shift x << 2 = 40 (0010 1000)
Ex:
>>> 4&5
4
>>> 4|5
5
>>> 4^5
1
>>> 10&10.5
TypeError: unsupported operand type(s) for &: 'int' and 'float'
>>> True & True
True
bitwise complement(~):
We have apply complement for all the bits.
The most significant bit acts as sign bit. 0 value represents +ve number where as 1
represents -ve value.
Positive numbers will be represented directly in the memory where as negative numbers
will be represented indirectly in 2's complement form.
Ex:
>>> ~4
-5
Explanation:
4 0000---------100
~4 1111---------011 Here first 1 represent sign, it is negative. Negative values
can not represented directly in memory. So, convert only the value to 2’s complement
form.
~4111---------011
1’s complement is 000------100
2’s complement is 000------101
The value is 5, now add –ve sign to this. So answer is -5.
Shift Operators:
Left shift operator(<<): After left shift the empty locations will be filled with 0.
Ex:
>>> 10<<2
40
Right shift operator(>>): After shifting the empty cells we have to fill with sign bit.
(0 for +ve and 1 for -ve).
Ex:
>>> 10>>2
2
5) Assignment Operators:
Assignment operators are used in Python to assign values to variables.
Ex:
a=10
a,b,c,d=10,20,30,40
There are various compound operators in Python.
Operator Example Equivalent to
= x=5 x=5
+= x += 5 x=x+5
-= x -= 5 x=x-5
*= x *= 5 x=x*5
/= x /= 5 x=x/5
%= x %= 5 x=x%5
//= x //= 5 x = x // 5
**= x **= 5 x = x ** 5
&= x &= 5 x=x&5
|= x |= 5 x=x|5
^= x ^= 5 x=x^5
>>= x >>= 5 x = x >> 5
<<= x <<= 5 x = x << 5
6) Special Operators:
Python language offers some special types of operators like :
i) Identity operators.
ii) Membership operators
i) Identity operators:
is and is not are the identity operators in Python. They are used to check if two values
(or variables) are located on the same part of the memory or not. Two variables that are
equal does not imply that they are identical.
Operator Meaning Example
is True if the operands are identical (refer to the x is True
same object)
is not True if the operands are not identical (do not x is not True
refer to the same object)
Ex:
l1=[10,20,30]
l2=[10,20,30]
print('Id of l1:',id(l1))
print('Id of l2:',id(l2))
print('l1 is l2:',l1 is l2)
print('l1 is not l2:',l1 is not l2)
print('l1 == l2:',l1 == l2)
Output:
Id of l1: 42403240
Id of l2: 15323272
l1 is l2: False
l1 is not l2: True
l1 == l2: True
Here in list, individual objects will have same address if they are same, but lists will not
have same address, if the values of list are same.
Ex:
a='cyber'
b='cyber'
print('Id of a:',id(a))
print('Id of b:',id(b))
print('a is b:',a is b)
Output:
Id of a: 42569952
Id of b: 42569952
a is b: True
Ex:
list1=[10,20,30,4,50]
print('10 in list1:',10 in list1)
print('70 in list1:',70 in list1)
print('100 not in list1:',100 not in list1)
Output:
10 in list1: True
70 in list1: False
100 not in list1: True
Ex:
string='Hi,CYBER SECURITY DEPARTMENT’
print('h' in string)
print('cyber' in string)
print('CYBER' in string)
print('cyber' not in string)
print('SECURITY' not in string)
print('k' in string)
Output:
False
False
True
True
False
False
>>> str(4.53-2j)
'(4.53-2j)'
>>>
>>> str(1)
'1'
>>>>>> str(2e10)
'20000000000.0'
>>>
>>> str([0, 5, 9, 9])
'[0, 5, 9, 9]'
>>>
>>> repr([0, 5, 9, 9])
'[0, 5, 9, 9]'
>>>
>>> `[0, 5, 9, 9]`
'[0, 5, 9, 9]'
type():
The type() returns the type for any Python object, not just the standard types.
Example:
>>> type('')
<type 'string'>
>>>
>>> s = 'xyz'
>>>
>>> type(s)
<type 'string'>
>>>
>>> type(100)
<type 'int'>
>>>
>>> type(-2)
<type 'int'>
>>>
>>> type(0)
<type 'int'>
>>>
>>> type(0+0j)
<type 'complex'>
>>>
>>> type(0L)
<type 'long int'>
>>>
>>> type(0.0)
<type 'float'>
>>>
>>> type([])
<type 'list'>
>>>
>>> type(())
<type 'tuple'>
>>>
>>> type({})
<type 'dictionary'>
>>>
>>> type(type)
<type 'builtin_function_or_method'>
>>>
>>> type(Abc)
<type 'class'>
>>>
>>> type(Abc_obj)
<type 'instance'>
Update Model:
Another way of categorizing the standard types is by asking the question, "Once created,
can objects be changed or their values updated?" When we introduced Python types
early on, we indicated that certain types allow their values to be updated and others do
not. Mutable objects are those whose values can be changed, and immutable objects are
those whose values cannot be changed.
Bellow Table illustrates which types support updates and which do not.
Types categorized by the Update Model
Update model category Python types that fit category
mutable lists, dictionaries
immutable numbers, strings, tuples
Example:
x = 'Python numbers and strings'
print id(x)
x = 'are immutable?!? What gives?'
print id(x)
i=0
print id(i)
i=i+1
print id(i)
Output:
16191392
16191232
7749552
7749600
Rather than pointing to the original objects, new objects with the new values were
allocated and (re)assigned to the original variable names, and the old objects were
garbage-collected. One can confirm this by using the id() built-in function to compare
object identities before and after such assignments.
On the other side, lists can be modified without replacing the original object, as
illustrated in the code below.
>>> aList = [ 'ammonia', 83, 85, 'lady' ]
>>> aList
['ammonia', 83, 85, 'lady']
>>>
>>> aList[2]
85
>>>
>>> id(aList)
135443480
>>>
>>> aList[2] = aList[2] + 1
>>> aList[3] = 'stereo'
>>> aList
['ammonia', 83, 86, 'stereo']
>>>
>>> id(aList)
135443480
Notice how for each change, the ID for the list remained the same.
Access Model:
Although the previous two models of categorizing the types are useful when being
introduced to Python, they are not the primary models for differentiating the types. For
that purpose, we use the access model. By this, we mean, how do we access the values
of our stored data? There are three categories under the access model: direct, sequence,
and mapping. The different access models and which types fall into each respective
category are given in bellow Table.
Types categorized by the Access Model
access model category Python types that fit category
direct numbers
sequence strings, lists, tuples
mapping dictionaries
Direct types indicate single element, non-container types. All numeric types fit
into this category.
Sequence types are those whose elements are sequentially-accessible via index
values starting at 0. Accessed items can be either single elements or in groups,
better known as slices. Types which fall into this category include strings, lists,
and tuples.
Mapping types are similar to the indexing properties of sequences, except instead
of indexing on a sequential numeric offset, elements (values) are unordered and
accessed with a key, thus making mapping types a set of hashed key-value pairs.
Unsupported Types:
Boolean
Unlike Pascal or Java, Python does not feature the Boolean type (Boolean type (bool)
was introduced in Python version 2.3). Use integers instead.
char or byte
Python does not have a char or byte type to hold either single character or 8-bit integers.
Use strings of length one for characters and integers for 8-bit numbers. (bytes type was
introduced in Python 3.0.)
pointer
Since Python manages memory for you, there is no need to access pointer addresses.
The closest to an address that you can get in Python is by looking at an object's identity
using the id() built-in function. Since you have no control over this value, it's a moot
point.
int vs. short vs. long
Python's plain integers are the universal "standard" integer type, obviating the need for
three different integer types, i.e., C's int, short, and long. For the record, Python's
integers are implemented as C longs. For values larger in magnitude than regular
integers (usually your system architecture size, i.e., 32-bit), use Python's long integer.
float vs. double
C has both a single precision float type and double-precision double type. Python's float
type is actually a C double. Python does not support a single-precision floating point
type because its benefits are outweighed by the overhead required to support two types
of floating point types.
Numbers:
Introduction to Numbers:
Numbers provide literal or scalar storage and direct access. Numbers are also an
immutable type, meaning that changing or updating its value results in a newly allocated
object. This activity is, of course, transparent to both the programmer and the user, so
it should not change the way the application is developed.
Python has four types of numbers: "plain" integers, long integers, floating point real
numbers, and complex numbers.
Integers:
Python has two types of integers. Plain integers are the generic vanilla (32-bit) integers
recognized on most systems today. Python also has a long integer size; however, these
far exceed the size provided by C longs.
(Plain) Integers:
Python's "plain" integers are the universal numeric type. Most machines (32-bit)
running Python will provide a range of -231 to 231-1, that is -2,147,483,648 to
2,147,483,647. Here are some examples of Python integers:
i) Binary:
It uses two values 0 and 1. It uses Base-2(0,1). Binary literal should be prefixed with 0b
or 0B.
Ex:
a=0b1001
b=0B1010
c=1010 #not in binary
d=-0b1111
#e=0b1211#Error
print(a)
print(b)
print(c)
print(d)
Output:
9
10
1010
-15
ii) Octal:
It uses eight values 0 to 7. It uses Base-8(0-7). Octal literal should be prefixed with 0o
or 0O.
Ex:
a=0o10
b=0O12
c=12 #not in octal
d=-0o15
#e=0o128#Error
print(a)
print(b)
print(c)
print(d)
Output:
8
10
12
-13
iii) Decimal:
It uses ten values 0 to 9.It uses Base-10(0-9).Decimal literal can be represented without
any prefix. Leading zeros in decimal integer literals are not permitted.
Ex:
a=10
print(a)
iv) Hexadecimal:
It uses sixteen values 0 to 9 ,a to f (or) A to F .It uses Base-16(0-9,A-F).Hexadecimal
literal should be prefixed with 0x or 0X
Ex:
a=0x1a
b=0XFace
c=0xabcd123
d=-0X1a2bcd
#e=0xfan #Error
#f=ox123 #Error
print(a)
print(b)
print(c)
print(d)
Output:
26
64206
180146467
-1715149
Note: we can specify literal values in decimal, binary, octal and hexa decimal forms.
But Python Virtual Machine will always provide values only in decimal form only.
Long Integers:
The first thing we need to say about Python long integers is to not get them confused
with long integers in C or other compiled languages—these values are typically
restricted to 32- or 64-bit sizes, whereas Python long integers are limited only by the
amount of (virtual) memory in your machine.
Long integers are a superset of integers and are useful when the range of plain integers
exceeds those of your application, meaning less than -231 or greater than 231-1. Use of
long integers is denoted by an upper- or lowercase (L) or (l), appended to the integer's
numeric value. Values can be expressed in decimal, octal, or hexadecimal. The
following are examples of long integers:
16384L -0x4E8L 017L -2147483648l 052144364L
Complex Numbers:
The concept of complex numbers was introduced to address the limitations of real
numbers in solving certain mathematical problems.
The Problem with Real Numbers:
Mathematics in the early days focused on real numbers, which include integers,
fractions, and irrational numbers. These were sufficient for many practical purposes.
However, problems arose with equations like:
x2+1=0
This equation implies: x2 = -1
The square of any real number is non-negative, so there is no real number x that satisfies
this equation. In other words, the reason for this is because any real number (positive or
negative) multiplied by itself results in a positive number. How can you multiply any
number with itself to get a negative number? No such real number exists. This led
mathematicians to question how to make sense of the square root of a negative number.
Introduction of i:
In the eighteenth century, mathematicians invented something called an imaginary
number i (or j) such that:
Using i, the square root of any negative number could be written as:
Now, if x is initialized to 15, then new object will be created for x. y and z will refer to
old object only.
print(y is z) True
print(x is y) False
For int type, reusing same object is applicable only from 0 to 256 values. If we use 257
or high values, then reusing of object is not applicable.
Ex:
x=256
y=256
print(x is y) True
Ex:
x=257
y=257
print(x is y) False
print(id(x)) Returns different addresses
print(id(y))
Ex:
a=10+20j
b=10+20j
id(a) Returns different addresses.
id(b)
Reusability of object is applicable for str type.
Ex:
s1= ‘siva'
s2= 'siva'
id(s1) Returns same addresses.
id(s2)
Built-in Functions:
Standard Type Functions:
In the previous section, we introduced the cmp(), str(), and type() built-in functions
that apply for all standard types.
Numeric Type Functions:
Python currently supports different sets of built-in functions for numeric types. Some
convert from one numeric type to another while others are more operational, performing
some type of calculation on their numeric arguments.
Conversion
The int(), long(), float(), and complex() built-in functions are used to convert from any
numeric type to another.
Function Description
int() Returns an integer number
long() Returns an long integer number
float() Returns a floating point number
complex() Returns a complex number
Examples:
>>> int(4.25555)
4
>>> long(42)
42L
>>> float(4)
4.0
>>> complex(4)
(4+0j)
>>>
>>> complex(2.4, -8)
(2.4-8j)
Operational
Python has five operational built-in functions for numeric types: abs(), coerce(),
divmod(), pow(), and round().
Function Description
abs( num ) returns the absolute value of num
divmod( num1,num2 ) division-modulo combination returns (num1 / num2,
num1 %
num2) as a tuple. For floats and complex, the quotient is
rounded down
pow( num1, num2,mod raises num1 to num2 power, quantity modulo mod if
=1) provided
round( flt, ndig=0) (floats only) takes a float flt and rounds it to ndig digits,
defaulting to zero if not provided
abs():
abs() returns the absolute value of the given argument. If the argument is a complex
number, 𝑧=𝑎+𝑏j, where 𝑎 is the real part and 𝑏 is the imaginary part, the absolute value
is computed as: math.sqrt( num. real2 + num. imag2) or
divmod():
The divmod() built-in function combines division and modulus operations into a single
function call that returns the pair (quotient, remainder) as a tuple. For floats, the quotient
returned is math.floor( num1/num2 ) and for complex numbers, the quotient is
math.floor(( num1/num2 ).real).
divmod(a, b)
Parameters:
a: The dividend (number to be divided).
b: The divisor (number by which the dividend is divided)
pow():
The pow() function in Python is a built-in function used for exponentiation. It can
compute the power of a number and, optionally, the modulus of the result.
pow(base, exp[, mod])
Parameters:
base: The base number.
exp: The exponent to which the base is raised.
mod (optional): The modulus. If provided, the result will be (base ** exp) % mod
Returns:
pow(2, 3) returns 8
pow(2, 3, 5) returns 3
pow(2, -3) returns 0.125
>>> pow(3.141592, 2)
9.86960029446
round():
The round() built-in function has a syntax of round (flt,ndig=0). It normally rounds a
floating point number to the nearest integral number and returns that result (still) as a
float. When the optional third ndig option is given, round() will round the argument to
the specific number of decimal places.
>>> round(3)
3.0
>>> round(3.45)
3.0
>>> round(3.4999999)
3.0
>>> round(3.4999999, 1)
3.5
>>> round(4.6)
5.0
>>> round(4.678, 2)
4.68 // 4.678 is rounded to two decimal places, resulting in 4.68
>>>round(12345, -2)
12300 // Rounding 12345 to the nearest hundred gives 12300
Integer-only Functions:
In addition to the built-in functions for all numeric types, Python supports a few that are
specific only to integers (plain and long). These functions fall into two categories, base
presentation with hex() and oct(), and ASCII conversion featuring chr() and ord().
Function Description
hex( num ) converts num to hexadecimal and return as string
oct( num ) converts num to octal and return as string
chr( num ) takes ASCII value num and returns ASCII character as
string; 0 <= num <=255 only
ord( chr ) takes ASCII chr and returns corresponding ordinal
ASCII value; chr must be a string of length 1
Base Representation:
Python integers automatically support octal and hexadecimal representations in addition
to the decimal standard. Also, Python has oct() and hex() built-in functions. They both
take an integer (in any representation) object and return a string with the corresponding
value. The following are some examples of their usage:
>>> hex(255)
'0xff'
>>> hex(23094823l)
'0x1606627L'
>>> hex(65535*2)
'0x1fffe'
>>>hex(-42)
'-0x2a'
>>> oct(255)
'0377'
>>> oct(23094823l)
'0130063047L'
>>> oct(65535*2)
'0377776'
ASCII Conversion:
Python also provides functions to go back and forth between ASCII (American Standard
Code for Information Interchange) characters and their ordinal integer values. Each
character is mapped to a unique number in a table numbered from 0 to 255. This number
does not change for all computers using the ASCII table, providing consistency and
expected program behavior across different systems. chr() takes a single-byte integer
value and returns a one-character string with the equivalent ASCII character. ord() does
the opposite, taking a single ASCII character in the form of a string of length one and
returns the corresponding ASCII value as an integer:
>>> ord('a')
97
>>> ord('A')
65
>>> ord('0')
48
>>> chr(97)
'a'
>>> chr(65L)
'A'
>>> chr(48)
'0'
Function Description
ascii() Returns a readable version of an object. Replaces none-ascii
characters with escape character. It escapes any non-ASCII
characters using Unicode escape sequences (e.g., \uXXXX for
characters outside the ASCII range).
bin() Returns the binary version of a number
bool() Returns the boolean value of the specified object
bytearray() Returns an array of bytes
bytes() Returns a bytes object
callable() Returns True if the specified object is callable, otherwise False
compile() Returns the specified source as an object, ready to be executed
dict() Returns a dictionary or The dict() function is used to create a new
dictionary, which is a collection of key-value pairs.
dir() Returns a list of the specified object's properties and methods
eval() Evaluates and executes an expression
exec() Executes the specified code (or object)
format() Formats a specified value
frozenset() Returns a frozenset object
hash() Returns the hash value of a specified object
help() Executes the built-in help system
id() Returns the id of an object
input() Allowing user input
len() Returns the length of an object
print() Prints to the standard output device
range() Returns a sequence of numbers, starting from 0 and increments
by 1 (by default)
ascii():
Returns a readable version of an object. Replaces none-ascii characters with escape
character. It escapes any non-ASCII characters using Unicode escape sequences (e.g.,
\uXXXX for characters outside the ASCII range).
Examples:
# Non-ASCII characters
# Non-printable characters
print(ascii('\n\t')) # Output: '\\n\\t'
bin():
# Convert positive integers to binary
print(bin(10)) # Output: '0b1010'
bool():
Examples:
# Truthy values
print(bool(1)) # Output: True
print(bool("Hello")) # Output: True
print(bool([1, 2, 3])) # Output: True
# Falsy values
print(bool(0)) # Output: False
print(bool("")) # Output: False
print(bool(None)) # Output: False
bytearray():
If the source is an integer, it creates a bytearray of that size, initialized with null bytes
(\x00).
Examples:
ba = bytearray(5)
print(ba) # Output: bytearray(b'\x00\x00\x00\x00\x00')
You can create a bytearray from an iterable of integers (values must be between 0 and
255).
ba = bytearray([65, 66, 67])
print(ba) # Output: bytearray(b'ABC')
bytes():
Examples:
ba = bytearray(5)
print(ba) # Output: bytearray(b'\x00\x00\x00\x00\x00')
# bytes is immutable
b = bytes([1, 2, 3])
# b[0] = 4 # Raises TypeError: 'bytes' object does not support item
assignment
# bytearray is mutable
ba = bytearray([1, 2, 3])
ba[0] = 4
print(ba) # Output: bytearray(b'\x04\x02\x03')
callable():
Examples:
Checking Built-in Functions:
print(callable(len)) # Output: True
print(callable(print)) # Output: True
Checking Functions:
def my_function():
return "Hello, World!"
print(callable(my_function)) # Output: True
Compile():
The compile() method in Python is used to compile a source code string into a code
object, which can then be executed using the exec() or eval() functions. It allows
dynamic execution of Python code at runtime
Syntax:
Parameters
dir():
Returns a list of the specified object's properties and methods
Syntax
dir([object])
object (optional): The object whose attributes are to be listed.
If no argument is passed, dir() returns a list of names in the current local scope.
Example:
import math
print(dir(math))
# Output: ['__doc__', '__loader__', '__name__', '__package__', 'acos', 'acosh', 'asin',
...]
eval():
The eval() function in Python is used to evaluate and execute a string expression as
Python code. It takes a string input and parses it as a Python expression.
Syntax:
eval(expression, globals=None, locals=None)
Parameters:
expression (required): A string containing a valid Python expression.
globals (optional): A dictionary representing the global namespace.
locals (optional): A dictionary representing the local namespace.
Example-1:
expression = "3 + 5"
result = eval(expression)
print(result) # Output: 8
Example-2:
x = 10
y = 20
expression = "x * y"
result = eval(expression)
print(result) # Output: 200
exec() :
The exec() function in Python is used to execute dynamically generated Python code,
which can include statements, functions, classes, loops, and other valid Python
constructs.
Syntax
exec(object[, globals[, locals]])
Parameters
object: A string, bytes, or AST object containing Python statements to be executed.
globals (optional): A dictionary representing the global namespace.
locals (optional): A dictionary representing the local namespace.
Example:
Executing a Single Statement
exec("print('Hello, World!')")
# Output: Hello, World!
format():
The format() function in Python is used for string formatting. It allows you to insert
values into a string with placeholders, making it easier to create formatted strings
dynamically. You can use {} as placeholders, and then specify values to insert into these
placeholders in a specific order or by name.
Examples:
name = "Alice"
age = 30
sentence = "My name is {} and I am {} years old.".format(name, age)
print(sentence)
Output:
My name is Alice and I am 30 years old.
frozenset():
The frozenset() function in Python creates an immutable (or "frozen") version of a set.
Example:
frozen = frozenset([1, 2, 3])
# Attempting to add an element (raises an error)
frozen.add(4) # This will raise AttributeError
globals():
Example:
x = 10
y = 20
# Displaying the global symbol table
print(globals())
Output:
{
'__name__': '__main__',
'__doc__': None,
'__package__': None,
'__loader__': <_frozen_importlib_external.SourceFileLoader object at
0x7f8d9b263be0>,
'__spec__': None,
'__builtin__': <module 'builtins' (built-in)>,
'__file__': 'path/to/script.py',
'__cached__': None,
'x': 10,
'y': 20
}
Note: The globals() function returns the dictionary of the global symbol table, including
variables like x, y, and other built-in attributes.
hash():
The hash() function in Python returns the hash value of an object, which is an integer.
This integer is used to uniquely identify the object, typically for hashing purposes in
data structures like dictionaries and sets.
Example:
# initializing objects
int_val = 4
str_val = 'Cyber'
flt_val = 24.56
print("The integer hash value is : " + str(hash(int_val)))
print("The string hash value is : " + str(hash(str_val)))
print("The float hash value is : " + str(hash(flt_val)))
Output:
The integer hash value is : 4
The string hash value is : 4349415460800802357
The float hash value is : 1291272085159665688
help():
Python help() function is used to get help related to the object passed during the call.
import math
help(math)
Output:
Help on module math:
NAME
math
DESCRIPTION
This module provides access to mathematical functions.
MODULE FUNCTIONS
acos(...)
Return the arc cosine of x in radians.
acosh(...)
Return the inverse hyperbolic cosine of x.
...
id():
Example:
x = 42
print(id(x))
Output:
140642115230496
input():
The input() function in Python is used to read data from the user via the console. It
allows the user to enter information, which is then returned as a string. If you need to
convert the input to another data type (e.g., integer, float), you will need to cast it
explicitly.
Example-1:
name = input("Enter your name: ")
print(f"Hello, {name}!")
Output:
Enter your name: Alice
Hello, Alice!
Example-2:
age = input("Enter your age: ")
age = int(age) # Convert the input to an integer
print(f"You are {age} years old.")
Output:
Enter your age: 25
You are 25 years old.
print():
The print() function in Python is used to display output to the console.
Syntax:
print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
Parameters:
*objects: One or more objects to print. Multiple objects are separated by sep.
sep: String inserted between objects. Defaults to a single space ' '.
end: String appended after the last object. Defaults to a newline '\n'.
file: File-like object to write to. Defaults to sys.stdout (console output).
flush: If True, the output is flushed immediately. Defaults to False
In print() function the items are each converted to text form, separated by spaces, and
there is a single '\n' at the end (the "newline" char). When called with zero parameters,
print() just prints the '\n' and nothing else.
Print Option sep=
By default, print() separates the items by spaces. The optional sep= parameter sets a
different separator text.
Examples:
>>> print(12, 24, -2)
12 24 -2
>>> print(12, 24, -2, sep=':')
12:24:-2
>>> print('but', 'not', 'including', sep='**')
but**not**including
Print Option end=
By default, print() puts a single '\n' after all the items. The optional end= parameter sets
a custom string to appear after all the items. If you use '\n' along with the items, the
printing the string ends up double-spacing the output.
Examples:
>>> print('hello\n')
hello
>>> print('there\n')
there
>>>
If you want remove extra newline, you should set end= with empty string.
>>> print('hello\n', end='')
hello
>>> print('there\n', end='')
there
You can print multiple values in a single line using * with print().
print(*["Python", "is", "awesome!"])
Output:
Python is awesome!
Print To File
The super common case is printing to standard output. However, print() also works
printing to an open file.
To open a file for writing, add 'w' when calling the open() function (shown below) —
'w' for "writing".
Example:
with open(filename, 'w') as f:
print('Hello world', file=f)
range():
Syntax:
range(start, stop, step)
Parameters:
Examples:
# Generate numbers from 2 to 6
for i in range(2, 7):
print(i, end=" ") # Output: 2 3 4 5 6
Ex:
a=5
b = 10
if a < b:
print("a is smaller than b")
Output:
a is smaller than b
Ex:
name=input('Enter your name:')
if name=='cyber':
print('Hi')
print('How are you ',name)
Output:
Enter your name:cyber
Hi
How are you cyber
ii) else:
Any expression evaluated to True leads the execution of it's body statements whereas
else body statement is executed once the expression evaluates to False. It is an optional
statement in if condition.
Syntax:
if expression:
statement 1
………..
statement n
else:
statement 1
………..
statement n
Ex:
a = 10
b=5
if a < b:
print("a is smaller than b")
else:
print("a is greater than b")
Output:
a is greater than b
iii) elif:
elif statement is used to chain multiple if statements. Once any one of the if (it may be
if or elif) expression is evaluated to True, the program executes the body of it and exits
the control flow, else the body of else is executed.
Syntax:
if expression:
statement 1
…..
elif expression:
statement 1
…..
.
.
else :
statement 1
…….
Ex:
food=input("Enter Your Favourite Food item:")
if food=="biryani"
print("It will be Delcious in Paradise")
elif food=="pizza":
print("It will be Delcious in Dominos")
elif food=="burger":
print("It will be Delcious in McDonalds")
else :
print("I don't about this food item")
Output:
Enter Your Favourite Food item: pizza
It will be Delcious in Dominos
Example:
# Print numbers 1 to 5
i=1
while i <= 5:
print(i)
i =i+ 1
Output:
1
2
3
4
5
We can also use while loops for infinite loops.
Example:
while True:
print('Hi')
Output:
Hi
Hi
….
for loop:
The for loop is used to iterate over any iterable objects such as list, set, string etc. It
visits each item in an iterable series unless the keyword break or continue is encountered
and assigns it to a variable that we specify in the for statement.
Syntax:
for item in iterable:
statements
Example:
# Loop through a sequence (list)
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
Example:
name = "CYBER"
for ch in name:
print(ch)
Output:
C
Y
B
E
R
Example:
list=eval(input("Enter List:"))
sum=0;
for x in list:
sum=sum+x;
print("The Sum=",sum)
Output:
Enter List:[10,20,30]
The Sum= 60
Nested Loops: A loop inside another loop is called nested loops.
Example:
for i in range(3):
for j in range(3):
print("i=",i," j=",j)
Output:
i= 0 j= 0
i= 0 j= 1
i= 0 j= 2
i= 1 j= 0
i= 1 j= 1
i= 1 j= 2
i= 2 j= 0
i= 2 j= 1
i= 2 j= 2
Output:
Shirley
Terry
Joe
Heather
Lucy
break:
break keyword terminates the innermost loop, transferring execution to the first
statement after the loop. With the break statement we can stop the loop even if the while
condition is True. For a nested loop, break terminates the innermost loop.
Example:
for i in range(10):
if i==7:
print("Value is 7 Break the loop")
break
print(i)
Output:
0
1
2
3
4
5
6
Value is 7 Break the loop
continue:
Whenever a continue statement is encountered during a program execution, the
execution flow skips the current iteration and goes to next iteration.
Example:
for i in range(10):
if i%2==0:
continue
print(i,end=' ')
Output:
13579
pass Statement:
In Python programming, the pass statement is a null statement.
The difference between a comment and a pass statement in Python is that while
the interpreter ignores a comment entirely, pass is not ignored.
However, nothing happens when the pass is executed. It results in no operation
(NOP).
Suppose we have a loop or a function that is not implemented yet, but we want
to implement it in the future. They cannot have an empty body. The interpreter
would give an error. So, we use the pass statement to construct a body that does
nothing.
Example 1:
sequence = {'p', 'a', 's', 's'}
for val in sequence:
pass
Example 2:
def function(args):
pass
Example 3:
class Example:
pass
Example 4:
for i in range(10):
if i%2==0:
print(i,end=' ')
else:
pass
Output:
02468
while condition:
# Loop body
else:
# Executes if the loop is not terminated by break
Example 1:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
if num == 10: # This condition is never met
break
else:
print("Loop completed without a break.")
Output:
1
2
3
4
5
Loop completed without a break.
Example 2:
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
if num == 3: # Loop terminates here
break
else:
print("Loop completed without a break.")
Output:
1
2
3
Note: Here, the else block is not executed because the loop was terminated by a break.
Example 3:
i=1
while i <= 5:
print(i)
if i == 3: # Loop terminates here
break
i += 1
else:
print("While loop completed without a break.")
Output:
1
2
3
del statement:
del is a keyword in Python. After using a variable, it is highly recommended to delete
that variable if it is no longer required,We can delete variable by using del keyword.
Example:
x=10
print(x)
del x
After deleting a variable we cannot access that variable otherwise we will get
NameError.
Example:
x=10
del x
print(x)
Output:
NameError: name 'x' is not defined.
List comprehensions:
List comprehensions in Python are a concise and elegant way to create lists. They allow
you to generate new lists by applying an expression to each item in an iterable,
optionally filtering items with a condition.
Syntax:
new_list = [expression for item in iterable if condition]
Example 1:
#Create a list of squares of numbers from 1 to 5.
squares = [x ** 2 for x in range(1, 6)]
print(squares)
Output:
[1, 4, 9, 16, 25]
Example 2:
#Create a list of even numbers from 1 to 10.
evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens)
Output:
[2, 4, 6, 8, 10]
Example 3:
#Nested Loops in List Comprehension
pairs = [(x, y) for x in range(1, 3) for y in range(3, 5)]
print(pairs)
Output:
[(1, 3), (1, 4), (2, 3), (2, 4)]
Generator expressions:
Generator expressions in Python are similar to list comprehensions, but they create a
generator object instead of a list. Generators are used to produce items lazily, meaning
that they generate values on the fly and do not store them in memory, which is especially
useful when working with large datasets.
Syntax:
generator = (expression for item in iterable if condition)
expression: The operation or value to apply to each item.
item: The current item in the iteration.
iterable: The sequence or range to iterate over.
condition: (Optional) A filter to include only items that satisfy this condition.
Example 1:
sum_of_squares = sum(x ** 2 for x in range(1, 6))
print(sum_of_squares)
Output:
55
Example 2:
vens = (x for x in range(1, 11) if x % 2 == 0)
for even in evens:
print(even)
Output:
2
4
6
8
10