0% found this document useful (0 votes)
9 views54 pages

Python Unit 1 Notes

This document provides an overview of Python basics, focusing on objects, standard types, and built-in types. It explains key concepts such as mutable vs immutable objects, standard operations, and various data types including numbers, sequences, mappings, and sets. Additionally, it covers internal types, operators, and their usage in Python programming.

Uploaded by

motatiakhila
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)
9 views54 pages

Python Unit 1 Notes

This document provides an overview of Python basics, focusing on objects, standard types, and built-in types. It explains key concepts such as mutable vs immutable objects, standard operations, and various data types including numbers, sequences, mappings, and sets. Additionally, it covers internal types, operators, and their usage in Python programming.

Uploaded by

motatiakhila
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

UNIT - I

Python Basics, Objects- Python Objects, Standard Types, Other Built-in Types,
Internal Types, Standard Type Operators, Standard Type Built-in Functions,
Categorizing the Standard Types, Unsupported Types
Numbers - Introduction to Numbers, Integers, Floating Point Real Numbers,
Complex Numbers, Operators, Built- in Functions, Related Modules Sequences -
Strings, Lists, and Tuples, Mapping and Set Types

Python Basics, Objects- Python Objects


Introduction to Python
• Python is a high-level, interpreted, general-purpose programming language.
• Key Features:
o Simple and easy-to-learn syntax.
o Interpreted: runs line by line.
o Object-Oriented: everything is an object.
o Large standard library for various applications.
Example:
print("Hello, Python!")

Python Objects
1. Introduction
• In Python, everything is an object.
• Objects are instances of a class (type).
• Each object has:
1. Identity – unique address in memory (id())
2. Type – the class of the object (type())
3. Value – the data stored in the object
Analogy: Think of an object as a real-world object (like a pen):
• Identity → serial number of the pen
• Type → pen type (ballpoint, gel)
• Value → color of ink

2. Creating Objects
• Objects are created automatically when you assign a value to a variable.
x = 10 # integer object
y = "Python" # string object
z = [1, 2, 3] # list object
• Check object type:
print(type(x)) # <class 'int'>
print(type(y)) # <class 'str'>
print(type(z)) # <class 'list'>
• Check object identity:
print(id(x)) # memory address of x
print(id(y))

3. Mutable vs Immutable Objects


• Immutable objects – value cannot be changed after creation:
o int, float, complex, str, tuple, frozenset
• Mutable objects – value can be changed:
o list, dict, set, bytearray
Example:
# Immutable
x=5
print(id(x)) # e.g., 140707543456656
x = 10 # creates a new object
print(id(x)) # different memory address
# Mutable
lst = [1, 2, 3]
print(id(lst))
[Link](4) # modifies the same object
print(id(lst)) # same memory address

4. Standard Operations on Objects


• Assignment – creates a reference to an object
a = [1, 2, 3]
b = a # b refers to the same object as a
[Link](4)
print(a) # [1,2,3,4]
• Copying objects – to avoid modifying original object:
import copy
a = [1,2,3]
b = [Link](a) # shallow copy
[Link](4)
print(a) # [1,2,3]

5. Python’s Built-in Object Functions


• id(obj) → returns unique identifier (memory address)
• type(obj) → returns the object’s type
• isinstance(obj, class) → checks if object is instance of class
• dir(obj) → returns list of all attributes and methods of object
Example:
x = "Python"
print(id(x)) # memory address
print(type(x)) # <class 'str'>
print(isinstance(x,str)) # True
print(dir(x)) # methods of string object

6. Objects and Memory Management


• Python uses reference counting and garbage collection to manage memory.
• When no references point to an object, it is automatically deleted.
x = [1,2,3]
y=x
del x
print(y) # [1,2,3] object still exists because y references it

Hence
• Everything in Python is an object.
• Objects have identity, type, and value.
• Understanding mutable vs immutable objects is crucial.
• Built-in functions like id(), type(), and isinstance() help inspect objects.

Python Standard Types


1. Introduction
• Python provides built-in standard types to represent different kinds of data.
• These types are the basic building blocks of Python programs.
• Categories:
1. Numbers – int, float, complex
2. Sequences – str, list, tuple
3. Mapping – dict
4. Set types – set, frozenset
5. Boolean – True/False
6. NoneType – None

2. Numbers
• Used to represent numeric values.
• Types:
1. int – whole numbers
2. float – decimal numbers
3. complex – numbers with real and imaginary parts
Example:
a = 10 # int
b = 3.14 # float
c = 2 + 3j # complex
print(type(a)) # <class 'int'>
print(type(b)) # <class 'float'>
print(type(c)) # <class 'complex'>

3. Sequences
• Ordered collection of items
• Types:
1. String (str) – sequence of characters (immutable)
• s = "Python"
• print(s[0]) # P
• print(s[1:4]) # yth
2. List (list) – mutable sequence
• lst = [1,2,3]
• [Link](4)
• print(lst) # [1,2,3,4]
3. Tuple (tuple) – immutable sequence
• t = (1,2,3)
• print(t[1]) # 2

4. Mapping Type
• Dictionary (dict) – collection of key-value pairs (mutable)
student = {"name":"Ananth", "age":22}
print(student["name"]) # Ananth
student["age"] = 23 # update value

5. Set Types
• Set (set) – unordered collection of unique elements (mutable)
s = {1,2,2,3}
print(s) # {1,2,3}
[Link](4)
• Frozen Set (frozenset) – immutable set
fs = frozenset([1,2,3])
# [Link](4) # ERROR, cannot modify

6. Boolean Type
• Represents truth values: True or False
• Often result of comparisons:
a = 10
b=5
print(a > b) # True
print(a == b) # False

7. None Type
• Represents absence of a value: None
x = None
print(x) # None
print(type(x))# <class 'NoneType'>

8. Summary Table of Standard Types

Type Mutable Example

int No a = 10

float No b = 3.14

complex No c = 2 + 3j

str No s = "Python"

list Yes lst = [1,2,3]

tuple No t = (1,2,3)

dict Yes d = {"a":1}

set Yes s = {1,2,3}

frozenset No fs = frozenset([1])

bool No True, False

NoneType No None

Key Points :
1. Standard types are predefined in Python.
2. Mutable vs Immutable is important for understanding behavior in programs.
3. Every object has type, identity, and value.
Other Built-in Types in Python
1. Introduction
• Besides the standard types (numbers, sequences, mappings, sets), Python
provides other built-in types to handle special purposes.
• These types are useful for working with binary data, ranges, memory, and
immutable sets.

2. Bytes and Bytearray


• Used to store binary data.
Bytes
• Immutable sequence of integers (0–255).
b = bytes([65, 66, 67])
print(b) # b'ABC'
print(type(b)) # <class 'bytes'>
Bytearray
• Mutable version of bytes.
ba = bytearray([65, 66, 67])
ba[0] = 97
print(ba) # bytearray(b'aBC')
Use: Reading/writing binary files, network communication.

3. Range
• Represents a sequence of numbers.
• Commonly used in loops.
r = range(5)
print(list(r)) # [0, 1, 2, 3, 4]
r2 = range(1, 10, 2)
print(list(r2)) # [1, 3, 5, 7, 9]
• Syntax: range(start, stop, step)

4. Memoryview
• Used to access memory of binary objects without copying.
• Efficient for large data handling.
b = bytes([10, 20, 30])
m = memoryview(b)
print(m[0]) # 10
• Note: Usually used in advanced programming (networking, file handling).

5. Frozenset
• Immutable version of a set.
• Cannot add or remove elements.
fs = frozenset([1,2,3,3])
print(fs) # frozenset({1,2,3})
# [Link](4) # ERROR: cannot modify
• Use: As keys in dictionaries (normal sets cannot be keys).

6. Summary Table of Other Built-in Types

Type Mutable Description Example

Immutable sequence of integers (0–


bytes No b = bytes([65,66,67])
255)

ba =
bytearray Yes Mutable version of bytes
bytearray([65,66])

range No Sequence of numbers range(0,5)

memoryview Yes Access memory of binary objects memoryview(b'abc')

frozenset No Immutable set frozenset([1,2,3])


Key Points
1. Bytes and bytearray are used for binary data handling.
2. Range simplifies creating sequences in loops.
3. Memoryview is for efficient data access (advanced).
4. Frozenset is immutable and hashable, unlike a normal set.

Internal Types in Python


1. Introduction
• Internal types are special types that Python uses internally to manage objects
and program execution.
• They are not commonly created directly by the programmer, but
understanding them helps in advanced programming and debugging.

2. Common Internal Types


1. Code Objects
• Represent compiled Python code (functions, modules).
• Every function you define is compiled into a code object.
def add(a, b):
return a + b
print(add.__code__) # <code object add at 0x...>
• Use: Inspect function internals (number of arguments, variable names, etc.)
code_obj = add.__code__
print(code_obj.co_varnames) # ('a', 'b')

2. Frame Objects
• Represent execution frames of Python code.
• Keep track of local variables, execution position, and call stack.
• Used in debugging, exception handling, and profiling.
import sys
def func():
frame = sys._getframe()
print(frame.f_code.co_name) # func
func()

3. Slice Objects
• Represent slices used in sequences.
• Used internally when you write [start:stop:step] in strings, lists, or tuples.
s = "Python"
slice_obj = slice(1,5,2)
print(s[slice_obj]) # 'yh'
• Equivalent to s[Link]

4. Ellipsis
• Represented by ...
• Used in advanced indexing, especially in NumPy arrays.
arr = [[1,2,3],[4,5,6]]
print(arr[...]) # [[1,2,3],[4,5,6]]

3. Key Points
1. Internal types are mostly used by Python itself.
2. Common ones: code objects, frame objects, slice objects, ellipsis.
3. Understanding these helps in debugging, slicing, and introspection.
4. Most beginners rarely create them directly, but slice objects are useful in
sequence operations.
Python Standard Type Operators
1. Introduction
• Operators in Python allow you to perform operations on objects.
• The behavior of operators depends on the object type.
• Common categories of operators:
1. Arithmetic
2. Relational (Comparison)
3. Logical
4. Assignment
5. Membership
6. Identity

2. Arithmetic Operators
• Used for mathematical calculations.

Operator Description Example

+ Addition 5+3=8

- Subtraction 5-3=2

* Multiplication 5 * 3 = 15

/ Division (float) 5 / 2 = 2.5

// Floor Division 5 // 2 = 2

% Modulus (remainder) 5 % 2 = 1

** Exponentiation 2 ** 3 = 8

Example:
a = 10
b=3
print(a + b) # 13
print(a // b) # 3
print(a ** b) # 1000

3. Relational (Comparison) Operators


• Compare two objects and return True or False.

Operator Description Example

== Equal to 5 == 5 → True

!= Not equal 5 != 3 → True

> Greater than 5 > 3 → True

< Less than 5 < 3 → False

>= Greater or equal 5 >= 5 → True

<= Less or equal 3 <= 5 → True

Example:
x = 10
y = 20
print(x < y) # True
print(x == y) # False

4. Logical Operators
• Combine boolean expressions.

Operator Description Example

and True if both true True and False → False

or True if any true True or False → True

not Negates value not True → False

Example:
a=5
b = 10
print(a < 10 and b > 5) # True
print(not(a == b)) # True

5. Assignment Operators
• Used to assign values to variables.

Operator Meaning Example

= Assign a=5

+= Add and assign a += 3 → a = a+3

-= Subtract and assign a -= 2 → a = a-2

*= Multiply and assign a *= 2 → a = a*2

/= Divide and assign a /= 2 → a = a/2

//= Floor divide and assign a //= 2

%= Modulus and assign a %= 3

**= Exponentiate and assign a **= 2

Example:
x=5
x += 3
print(x) # 8

6. Membership Operators
• Check membership in sequences or sets.

Operator Description Example

in True if value exists 'a' in 'cat' → True

not in True if value missing 5 not in [1,2,3] → True


Example:
s = [1,2,3,4]
print(3 in s) # True
print(5 not in s) # True

7. Identity Operators
• Compare whether two objects are the same (same memory location).

Operator Description Example

is True if same object a is b

is not True if not same a is not b

Example:
a = [1,2,3]
b=a
c = [1,2,3]
print(a is b) # True (same object)
print(a is c) # False (different objects)

8. Operator Examples with Different Types


• Numbers: + - * / // % **
• Strings: + (concatenation), * (repetition)
print("Hello" + "World") # HelloWorld
print("Hi" * 3) # HiHiHi
• Lists/Tuples: + (concatenate), * (repeat)
print([1,2] + [3,4]) # [1,2,3,4]
print((1,2)*2) # (1,2,1,2)
• Sets: | (union), & (intersection), - (difference)
A = {1,2,3}
B = {2,3,4}
print(A | B) # {1,2,3,4}
print(A & B) # {2,3}
print(A - B) # {1}

Key Points
1. Operators behave differently depending on object type.
2. Always know mutable vs immutable types when performing operations.
3. Logical, membership, and identity operators are important for conditional
statements.

Python Standard Type Built-in Functions

1. Introduction
• Python provides a set of built-in functions that can be used on standard
types.
• They are ready to use and help perform common tasks like type conversion,
checking, calculations, and sequence operations.

2. Type and Identity Functions

Function Description Example

type(obj) Returns the type of the object type(5) → <class 'int'>

Returns unique identity (memory id(5) →


id(obj)
address) 140707543456656

isinstance(obj,
Checks if object is instance of class isinstance(5,int) → True
class)
Example:
x = [1,2,3]
print(type(x)) # <class 'list'>
print(id(x)) # memory address
print(isinstance(x,list))# True

3. Conversion Functions

Function Description Example

int() Converts to integer int(3.14) → 3

float() Converts to float float(5) → 5.0

complex() Converts to complex number complex(2,3) → (2+3j)

str() Converts to string str(10) → '10'

list() Converts to list list((1,2,3)) → [1,2,3]

tuple() Converts to tuple tuple([1,2,3]) → (1,2,3)

set() Converts to set set([1,2,2,3]) → {1,2,3}

frozenset() Converts to immutable set frozenset([1,2,2]) → frozenset({1,2})

Example:
x = "123"
y = int(x)
print(y + 10) # 133

4. Numeric Functions

Function Description Example

abs(x) Absolute value abs(-5) → 5

pow(x,y) x raised to power y pow(2,3) → 8


Function Description Example

round(x[,n]) Round to n decimals (default 0) round(3.1415,2) → 3.14

divmod(x,y) Returns quotient and remainder divmod(10,3) → (3,1)

max() Returns largest value max([1,5,2]) → 5

min() Returns smallest value min([1,5,2]) → 1

sum() Returns sum of numbers sum([1,2,3]) → 6

Example:
nums = [10, 20, 30]
print(max(nums)) # 30
print(sum(nums)) # 60
print(divmod(10,3))# (3,1)

5. Sequence Functions

Function Description Example

len(seq) Returns length of sequence len("Python") → 6

sorted(seq) Returns sorted list sorted([3,1,2]) → [1,2,3]

reversed(seq) Returns reversed iterator list(reversed([1,2,3])) → [3,2,1]

list(enumerate(['a','b'])) →
enumerate(seq) Returns (index,value) pairs
[(0,'a'),(1,'b')]

Combine sequences into


zip(*seqs) list(zip([1,2],[3,4])) → [(1,3),(2,4)]
tuples

Example:
s = "Python"
for index, char in enumerate(s):
print(index, char)
6. Boolean Functions

Function Description Example

all(iterable) True if all elements True all([True,True]) → True

any(iterable) True if any element True any([False, True]) → True

bool(x) Convert value to boolean bool(0) → False

7. Other Useful Functions


• dir(obj) → list all attributes/methods
• help(obj) → get documentation of object
• id(obj) → unique identifier of object
• callable(obj) → True if object is callable (function or method)
Example:
x = [1,2,3]
print(dir(x)) # list of methods like append, pop
print(callable(len)) # True

Key Points
1. Built-in functions save time and reduce code complexity.
2. Functions are categorized: type/identity, conversion, numeric, sequence,
boolean.
3. Understanding these functions is essential for data manipulation and
calculations.
Categorizing the Standard Types in Python
1. Introduction
• Python standard types can be grouped based on:
1. Mutability – whether the object can be changed after creation.
2. Category – numbers, sequences, mappings, sets, and others.
• Understanding this helps in choosing the right type for a task and avoids
bugs.

2. Mutable vs Immutable Types

Type Category Mutable Immutable Examples

Numbers No Yes int, float, complex

Strings No Yes "Hello", 'Python'

Lists Yes No [1, 2, 3]

Tuples No Yes (1, 2, 3)

Dictionaries (dict) Yes No {"a":1, "b":2}

Sets Yes No {1,2,3}

Frozensets No Yes frozenset({1,2,3})

Bytes No Yes b'ABC'

Bytearray Yes No bytearray(b'ABC')

Boolean No Yes True, False

NoneType No Yes None

3. Sequence Types
• Ordered collections: can be indexed and sliced.
• Immutable: str, tuple
• Mutable: list
Examples:
# Immutable sequence
t = (1,2,3)
s = "Python"

# Mutable sequence
lst = [1,2,3]
lst[0] = 100
print(lst) # [100,2,3]

4. Mapping Type
• Dictionary (dict) – key-value pairs, mutable.
• Example:
student = {"name":"Ananth","age":22}
student["age"] = 23 # modifying value

5. Set Types
• Set: mutable, unordered collection of unique elements
• Frozenset: immutable version of set
• Example:
s = {1,2,3}
[Link](4) # works
fs = frozenset([1,2,3])
# [Link](4) # ERROR
6. Numbers
• Always immutable.
• Types: int, float, complex
• Example:
x=5
y = x + 2 # creates new object, x is unchanged

7. Visual Summary Table

Category Type Mutable? Example

Number int, float, complex No 5, 3.14, 2+3j

Sequence str No "Python"

Sequence list Yes [1,2,3]

Sequence tuple No (1,2,3)

Mapping dict Yes {"a":1}

Set set Yes {1,2,3}

Set frozenset No frozenset({1,2,3})

Binary bytes No b'ABC'

Binary bytearray Yes bytearray(b'ABC')

Boolean bool No True, False

NoneType None No None

Key Points
1. Mutable objects can be changed in place; immutable objects cannot.
2. Most sequences are either mutable (list) or immutable (tuple, str).
3. Sets and dictionaries are mutable, frozenset is immutable.
4. Numbers are always immutable.
Unsupported Types in Python
1. Introduction
• Python has many standard types, but not all operations are supported
between all types.
• Attempting unsupported operations will raise TypeError.
• Understanding this helps students avoid common runtime errors.

2. Unsupported Operations Between Types


1. Numbers and Strings
• You cannot directly add, subtract, multiply, or divide a string with a number.
a = 10 # int
b = "Python" # str
# print(a + b) # ERROR: TypeError
# print(b - a) # ERROR: TypeError
Correct way: Convert the string to number if it represents digits:
b = "20"
print(a + int(b)) # 30

2. Lists and Strings


• Lists and strings cannot be combined directly using +.
lst = [1,2,3]
s = "Hello"
# print(lst + s) # ERROR: TypeError
Correct way: Convert string to list of characters:
print(lst + list(s)) # [1,2,3,'H','e','l','l','o']

3. Dictionary with Non-Hashable Keys


• Dictionary keys must be immutable (hashable).
• Using a list or another dictionary as a key is unsupported.
d = {}
# d[[1,2]] = "value" # ERROR: TypeError
d[(1,2)] = "value" # Works, tuple is immutable

4. Set Operations
• Sets can only contain hashable types.
• Attempting to add mutable types (like list or dict) is unsupported.
s = set()
# [Link]([1,2,3]) # ERROR: TypeError
[Link]((1,2,3)) # Works

5. Unsupported Indexing
• Attempting to index non-sequence types is unsupported.
x = 10
# print(x[0]) # ERROR: TypeError
y = {1:"a"}
# print(y[0]) # ERROR: KeyError (wrong key)

3. Summary Table of Common Unsupported Operations

Operation Example Error Type

int + str 10 + "5" TypeError

list + str [1,2] + "abc" TypeError

dict with list as key {[1,2]: "value"} TypeError

set add list [Link]([1,2]) TypeError

indexing non-sequence 10[0] TypeError


Key Points
1. Python is strongly typed: you cannot mix incompatible types.
2. Immutable types (like int, str, tuple) are usually safe in collections.
3. Always check data type before performing operations.
4. Understanding unsupported operations helps debug TypeErrors quickly.

Numbers in Python
1. Introduction
• In Python, numbers are a built-in standard type used to represent numeric
data.
• Python supports different numeric types:
1. Integer (int) – whole numbers
2. Floating Point (float) – decimal numbers
3. Complex (complex) – numbers with real and imaginary parts
• Key characteristics of numbers:
o Immutable: Once created, the value cannot be changed.
o Support arithmetic operations like addition, subtraction, multiplication,
etc.
o Can be converted between types using built-in functions.

2. Numeric Literals
• Numeric values can be written directly in code.
• Examples:
# Integer
x = 10
y = -5
z = 0b1010 # Binary literal (10 in decimal)
w = 0o12 # Octal literal (10 in decimal)
v = 0xA # Hexadecimal literal (10 in decimal)

# Floating Point
a = 3.14
b = -0.5
c = 2e3 # 2 × 10³ = 2000.0

# Complex
p = 2 + 3j
q = -1j

3. Immutability of Numbers
• Numbers are immutable objects.
• Any operation on a number creates a new object.
x=5
print(id(x)) # Memory address of x
x=x+2
print(id(x)) # New memory address (x now points to new object)

4. Type Conversion
• Numbers can be converted from one type to another using built-in functions:
a = 10 # int
b = float(a) # 10.0
c = complex(a) # (10+0j)
print(type(a)) # <class 'int'>
print(type(b)) # <class 'float'>
print(type(c)) # <class 'complex'>

5. Checking Numeric Types


• Use isinstance() to check the type of a number:
x = 3.14
print(isinstance(x, int)) # False
print(isinstance(x, float)) # True

6. Why Numbers are Important


1. Numbers are used in calculations, statistical analysis, financial data, etc.
2. Python provides arithmetic operators and built-in numeric functions for
computations.
3. Understanding number types helps in choosing correct type for precision and
operations.

Key Points
• Numbers are immutable objects in Python.
• Python supports integers, floats, and complex numbers.
• Numbers can be converted between types using int(), float(), complex().
• Numeric literals can include binary, octal, hexadecimal, and scientific
notation.

Integers in Python
1. Introduction
• Integer (int) is a numeric type representing whole numbers (no decimal
point).
• Can be positive, negative, or zero.
• Integers are immutable objects in Python.
Examples:
a = 10 # positive integer
b = -5 # negative integer
c=0 # zero

2. Integer Literals
• Integers can be written in different number systems:

Type Prefix Example Value

Decimal None 123 123

Binary 0b or 0B 0b1010 10

Octal 0o or 0O 0o12 10

Hexadecimal 0x or 0X 0xA 10

Example:
x = 0b1101 # Binary → 13
y = 0o15 # Octal → 13
z = 0xD # Hex → 13
print(x, y, z) # 13 13 13

3. Operations on Integers
Python supports arithmetic operations:
a = 15
b=4
print(a + b) # 19 (Addition)
print(a - b) # 11 (Subtraction)
print(a * b) # 60 (Multiplication)
print(a / b) # 3.75 (Division → float)
print(a // b) # 3 (Floor Division)
print(a % b) # 3 (Modulus)
print(a ** b) # 50625 (Exponentiation)

4. Integer Functions
Python provides several built-in functions for integers:

Function Description Example

abs(x) Absolute value abs(-10) → 10

divmod(a,b) Returns quotient and remainder divmod(10,3) → (3,1)

pow(a,b) a raised to power b pow(2,3) → 8

int(x) Converts to integer int(3.14) → 3

bin(x) Converts to binary string bin(10) → '0b1010'

oct(x) Converts to octal string oct(10) → '0o12'

hex(x) Converts to hexadecimal string hex(10) → '0xa'

Example:
n = -15
print(abs(n)) # 15
print(divmod(17,5)) # (3,2)
print(bin(10)) # 0b1010

5. Integer Properties
1. Immutable: Operations produce a new integer object.
x=5
print(id(x))
x=x+1
print(id(x)) # New memory address
2. Arbitrary precision: Python integers can be very large, limited only by
memory.
big = 123456789012345678901234567890
print(big * 2)

Key Points
1. Integers are whole numbers and immutable.
2. They support all arithmetic operations and conversion functions.
3. Python integers can be very large, unlike many other programming languages.
4. Understanding integer operations is foundational for working with numbers in
Python.

Floating Point Numbers in Python


1. Introduction
• Floating Point (float) numbers represent real numbers with a decimal point.
• Used for fractional values and precise calculations.
• Floats are immutable objects in Python.
Examples:
a = 3.14 # positive float
b = -0.5 # negative float
c = 2.0 # float representing integer

2. Floating Point Literals


• Can be written in decimal or scientific notation:

Format Example Value

Decimal 3.14 3.14

Negative Decimal -0.75 -0.75

Scientific 2e3 2000.0

Negative Scientific -4.5e-2 -0.045


Example:
x = 1.23e2 # 1.23 × 10² = 123.0
y = -4.56e-3 # -0.00456
print(x, y) # 123.0 -0.00456

3. Operations on Floats
• Supports arithmetic operations similar to integers:
a = 5.5
b = 2.0
print(a + b) # 7.5
print(a - b) # 3.5
print(a * b) # 11.0
print(a / b) # 2.75
print(a // b) # 2.0 (floor division returns float)
print(a % b) # 1.5 (remainder)
print(a ** b) # 30.25 (exponentiation)

4. Floating Point Functions


Python provides several built-in functions for floats:

Function Description Example

float(x) Converts value to float float(10) → 10.0

abs(x) Absolute value abs(-3.5) → 3.5

round(x[,n]) Rounds to n decimals (default 0) round(3.1415,2) → 3.14

pow(x,y) x raised to power y pow(2.5,2) → 6.25

divmod(x,y) Returns quotient and remainder divmod(7.5,2) → (3.0,1.5)


Example:
x = 7.25
y = 2.0
print(divmod(x,y)) # (3.0,1.25)
print(round(3.14159,3)) # 3.142

5. Floating Point Precision


• Floats may not always be exact due to binary representation.
• Use round() to handle precision issues:
a = 0.1 + 0.2
print(a) # 0.30000000000000004
print(round(a,2)) # 0.3
• For high-precision calculations, use the decimal module:
from decimal import Decimal
a = Decimal('0.1')
b = Decimal('0.2')
print(a + b) # 0.3

Key Points
1. Floats represent real numbers with decimals.
2. They support all arithmetic operations, similar to integers.
3. Floats are immutable objects.
4. Be aware of precision issues and use round() or decimal for exact calculations.
Complex Numbers in Python
1. Introduction
• Complex numbers are numbers with a real part and an imaginary part.
• In Python, the imaginary unit is represented by j or J.
• Complex numbers are immutable objects.
General form:
z = a + bj

where:
• (a) = real part
• (b) = imaginary part
Example:
z1 = 2 + 3j
z2 = -1 + 4j
print(z1, z2) # (2+3j) (-1+4j)

2. Creating Complex Numbers


• Directly using literals:
z = 5 + 2j
print(type(z)) # <class 'complex'>
• Using complex() function:
z = complex(5, 2) # complex(real, imag)
print(z) # (5+2j)
• Access real and imaginary parts:
print([Link]) # 5.0
print([Link]) # 2.0
3. Operations on Complex Numbers
• Python supports arithmetic operations on complex numbers:
z1 = 2 + 3j
z2 = 1 - 1j
print(z1 + z2) # (3+2j) Addition
print(z1 - z2) # (1+4j) Subtraction
print(z1 * z2) # (5+1j) Multiplication
print(z1 / z2) # (0.5+2.5j) Division
• Note: Floor division // and modulus % are not supported for complex
numbers.

4. Built-in Functions for Complex Numbers

Function Description Example

abs(z) Magnitude (modulus) of complex number abs(3+4j) → 5.0

Create a complex number from real r and


complex(r,i) complex(2,3) → 2+3j
imaginary i

[Link] Real part (2+3j).real → 2.0

[Link] Imaginary part (2+3j).imag → 3.0

(2+3j).conjugate() → 2-
[Link]() Returns complex conjugate
3j

Example:
z = 3 + 4j
print(abs(z)) # 5.0
print([Link]()) # (3-4j)
5. Complex Number Properties
1. Immutable: Arithmetic creates new objects.
2. *Supports +, -, , /, and conjugate operations.
3. Cannot use floor division or modulus.
4. Useful for engineering, physics, and mathematics calculations involving
imaginary numbers.

Key Points
1. Complex numbers have real and imaginary parts.
2. Use complex(r,i) or a + bj to create them.
3. Python allows arithmetic operations, magnitude (abs()), and conjugate
(.conjugate()).
4. Floor division and modulus are unsupported.

Operators for Numbers in Python


1. Introduction
• Operators allow us to perform operations on numeric values.
• Python supports arithmetic, comparison, logical, assignment, and bitwise
operators for numbers.
• Numbers include int, float, and complex (note: some operators are not
supported for complex numbers).

2. Arithmetic Operators

Operator Description Example

+ Addition 5+3→8

- Subtraction 5-3→2

* Multiplication 5 * 3 → 15

/ Division (float) 5 / 2 → 2.5


Operator Description Example

// Floor Division 5 // 2 → 2

% Modulus (remainder) 5 % 2 → 1

** Exponentiation 2 ** 3 → 8

Example:
x = 10
y=3
print(x + y) # 13
print(x / y) # 3.3333333333333335
print(x ** y) # 1000
Note: Floor division (//) works for int and float but not complex.

3. Comparison Operators
• Compare numeric values and return True or False.

Operator Description Example

== Equal to 5 == 5 → True

!= Not equal 5 != 3 → True

> Greater than 5 > 3 → True

< Less than 5 < 3 → False

>= Greater or equal 5 >= 5 → True

<= Less or equal 3 <= 5 → True

Example:
a=7
b = 10
print(a < b) # True
print(a == b) # False
Note: Complex numbers cannot be compared with <, >, <=, >=. Only == and != are
allowed.

4. Assignment Operators

Operator Description Example

= Assign value x = 10

+= Add and assign x += 5 → x = 15

-= Subtract and assign x -= 2 → x = 13

*= Multiply and assign x *= 2 → x = 26

/= Divide and assign x /= 2 → x = 13.0

//= Floor divide and assign x //= 2 → x = 6.0

%= Modulus and assign x %= 4 → x = 2.0

**= Exponentiation and assign x **= 3 → x = 8.0

5. Logical Operators
• Logical operators are used in conditional checks with numbers:

Operator Description Example

and True if both operands True (5 > 3) and (2 < 4) → True

or True if any operand True (5 < 3) or (2 < 4) → True

not Negates operand not(5 > 3) → False


6. Bitwise Operators (for integers only)

Operator Description Example

& AND 5&3→1

` ` OR

^ XOR 5^3→6

~ NOT ~5 → -6

<< Left Shift 5 << 1 → 10

>> Right Shift 5 >> 1 → 2

Example:
a = 5 # 0b0101
b = 3 # 0b0011
print(a & b) # 1 (0b0001)
print(a | b) # 7 (0b0111)
Note: Bitwise operators cannot be used with floats or complex numbers.

Key Points
1. Arithmetic operators: + - * / // % **
2. Comparison operators: == != < > <= >=
3. Logical operators: and, or, not
4. Assignment operators: =, +=, -=, *=, /=, //=, %=, **=
5. Bitwise operators: Only for integers.
6. Complex numbers cannot use <, >, <=, >=, //, % or bitwise operators.
Built-in Functions for Numbers in Python
1. Introduction
• Python provides many built-in functions to perform operations on numbers.
• These functions work for integers, floats, and in some cases complex
numbers.
• They are ready to use without importing any module.

2. Common Numeric Built-in Functions

Function Description Example

abs(x) Returns absolute value abs(-5) → 5

round(x[, n]) Rounds x to n decimal places round(3.1415,2) → 3.14

pow(x, y[, z]) Returns x**y or x**y % z if z given pow(2,3) → 8

divmod(x, y) Returns quotient and remainder as a tuple divmod(10,3) → (3,1)

int(x) Converts to integer int(3.14) → 3

float(x) Converts to float float(5) → 5.0

complex(x[, y]) Converts to complex number complex(2,3) → 2+3j

max(a, b, …) Returns maximum value max(1,5,3) → 5

min(a, b, …) Returns minimum value min(1,5,3) → 1

sum(iterable) Returns sum of all elements sum([1,2,3]) → 6

3. Examples of Numeric Built-in Functions


# Absolute Value
x = -10
print(abs(x)) # 10
# Rounding
pi = 3.14159
print(round(pi, 2)) # 3.14
# Power
print(pow(2, 3)) #8
print(pow(2, 3, 5)) # 3 (2**3 % 5)
# Divmod
print(divmod(17, 4)) # (4,1)
# Conversions
print(int(3.99)) #3
print(float(5)) # 5.0
print(complex(2, 3)) # (2+3j)
# Max, Min, Sum
numbers = [5, 1, 7, 3]
print(max(numbers)) # 7
print(min(numbers)) # 1
print(sum(numbers)) # 16

4. Functions for Complex Numbers

Function Description Example

abs(z) Magnitude (modulus) abs(3+4j) → 5.0

[Link] Real part (2+3j).real → 2.0

[Link] Imaginary part (2+3j).imag → 3.0

[Link]() Complex conjugate (2+3j).conjugate() → 2-3j

Example:
z = 3 + 4j
print(abs(z)) # 5.0
print([Link], [Link]) # 3.0 4.0
print([Link]()) # (3-4j)
Key Points
1. abs(), round(), pow(), divmod() are useful for calculations.
2. Conversions like int(), float(), complex() allow type changes.
3. max(), min(), sum() help work with lists or sequences of numbers.
4. Complex numbers have .real, .imag, .conjugate() and can use abs().
5. Most functions are immutable, i.e., they do not change the original number.

Related Modules for Numbers in Python


Python provides modules that extend number operations for more complex
calculations.
1. math Module
• Used for real number mathematics (integers and floats).
• Functions include:

Function Description Example

[Link](x) Square root [Link](16) → 4.0

[Link](x,y) x raised to power y [Link](2,3) → 8.0

[Link](x) Round up [Link](3.2) → 4

[Link](x) Round down [Link](3.8) → 3

[Link](x) Factorial [Link](5) → 120

[Link](x) Sine (x in radians) [Link]([Link]/2) → 1.0

[Link](x) Cosine [Link](0) → 1.0

[Link](x, base) Logarithm with base [Link](8,2) → 3.0

Example:
import math
x=9
print([Link](x)) # 3.0
print([Link](5)) # 120
print([Link](3.14)) # 4

2. cmath Module
• Used for complex numbers.
• Functions include [Link](), [Link](), [Link](), etc.
Example:
import cmath
z = 2 + 3j
print([Link](z)) # (1.6741492280355401+0.8959774761298381j)
print(abs(z)) # 3.605551275463989

3. decimal Module
• For high precision floating point numbers.
• Avoids floating-point rounding errors.
Example:
from decimal import Decimal
a = Decimal('0.1')
b = Decimal('0.2')
print(a + b) # 0.3

4. fractions Module
• For rational numbers as fractions.
Example:
from fractions import Fraction
f1 = Fraction(3,4)
f2 = Fraction(1,2)
print(f1 + f2) # 5/4
Sequences – Strings
1. Introduction
• Strings are immutable sequences of characters in Python.
• Enclosed in single ' ', double " ", or triple quotes ''' ''' / """ """.
• Strings support indexing, slicing, and iteration.
Example:
s1 = "Python"
s2 = 'Hello'
s3 = """This is a multi-line
string."""
print(s1, s2)

2. String Operations

Operation Example Result

Concatenation "Hello" + "World" 'HelloWorld'

Repetition "Hi"*3 'HiHiHi'

Indexing "Python"[0] 'P'

Slicing "Python"[1:4] 'yth'

Length len("Python") 6

Membership 'y' in "Python" True

Example:
s = "Python"
print(s[0]) #P
print(s[1:4]) # yth
print(len(s)) # 6
print('t' in s) # True
3. Immutability
• Strings cannot be changed in-place. Any operation creates a new string:
s = "Python"
# s[0] = 'J' # ERROR
s = "J" + s[1:]
print(s) # Jython

Lists in Python
1. Introduction
• Lists are ordered, mutable sequences of elements.
• Elements can be of any type: numbers, strings, other lists, etc.
• Lists are defined using square brackets [].
Example:
# List of integers
numbers = [1, 2, 3, 4]
# List of mixed types
mixed = [1, "Hello", 3.14, True]
# Empty list
empty = []
print(numbers, mixed, empty)

2. List Operations

Operation Example Result

Indexing numbers[0] 1

Negative Indexing numbers[-1] 4

Slicing numbers[1:3] [2,3]


Operation Example Result

Concatenation [1,2] + [3,4] [1,2,3,4]

Repetition [1,2]*2 [1,2,1,2]

Membership 3 in numbers True

Length len(numbers) 4

Example:
lst = [10, 20, 30, 40]
print(lst[1]) # 20
print(lst[-1]) # 40
print(lst[1:3]) # [20, 30]
print(lst + [50, 60]) # [10, 20, 30, 40, 50, 60]

3. Modifying Lists
• Lists are mutable, so elements can be changed, added, or removed.
Changing an element:
lst = [1,2,3]
lst[0] = 100
print(lst) # [100,2,3]
Adding elements:
[Link](4) # Adds 4 at end
[Link](1, 50) # Inserts 50 at index 1
print(lst) # [100,50,2,3,4]
Removing elements:
[Link](50) # Removes first occurrence of 50
[Link]() # Removes last element
del lst[0] # Deletes element at index 0
print(lst)
4. List Functions

Function Description Example

len(lst) Returns number of elements len([1,2,3]) → 3

max(lst) Returns maximum value max([1,4,2]) → 4

min(lst) Returns minimum value min([1,4,2]) → 1

sum(lst) Returns sum of elements sum([1,2,3]) → 6

sorted(lst) Returns sorted list sorted([3,1,2]) → [1,2,3]

list() Converts iterable to list list((1,2,3)) → [1,2,3]

5. Nested Lists
• Lists can contain other lists (2D or multidimensional lists).
matrix = [[1,2,3], [4,5,6], [7,8,9]]
print(matrix[0]) # [1,2,3]
print(matrix[1][2]) # 6

Key Points
1. Lists are ordered and mutable.
2. Support indexing, slicing, and iteration.
3. Can contain elements of any type.
4. Common operations: append, insert, remove, pop, sort, reverse.
5. Nested lists allow matrix-like structures.
Tuples in Python
1. Introduction
• Tuples are ordered, immutable sequences of elements.
• Unlike lists, tuples cannot be changed once created.
• Tuples are defined using parentheses () or simply commas.
Example:
# Tuple of integers
numbers = (1, 2, 3, 4)
# Tuple of mixed types
mixed = (1, "Hello", 3.14, True)
# Single element tuple
single = (5,)
# Empty tuple
empty = ()
print(numbers, mixed, single, empty)

2. Tuple Operations

Operation Example Result

Indexing numbers[0] 1

Negative Indexing numbers[-1] 4

Slicing numbers[1:3] [2,3]

Concatenation (1,2) + (3,4) (1,2,3,4)

Repetition (1,2)*2 (1,2,1,2)

Membership 3 in numbers True

Length len(numbers) 4
Example:
t = (10, 20, 30, 40)
print(t[1]) # 20
print(t[-1]) # 40
print(t[1:3]) # (20, 30)
print(t + (50,60)) # (10,20,30,40,50,60)

3. Immutability
• Tuples cannot be modified: no element assignment, deletion, or append.
t = (1,2,3)
# t[0] = 100 # ERROR
# [Link](4) # ERROR
# You can create a new tuple instead
t = (100,) + t[1:]
print(t) # (100, 2, 3)

4. Tuple Functions

Function Description Example

len(t) Number of elements len((1,2,3)) → 3

max(t) Maximum value max((1,4,2)) → 4

min(t) Minimum value min((1,4,2)) → 1

sum(t) Sum of elements sum((1,2,3)) → 6

tuple() Converts iterable to tuple tuple([1,2,3]) → (1,2,3)

5. Nested Tuples
• Tuples can contain other tuples (or lists) for multi-dimensional data:
nested = ((1,2,3), (4,5,6), (7,8,9))
print(nested[0]) # (1,2,3)
print(nested[1][2]) # 6

6. Tuple vs List

Feature Tuple List

Mutability Immutable Mutable

Syntax () []

Use Case Fixed data Changing data

Performance Faster Slower

Key Points
1. Tuples are ordered, immutable sequences.
2. Support indexing, slicing, and iteration.
3. Useful for fixed data or multiple return values.
4. Can contain mixed types and nested structures.
5. Slightly faster than lists due to immutability.

Mapping Types in Python – Dictionaries


1. Introduction
• Dictionaries are unordered, mutable collections of key-value pairs.
• Keys must be unique and immutable (like strings, numbers, tuples).
• Values can be of any type (numbers, strings, lists, dictionaries, etc.).
• Dictionaries are defined using curly braces {} or the dict() function.
Example:
# Creating a dictionary
student = {"name": "Alice", "age": 20, "grade": "A"}
# Using dict()
employee = dict(id=101, name="John", dept="HR")
print(student)
print(employee)

2. Accessing Dictionary Elements


• Access value using key:
print(student["name"]) # Alice
print([Link]("dept")) # HR
• Using get() avoids KeyError if the key does not exist:
print([Link]("roll_no", "Not Found")) # Not Found

3. Modifying Dictionaries
• Add or update key-value pairs:
student["age"] = 21 # Update existing key
student["roll_no"] = 101 # Add new key
print(student)
• Remove elements:
[Link]("grade") # Removes key 'grade'
del student["roll_no"] # Deletes key 'roll_no'
[Link]() # Clears all key-value pairs

4. Dictionary Operations

Operation/Method Description Example

len(d) Number of key-value pairs len(student) → 3

[Link]() Returns all keys [Link]()

[Link]() Returns all values [Link]()


Operation/Method Description Example

[Link]() Returns key-value pairs as tuples [Link]()

in Check if key exists 'name' in student → True

update() Merge another dictionary [Link]({"city":"NY"})

Example:
student = {"name": "Alice", "age": 20}
print([Link]()) # dict_keys(['name','age'])
print([Link]()) # dict_values(['Alice',20])
print([Link]()) # dict_items([('name','Alice'),('age',20)])

5. Nested Dictionaries
• Dictionaries can contain other dictionaries for structured data:
school = {
"class1": {"name": "Alice", "age": 10},
"class2": {"name": "Bob", "age": 11}
}
print(school["class1"]["name"]) # Alice

Key Points
1. Dictionaries are unordered, mutable collections of key-value pairs.
2. Keys must be immutable and unique, values can be any type.
3. Useful for mapping one value to another (like name → age).
4. Supports access, update, delete, and iteration over keys, values, or items.
5. Nested dictionaries allow hierarchical data storage.
Set Types in Python
1. Introduction
• Sets are unordered collections of unique elements.
• They are mutable, but elements must be immutable (numbers, strings,
tuples).
• Sets do not allow duplicates.
• Defined using curly braces {} or the set() function.
Example:
# Creating sets
numbers = {1, 2, 3, 4, 4, 5} # Duplicate 4 is removed
letters = set(['a','b','c','a']) # Duplicate 'a' removed
print(numbers) # {1, 2, 3, 4, 5}
print(letters) # {'a', 'b', 'c'}
• Empty set must be created using set(), not {} (which creates an empty
dictionary).
empty_set = set()
print(empty_set) # set()

2. Set Operations
Sets support mathematical operations like union, intersection, difference, and
symmetric difference.
A = {1,2,3,4}
B = {3,4,5,6}
print(A | B) # Union → {1,2,3,4,5,6}
print(A & B) # Intersection → {3,4}
print(A - B) # Difference → {1,2}
print(A ^ B) # Symmetric Difference → {1,2,5,6}
3. Modifying Sets

Method Description Example

add(x) Adds element x [Link](10)

remove(x) Removes element x, KeyError if not found [Link](2)

discard(x) Removes element x if exists [Link](2)

pop() Removes and returns a random element [Link]()

clear() Removes all elements [Link]()

update(set2) Adds all elements from another set [Link](B)

Example:
A = {1,2,3}
[Link](4)
[Link](2)
print(A) # {1, 3, 4}

4. Set Membership
• Check if an element exists in a set:
fruits = {"apple","banana","cherry"}
print("apple" in fruits) # True
print("orange" not in fruits) # True

5. Set Comparison
• Subset, Superset, and Disjoint:
A = {1,2,3}
B = {1,2,3,4,5}
print([Link](B)) # True
print([Link](A)) # True
print([Link]({4,5})) # True
Key Points
1. Sets are unordered, mutable collections with unique elements.
2. Support mathematical operations: union (|), intersection (&), difference (-),
symmetric difference (^).
3. Elements can be added, removed, or updated.
4. Useful for removing duplicates, membership tests, and set operations.
5. Empty set must be created using set(), not {}.

You might also like