UNIT -I
INTRODUCTION TO PYTHON
Python is a high-level, interpreted programming language known for its simplicity and readability. It was
created by Guido van Rossum and first released in 1991. Python supports multiple programming paradigms,
including procedural, object-oriented, and functional programming.
WHY LEARN PYTHON?
• Easy to Learn: Python has a simple syntax that is easy to understand and write.
• Versatile: Used in web development, data science, artificial intelligence, scientific computing etc.
• Large Community: Extensive documentation and a large community for support.
• Cross-Platform: Runs on Windows, macOS, Linux, and more.
• Extensive Libraries: A rich set of libraries and frameworks for various applications.
PYTHON SYNTAX AND STRUCTURE
• Indentation: Python uses indentation to define code blocks instead of braces {}.
• Comments: Use # for single-line comments and ''' or """ for multi-line comments.
• Statements: Each statement typically ends with a newline, but you can use a semicolon ; to separate
statements on the same line.
PYTHON DATA TYPES
CATEGORY DATA TYPE DESCRIPTION EXAMPLE
int Integer numbers 5, -10
Numeric float Floating-point numbers 3.14, -0.001
complex Complex numbers 1 + 2j
str Strings (sequence of characters) "Hello", 'Python'
Sequence list Ordered, mutable collection [1, 2, 3]
tuple Ordered, immutable collection (1, 2, 3)
Mapping dict Key-value pairs {"name": "Alice"}
set Unordered, unique collection {1, 2, 3}
Set
frozenset Immutable set frozenset({1, 2, 3})
Boolean bool Truth values True, False
bytes Immutable sequence of bytes b"Hello"
Binary bytearray Mutable sequence of bytes bytearray(b"Hello")
memoryview Memory view of an object memoryview(b"Hello")
None None Represents no value None
EXAMPLE
You can check the type of a variable using the type() function.
x=5
print(type(x)) # <class 'int'>
y = "Hello"
print(type(y)) # <class 'str'>
TYPE CONVERSION IN PYTHON
Type conversion (also known as type casting) is the process of converting a value from one data type to
another. Python provides built-in functions to perform type conversion. There are two types of type
conversion in Python:
Implicit Type Conversion: Automatically performed by Python.
Explicit Type Conversion: Manually performed by the programmer using built-in functions.
1- IMPLICIT TYPE CONVERSION
Python automatically converts one data type to another when needed, without any user intervention. This
usually happens when performing operations between different data types.
EXAMPLE
# Integer and Float
a=5 # int
b = 3.14 # float
result = a + b # Python converts 'a' to float implicitly
print(result) # 8.14 (float)
2. EXPLICIT TYPE CONVERSION
Explicit type conversion is done manually using built-in functions. Python provides the following functions
for explicit type conversion:
FUNCTION DESCRIPTION EXAMPLE
int() Converts to integer int(3.14) → 3
float() Converts to float float(5) → 5.0
str() Converts to string str(100) → "100"
bool() Converts to boolean bool(1) → True
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]) → {1, 2}
dict([(1, 'a'), (2, 'b')]) → {1: 'a', 2: 'b'}
dict() Converts to dictionary
PYTHON OPERATORS
CATEGORY OPERATOR DESCRIPTION
Arithmetic +, -, *, /, //, %, ** Mathematical operations
Comparison ==, !=, >, <, >=, <= Compare values
Logical and, or, not Combine conditions
Assignment =, +=, -=, *=, /=, etc. Assign values
Bitwise &, ` , ^, ~, <<, >>` Binary operations
Membership in, not in Check for membership
Identity is, is not Compare object identity
Ternary if-else Shorthand for conditions
MEMBERSHIP OPERATORS
Used to check if a value exists in a sequence (e.g., list, tuple, string).
OPERATOR DESCRIPTION EXAMPLE
in True if value exists "a" in "apple" → True
not in True if value does not exist "b" not in "apple" → True
IDENTITY OPERATORS
Used to compare the memory locations of two objects.
OPERATOR DESCRIPTION EXAMPLE
is True if both objects are the same x is y
is not True if both objects are not the same x is not y
PYTHON BLOCKS
A block is a group of statements that are executed together as a unit. Blocks are defined by their indentation
level, which is a key feature of Python's syntax. Unlike other programming languages that use braces {} or
keywords like begin and end to define blocks, Python uses consistent indentation to group statements.
KEY CHARACTERISTICS OF PYTHON BLOCKS
INDENTATION:
• Blocks are created by indenting code. The standard convention is to use 4 spaces per indentation
level (though tabs can also be used, spaces are recommended).
• All statements within a block must have the same indentation level.
SCOPE:
• Blocks define the scope of variables, loops, conditionals, and functions.
• Variables defined inside a block are local to that block unless explicitly declared as global.
COMMON BLOCK TYPES:
• Conditional Blocks: Used with if, elif, and else statements.
• Loop Blocks: Used with for and while loops.
• Function Blocks: Used to define functions with the def keyword.
• Class Blocks: Used to define classes with the class keyword.
• Exception Handling Blocks: Used with try, except, finally, and else statements.
EXAMPLES OF PYTHON BLOCKS
1. Conditional Block (if-else)
x = 10
if x > 5:
print("x is greater than 5") # This is part of the if block
else:
print("x is less than or equal to 5") # This is part of the else block
2. Loop Block (for loop)
for i in range(3):
print(i) # This is part of the for block
print("Inside loop") # Also part of the for block
print("Outside loop") # Outside the for block
3. Function Block (def)
def greet(name):
message = f"Hello, {name}!" # This is part of the function block
print(message)
greet("Alice")
4. Class Block (class)
class Dog:
def __init__(self, name):
self.name = name # Part of the class block
def bark(self):
print(f"{self.name} says woof!") # Part of the class block
5. Exception Handling Block (try-except)
try:
result = 10 / 0 # Part of the try block
except ZeroDivisionError:
print("Cannot divide by zero!") # Part of the except block
DECLARING AND USING NUMERIC DATA TYPES
1. INTEGER (INT)
# Declaring an integer
x = 10
y = -5
# Printing the type and value
print(type(x)) # Output: <class 'int'>
print(x) # Output: 10
print(y) # Output: -5
2. FLOAT (FLOAT)
# Declaring a float
a = 3.14
b = -0.001
# Printing the type and value
print(type(a)) # Output: <class 'float'>
print(a) # Output: 3.14
print(b) # Output: -0.001
3. COMPLEX (COMPLEX)
# Declaring a complex number
c = 1 + 2j
d = 3 - 4j
# Printing the type and value
print(type(c)) # Output: <class 'complex'>
print(c) # Output: (1+2j)
print(d) # Output: (3-4j)
CHECKING NUMERIC TYPES
You can check if a variable is of a specific numeric type using the isinstance() function:
EXAMPLE
print(isinstance(x, int)) # Output: True
print(isinstance(a, float)) # Output: True
print(isinstance(c, complex)) # Output: True