Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
3 views

Python Programming Unit-1

The document provides an overview of Python basics, focusing on Python objects, their characteristics, and standard data types including numeric, sequence, set, mapping, boolean, binary, and none types. It also covers internal types, standard type operators, and examples of arithmetic and relational operators. Additionally, it highlights the differences between Python 2 and 3 regarding range and xrange functions.

Uploaded by

venkatasai012345
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Python Programming Unit-1

The document provides an overview of Python basics, focusing on Python objects, their characteristics, and standard data types including numeric, sequence, set, mapping, boolean, binary, and none types. It also covers internal types, standard type operators, and examples of arithmetic and relational operators. Additionally, it highlights the differences between Python 2 and 3 regarding range and xrange functions.

Uploaded by

venkatasai012345
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

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}

frozenset: Immutable version of a set.


Example: frozenset([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)

Following is the output of the above code −


<memory at 0x00000186FFAA3580>

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

# Calculate the average of the numbers list



In libraries like NumPy, Ellipsis is used for slicing multi-dimensional arrays, allowing
users to skip over dimensions conveniently.
Example:
import numpy as np
# Create a 2D array named "cn" with some values
cn = np.array([[7, 2, 4, 7], [6, 5, 1, 7], [9, 4, 5, 1]])

# Extract and print the second column using Ellipsis literal


print(f"Ellipsis Literal Output: {cn[..., 1]}.")
Output:
[2 5 4]
Using three dots (...) indicates that we need all rows and only the second column: cn[...,
1].

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

Standard Type Operators:


Operators are used to perform operations on variables and values.
1) Arithmetic operators:
Arithmetic operators are used to perform mathematical operations like addition,
subtraction, multiplication, etc.
Operato Meaning Example
r
+ Add two operands or unary plus x+y
- Subtract right operand from the left or unary minus x-y
* Multiply two operands x*y
/ Divide left operand by the right one (always results into float) x / y
% Modulus - remainder of the division of left operand by the right x % y
(remainder
of x/y)
// Floor division - division that results into whole number x // y
adjusted to the left in the number line
** Exponent - left operand raised to the power of right x**y
(x to the
power y)

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'

 If we perform division, floor division, modulo by 0, we will get


ZeroDivisionError.

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

Note: Increment and decrement operators are not allowed in python.

2) Relational (or) comparison operators:


Comparison operators are used to compare values. It returns either True or False
according to the condition.

Operator Meaning Example


> Greater than - True if left operand is greater than the right x>y
< Less than - True if 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 left operand is greater than x >= y
or equal to the right
<= Less than or equal to - True if left operand is less than or x <= y
equal
to the right

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

We can also apply relational operators to strings.


Ex:
a='sum'
b='row'
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
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

Relational operators can be applied to boolean values. Internally, True is considered as


1 and False is considered as 0.
Ex:
a=True
b=False
print('a>b:',a>b)
print('a<b:',a<b)
Output:
a>b: True
a<b: False

Chaining of relational operators is possible. If all comparisons are True,then it returns


True. If atleast one comparison is False, then entire comparison returns False.
Ex:
print('10<20<30:',10<20<30)
print('10<20>30:',10<20>30)
Output:
10<20<30: True
10<20>30: False
Ex:
>>> 'a'==97
False
>>> False==False
True
>>> 10==5+5==7+3==2*5
True
>>> 10==10.0
True
In this case,10 will be converted to larger type in the expression i.e., float
>>> 10=='10'
False
>>> 1==True
True
>>> 10==10.1
False
>>> 10.10==10.1
True

3) Logical Operators:
Logical operators are the and, or, not operators. We can apply these operators for all
types.

Operator Meaning Example


and True if both the operands are true x and y
or True if either of the operands is true x or y
not True if operand is false (complements not x
the operand)
For Boolean types:
and If both arguments are True then only result is True
or If atleast one arugemnt is True then result is True
not If True the False, If False then True.

Ex:
>>> True and False
False
>>> True or False
True
>>> not True
False

For Non-Boolean types:


For all Non boolean types, 0 means False and non zero means True. For strings, ' ' means
False and non empty strings means True.
 x and y: If x evaluates to false the result is x, otherwise returns y.
Truth table for and
A B A and B
TRUE TRUE TRUE
TRUE FALSE FALSE
FALSE TRUE FALSE
FALSE FALSE 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'

 x or y: If x evaluates to True then result is x, otherwise returns y.


Truth table for or
A B A or B
TRUE TRUE TRUE
TRUE FALSE TRUE
FALSE TRUE TRUE
FALSE FALSE FALSE

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

not x: If x evaluates to True then False, If x evaluates to False then True.

Ex:
>>> not 10
False
>>> not 0
True
>>> not ''
True
>>> not 'cyber'
False

Truth tabel for not


A not A
TRUE FALSE
FALSE TRUE

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.

~4111---------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

Ternary Operator (Conditional Operator):


In C, C++, Java we have ternary operator as ?:,but in python it is represented in different
way.
In Python ,Syntax of ternary operator is:
x=first_value if condition else second__value
Ex:
>>> x=30 if 10<20 else 40
>>> x
30

Ex: To find minimum value of two numbers


a=int(input('enter first value:'))
b=int(input('enter second value:'))
min=a if a<b else b
print('Minimum value is:',min)
Output:
enter first value:10
enter second value:20
Minimum value is: 10
 Ternary Operator can be nested.
Ex: To find maximum value of three numbers
a=int(input('Enter first value:'))
b=int(input('Enter second value:'))
c=int(input('Enter third value:'))
max=a if a>b and a>c else b if b>c else c
print('Maximum value is:',max)
Output:
Enter first value:30
Enter second value:20
Enter third value:10
Maximum value is: 30

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

ii) Membership Operators:


in and not in are the membership operators in Python. They are used to test whether a
value or variable is found in a sequence (string, list, tuple, set and dictionary).
In a dictionary we can only test for presence of key, not the value.
Operator Meaning Example
in True if value/variable is found in the sequence 5 in x
not in True if value/variable is not found in the sequence 5 not in x

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

Standard Type Built-in Functions:


Built-in functions in Python are pre-defined functions provided by the Python language
that can be used to perform common tasks. To use a built-in function, simply call it with
the appropriate arguments, like this: function_name(argument1, argument2). Python
also provides some builtin functions that can be applied to all the basic object types:
cmp(), repr(), str(), type(), and the single reverse or back quotes ( ' ' ) operator, which
is functionally equivalent to repr().
Function Description
cmp(obj1, obj2) compares obj1 and obj2, returns integer i where:
i < 0 if obj1 < obj2
i > 0 if obj1 > obj2
i == 0 if obj1 == obj2
repr(obj)/' obj' returns evaluatable string representation of obj
str(obj) returns printable string representation of obj
type(obj) determines type of obj and return type object
cmp( ):
The cmp() built-in function compares two objects, say, obj1 and obj2, and returns a
negative number (integer) if obj1 is less than obj2, a positive number if obj1 is greater
than obj2, and zero if obj1 is equal to obj2.
Example:
>>> a, b = -4, 12
>>> cmp(a,b)
-1
>>> cmp(b,a)
1
>>> b = -4
>>> cmp(a,b)
0
str() and repr() (and ' 'Operator):
The str() STRing and repr() REPResentation built-in functions or the single back or
reverse quote operator ( `` ) come in really handy if the need arises to either recreate an
object through evaluation or obtain a human-readable view of the contents of objects,
data values, object types, etc.
In some examples below, we take some random Python types and convert them to their
string representations.

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

Categorizing the Standard Types:


There are three different models we have come up with to help categorize the standard
types, with each model showing us the interrelationships between the types. These
models help us obtain a better understanding of how the types are related, as well as
how they work.
Storage Model:
The first way we can categorize the types is by how many objects can be stored in an
object of this type. Python's types, as well as types from most other languages, can hold
either single or multiple values. A type which holds a single object we will call literal
or scalar storage, and those which can hold multiple objects we will refer to as container
storage. (Container objects are also referred to as composite or compound objects in the
documentation, but some of these refer to objects other than types, such as class
instances.) Container types bring up the additional issue of whether different types of
objects can be stored. All of Python's container types can hold objects of different types.
Bellow Table categorizes Python's types by storage model.

Types categorized by the Storage Model


Storage model category Python types that fit category
literal/scalar numbers (all numeric types), strings
container lists, tuples, dictionaries

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.

How to Create and Assign Numbers (Number Objects):


Creating numbers is as simple as assigning a value to a variable:
Example:
anInt = 1
1aLong = -9999999999999999L
aFloat = 3.1415926535897932384626433832795
aComplex = 1.23 + 4.56J

How to Update Numbers:


You can "update" an existing number by (re)assigning a variable to another number.
The new value can be related to its previous value or to a completely different number
altogether.
anInt = anInt + 1
aFloat = 2.718281828

How to Remove Numbers:


Under normal circumstances, you do not really "remove" a number; you just stop using
it! If you really want to delete a reference to a number object, just use the del statement.
You can no longer use the variable name, once removed, unless you assign it to a new
object; otherwise, you will cause a NameError exception to occur.
Example:
del anInt
del aLong, aFloat, aComplex

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:

0101 84 -237 0x80 017 -680 -0X92

We can represent int values in the following forms:


i) Binary
ii) Octal
iii) Decimal
iv) Hexa Decimal

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

Floating Point Real Numbers:


Floats in Python are implemented as C doubles, double precision floating point real
numbers, values which can be represented in straight forward decimal or scientific
notations. These 8-byte (64-bit) values conform to the IEEE 754 definition
(52M/11E/1S) where 52 bits are allocated to the mantissa, 11 bits to the exponent (this
gives you about ± 10308.25 in range), and the final bit to the sign.
Floating point values are denoted by a decimal point ( . ) in the appropriate place and
an optional "e" suffix representing scientific notation.
Floating point numbers can be represented only in decimal form. We cannot represent
Floating point numbers in binary, octal, hexadecimal forms.

0.0 -777. 1.6 -5.555567119 96e3 * 1.0


4.3e25 9.384e-23

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:

Defining Complex Numbers:


Combining a real number with an imaginary number forms a single entity known as a
complex number.
A complex number is expressed in the form:
Object with same address:
In Python if a new object is required, then Python Virtual Machine won’t create object
immediately. First it will check is any object available with the required content or not.
If available then existing object will be reused. If it is not available then only a new
object will be created. The advantage of this approach is memory utilization and
performance will be improved.
Ex:
x=10
y=10
z=10
id(x)
id(y) returns same address for x, y and z
id(z)

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

Reusability of objects is applicable for bool type also.


Ex:
a=True
b=True

Reusability of objects is not applicable for float and complex types.


Ex:
a=12.5
b=12.5

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

For integers - the integer absolute value is returned


For floating numbers - the floating absolute value is returned
For complex numbers - the magnitude of the number is returned

Here are some examples of using the abs() built-in function:


>>> abs(-1)
1
>>> abs(10.)
10.0
>>> abs(-30.33)
30.33
>>> abs(3 + 4j)
5.0
>>> abs(3 - 4j)
5.0
>>> abs(0.23 - 0.78)
0.55

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)

divmod(10, 3) returns (3,1)


Examples:
>>> divmod(10.5, 3)
(3.0,1.5)
>>> divmod(3,10)
(0, 3)
>>> divmod(10,2.5)
(4.0, 0.0)
>>> divmod(2.5,10)
(0.0, 2.5)

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'

Other Built-in functions:

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

print(ascii('Python is fun 😊')) # Output: 'Python is fun \U0001f60a'

# ASCII characters only


print(ascii('Hello')) # Output: 'Hello'

# Escape special characters


print(ascii('Mañana')) # Output: 'Ma\u00f1ana'

# Non-printable characters
print(ascii('\n\t')) # Output: '\\n\\t'
bin():
# Convert positive integers to binary
print(bin(10)) # Output: '0b1010'

# Convert zero to binary


print(bin(0)) # Output: '0b0'

# Convert negative integers to binary


print(bin(-5)) # Output: '-0b101'

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

ba = bytearray([65, 66, 67])


print(ba) # Output: bytearray(b'ABC')

Comparing bytes and bytearray:


The bytes type is immutable, while bytearray is mutable:

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

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)

Parameters

1. source: The source code to be compiled. It can be a string, bytes, or an AST


(Abstract Syntax Tree) object.
2. filename: The name of the file from which the source code was read. If the
code is provided as a string, you can use <string> as the filename.
3. mode: Specifies the type of code being compiled:
o 'exec': Used when compiling a block of statements (e.g., functions,
loops).
o 'eval': Used when compiling a single expression.
o 'single': Used when compiling a single interactive statement.
4. flags (optional): Used to modify compilation behavior (default is 0).
5. dont_inherit (optional): Determines whether to inherit global syntax flags
(default is False).
6. optimize (optional): Optimization level (default is -1, which means use the
interpreter’s optimization setting).
Examples:
Using compile() with eval mode
code = "5 + 10"
compiled_code = compile(code, '<string>', 'eval')
result = eval(compiled_code)
print(result) # Output: 15

Using compile() with exec mode


code = """
x = 10
y = 20
print(x + y)
"""
compiled_code = compile(code, '<string>', 'exec')
exec(compiled_code)
# Output: 30

Using compile() with single mode


code = "print('Hello, World!')"
compiled_code = compile(code, '<string>', 'single')
exec(compiled_code)
# Output: Hello, World!

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

# prints the multiple items in the same line


print("Hello", end=" ")
print("World!")
Output:
Hello World!

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:

start (optional): The starting value of the sequence (inclusive). Defaults to 0.


stop (required): The endpoint of the sequence (exclusive).
step (optional): The difference between each number in the sequence. Defaults to 1.

Examples:
# Generate numbers from 2 to 6
for i in range(2, 7):
print(i, end=" ") # Output: 2 3 4 5 6

# Generate even numbers from 2 to 10


for i in range(2, 11, 2):
print(i, end=" ") # Output: 2 4 6 8 10

# Generate numbers in reverse


for i in range(10, 0, -2):
print(i, end=" ") # Output: 10 8 6 4 2

Conditionals and Loops


Conditional (or) Selection (or) Decision-making statements:
i) if:
if is the most basic control flow statement in Python. It enables the program to execute
a certain part of the program if the given condition in an if statement is satisfied.
Syntax:
if expression:
statement 1
…….
statement n
The program executes the statement only if the expression is evaluated to True.
As Python depends on indentation using whitespaces, all the control statements is
terminated with colon indicating the body will be followed next and the first unindented
line marks the end.

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

Single Statement Suites:


If the suite of an if clause consists only of a single line, it may go on the same line as
the header statement:
Example:
weather = "sunny"
if weather == "sunny": print("I should take a walk outside!")
output:
I should take a walk outside!

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

Iterative (or) Repetition (or) Looping statements:


In Python, looping statements allow you to repeat a block of code multiple times. There
are two primary types of loops in Python:
 while
 for
while loop:
This is used when you want to repeat a block of code as long as a condition is True.
When the condition becomes false, the line immediately after the loop in the program
is executed.
Syntax:
while expression:
statements

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

Iterating by Sequence Index:


An alternative way of iterating through each item is by index offset into the sequence
itself:
Example:
nameList = ['Shirley', "Terry", 'Joe', 'Heather', 'Lucy']
for nameIndex in range(len(nameList)):
print (nameList[nameIndex])

Output:
Shirley
Terry
Joe
Heather
Lucy

Transfer (or) Branching statements:


 break
 continue

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

Loops with else:


In Python, both for and while loops can have an optional else block. The else block
executes after the loop finishes its normal execution, i.e., it runs only if the loop was
not terminated by a break statement.
Syntax:
for item in iterable:
# Loop body
else:
# Executes if the loop is not terminated by break

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]

 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:
#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

You might also like