0% found this document useful (0 votes)
12 views49 pages

Unit 1 Python

python notes
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)
12 views49 pages

Unit 1 Python

python notes
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/ 49

Unit 1: INTRODUCTION TO PYTHON

What is Python?
 Python is a high-level, interpreted, and beginner-friendly
programming language created by Guido van Rossum in 1991.
 Python is called a high-level language because it is closer to human
language than machine language, making it easier for humans to
read, write, and understand.
 It is widely known for its simplicity and readability, making it one of
the best choices for beginners while still being powerful enough for
professionals.
 Python emphasizes code readability and allows programmers to
express concepts in fewer lines of code compared to languages like
C++ or Java.

Why Python is important?


1. Simple & Readable
 Python code looks like plain English, so even beginners can
understand it.
 Example:
print("Hello, World!")

This prints Hello, World! on the screen.


In C, you would need several lines of code to do the same.
2. Fewer Lines of Code
 You can do the same task in fewer lines compared to languages
like Java or C++.
 Example:
Python:
numbers = [1, 2, 3, 4]
print(sum(numbers))

Java (similar task):


int[] numbers = {1, 2, 3, 4};
int sum = 0;
for(int num : numbers) sum += num;
System.out.println(sum);

3. Versatile
 You can use Python in web development, data analysis, AI,
automation, game development, and more.
 Example:
Web development → Django, Flask
Data analysis → Pandas, NumPy
AI → TensorFlow, PyTorch

4. Free & Open Source


 You can download and use Python for free.
 Many libraries are also free.

Who Uses Python?


 YouTube – manages video streaming and backend services.
 Google – uses Python for automation and AI tools.
 NASA – uses Python for scientific computing.
 Yahoo – uses Python for backend and data processing.

The IDLE Python Development Environment


Definition:
IDLE (Integrated Development and Learning Environment) is Python’s built-in
Integrated Development Environment (IDE). It is also known as Interactive
Mode because it allows you to write and run Python code immediately.

What is an IDE?
An IDE is a collection of software tools designed to help in program
development. It usually includes:
1. Editor – For writing and modifying programs.
2. Translator/Interpreter – For executing the code you write.
3. Debugger – For controlling the program’s execution and finding errors
(bugs).

Popular Python IDEs


IDE Name Highlights

Professional, feature-rich, great for large


PyCharm
projects

VS Code Lightweight, lots of extensions

Best for data science & scientific


Spyder
programming

Thonny Beginner-friendly

IDLE Comes with Python, simple to use

Python installation:
 Windows – Go to chrome and search download python for windows or
you can directly open by the link https://www.python.org/downloads/
 For macOS – Go to chrome or safari and search download python for
macOs it will redirect you to the link or you can open directly
https://www.python.org/downloads/macos/
 To check python version open the terminal in window/macOS and write

the command python3 –version.

Modules in Python
A module is simply a Python file (.py) containing code — such as functions,
classes, or variables — that can be imported into another Python program.
Modules help you reuse code instead of writing it from scratch.

Types of Modules in Python


1. Built-in Modules 🏗
 These come pre-installed with Python.
 No need to install anything; you can use them right away.
 Examples:
o math → for mathematical operations
o os → for interacting with the operating system
o random → for generating random numbers

Example:
import random

print(random.randint(1, 10))
# Random number between 1 and 10

2. External Modules 📦
 These are not included with Python by default.
 You must install them using the Python package manager pip.
 Examples:
o pandas → for data analysis
o numpy → for numerical computations
o matplotlib → for creating graphs and charts
o flask → for web development

PIP (Package Installer for Python)


Definition:
PIP is Python’s package manager — a tool that lets you install and manage
additional Python libraries that are not included in the standard Python library
Key Points
1. Full Form: PIP stands for Package Installer for Python.
2. Purpose: Allows us to install, upgrade, and uninstall extra Python
packages from the internet (mainly from PyPI – Python Package Index).
3. Why Use It: Python’s built-in library is powerful, but sometimes we need
extra tools like NumPy (for math), Pandas (for data), or Flask (for web
apps).

Basic Commands
Action Command Example

Install pip install numpy

pip install --upgrade


Upgrade
numpy

Uninstall pip uninstall numpy

Check Version pip --version

List Packages pip list

Indentation in Python:
In Python, indentation means adding spaces or tabs at the beginning of a line
to define the structure of your code.
Unlike many other programming languages that use curly braces {} to mark
code blocks, Python uses indentation to show which statements belong
together.

1. Why indentation is important


 It tells Python which statements are inside a block (like inside a
function, loop, or if-condition).
 Incorrect indentation will cause an IndentationError.
 It also makes your code more readable.
2. Rules of indentation
1. Same block → same indentation level
All statements inside the same block must have the same number of
spaces.
2. Recommended spaces:
Python's style guide (PEP 8) recommends 4 spaces for each
indentation level.

3. Example
# Correct indentation
if True:
print("Inside the if block")
print("Still inside the if block")
print("Outside the if block")

# Incorrect indentation (will cause error)


if True:
print("Inside the if block")

print("Wrong extra space here") # ❌


4. Key point to remember
Indentation is not just for looks in Python — it’s part of the syntax.
If your indentation is wrong, the program won’t run at all.

COMMENTS IN PYTHON:
Definition:
Comments are lines in the code that are not executed by Python.
They are used to:
 Explain the code for better understanding.
 Add notes such as author name, date, or version.
 Temporarily disable parts of code during testing.

Types of Comments in Python:


1. Single-Line Comments:
 Use the # symbol at the start of the line.
 Everything after # is ignored by Python.

Example:
# This program adds two numbers
a = 5 # first number
b = 3 # second number
print(a + b) # output will be 8

3. Multi-Line Comments:
 Option 1: Use # at the start of each line.
 Option 2: Use triple quotes (""" """ or ''' ''') — even though these are
technically multi-line strings, they can be used as comments.

Example (using #):


# This is a program to demonstrate multi-line comments
# It will print a simple message
print("Hello, Python!")

Example (using triple quotes):


"""
Author: John Doe
Date: 13-Aug-2025
Description: This program prints a welcome message.
"""
print("Welcome to Python Programming!")
Identifiers in Python
An identifier is simply a name that you give to something in your program so
you can refer to it later.
You use identifiers to name variables, functions, classes, modules, and other
objects in Python.
Think of an identifier like a label on a container — the label doesn’t store
anything itself, but it tells you what’s inside.

Python Variables:
Definition:
A variable is a name used to store data in memory so we can use and change it
later in a program.
Think of a variable like a container with a label — the label is the variable
name, and inside is the value.
Rules for Naming Variables
1. Must start with a letter (a–z, A–Z) or underscore _.
2. Cannot start with a number.
3. Can only contain letters, numbers, and underscores.
4. Case-sensitive (Age and age are different).
5. Should not use Python keywords (if, while, class, etc.).

📜 Rules for Naming Variables


✅ Allowed ❌ Not Allowed

Start with a letter or _ (underscore) Start with a number

Can contain letters, digits, _ Use special characters (@, $, %)

Case-sensitive (Name ≠ name) Use Python keywords (if, class, for)


PROBLEM:
Which of the following identifier names are invalid in Python? Give reasons for
each invalid case.

i roll_Number
ii 99Bottles
iii price$tag
iv Student Name
v _averageScore
vi Class
vii my-variable
viii marks_2025
Creating Variables:
# Assigning values to variables
name = "Alice" # String
age = 20 # Integer
price = 99.99 # Float

print(name) # Alice
print(age) # 20
print(price) # 99.99

Changing Values:
x = 10
x = 25 # Value changed
print(x) # 25

Assigning Multiple Variables:


a, b, c = 5, 10, 15
print(a, b, c) # 5 10 15
Assigning Same Value to Multiple Variables:
x = y = z = 100
print(x, y, z) # 100 100 100

Variable Types are Dynamic:


 In Python, you don’t need to declare the type — it’s decided
automatically based on the value.
x=5 # int
x = "Hello" # now str
print(type(x))

A variable is like a school bag with your name on it — you can put books, lunch,
or clothes inside. What’s inside (value) can change anytime.

Python Data types:


Definition:
A data type defines the kind of value a variable can store and what operations
can be performed on it.
1.Numeric Types
a)Integers (int)– Whole numbers (positive, negative, or zero).
Example: print(24), print(-24),print(100)

age = 20
temperature = -5
print(type(age)) # <class 'int'>
b) Float (float) – Numbers with decimal points.
pi = 3.14
price = -99.99
print(type(pi)) # <class 'float'>
2. String Type (str) - Stores text (sequence of characters) in quotes.
“vishal” “hello” ‘vishal’ ‘hello’ ‘‘‘ hello’’’
name = "Python"
greeting = 'Hello'

print(type(name)) # <class 'str'>

4.Boolean – Stores True or False values. T and F should be in capital otherwise


it will return you an error.
is_sunny = True
is_raining = False
print(type(is_sunny)) # <class 'bool'>

5.None – a = None N should be in capital


Example: a = None
print(a)
Output = None

Keywords are reserved words in python:


PROBLEM:
What is the output of the following code?
city = "Delhi"
print(city)
print(id(city))

The id() function in Python returns a unique integer that represents the
identity (memory address) of the object during its lifetime.
 city = "Delhi" → creates a string object "Delhi" and assigns it to the
variable city.
 print(city) → displays the value "Delhi".
 print(id(city)) → displays an integer that shows where in memory Python
has stored that "Delhi" object.
Example:
a = "Delhi"
b=a
print(id(a)) # e.g., 140597356414768
print(id(b)) # same as id(a) because a and b refer to same object

Practical / Output Questions


1.
x=5
y = "5"
print(x + int(y))
What will be the output?
2.
name = "Alice"
age = 20
print(name, age)
What will be displayed?
3.
a = 10
b=a
a = 20
print(b)
What will be printed and why?
4.
x = "Hello"
x = x + " World"
print(x)
What is the final value of x?
5.
_city = "Delhi"
print(_city)
Is this variable name valid? Why?
6.
num1 = 10
num2 = 3.5
result = num1 + num2
print(result)

Example of Identifiers and Keywords


Here's a simple example demonstrating the use of identifiers and keywords:
# Keywords: def, return
# Identifiers: add_numbers, a, b, result

def add_numbers(a, b): # 'def' is keyword, 'add_numbers', 'a', 'b' are identifiers
result = a + b # 'result' is identifier
return result # 'return' is keyword

# Using the function


first_num = 5 # 'first_num' is identifier
second_num = 3 # 'second_num' is identifier
sum = add_numbers(first_num, second_num) # 'sum' is identifier
print(sum) # 'print' is identifier (built-in function)

PROBLEM: What happens if you try to use a variable that has not been defined
in Python?
a) Python will automatically define the variable.
b) Python will prompt the user to define the variable.
c) Python will raise a NameError.
d) Python will ignore the variable.

VARIABLE TYPES & SCOPE IN PYTHON


1. Python is Dynamically Typed
 You don’t need to declare the type of a variable before using it.
 The type is automatically decided based on the value assigned.
Example:
a=5 # 'a' is an integer
a = "Hello" # Now 'a' becomes a string (type changes automatically)

2. Variable Scope
 Scope means where in the program a variable can be accessed.
 There are mainly two types of scope in Python:
A. Global Scope
 A variable declared outside all functions is global.
 It can be accessed anywhere in the program, including inside
functions.
Example:
global_var = 10 # Global variable

def my_function():
print(global_var) # Accessing global variable inside a function

my_function()
print(global_var) # Accessing global variable outside a function

Output:
10
10

B. Local Scope
 A variable declared inside a function is local.
 It can only be accessed within that function.
Example:
def my_function():
local_var = 20 # Local variable
print(local_var) # Works here

my_function()

print(local_var) # ❌ Error: local_var is not defined outside the function

3. Local Variable with Same Name as Global


 If you declare a local variable with the same name as a global
variable, Python treats them separately.
Example:
x = 10 # Global variable

def my_function():
x = 20 # Local variable with same name as global
print(x) # Prints local variable value

my_function()
print(x) # Prints global variable value

Output:
20
10

4. Example Problem
s = "I love GeeksforGeeks" # Global variable

def f():
print("Inside Function:", s) # Accessing global variable inside function

f()
print("Outside Function:", s) # Accessing global variable outside function

Output:
Inside Function: I love GeeksforGeeks
Outside Function: I love GeeksforGeeks

MUTABLE & IMMUTABLE VARIABLES IN PYTHON:


1. Immutable Types
 Immutable means: Once created, the value cannot be changed.
 Instead of changing the same object, Python creates a new object
when you try to modify it.
 Examples:
-Numbers (int, float)
-Strings (str)
-Tuples (tuple)
Example:
a = "Hello"
print("a =", a)
print("Type:", type(a))
print("ID before change:", id(a)) # Memory address before change

a = "World" # Assigning new value creates a new object


print("a =", a)
print("Type:", type(a))
print("ID after change:", id(a)) # Different memory address
Output:
a = Hello
Type: <class 'str'>
ID before change: 140... (example)
a = World
Type: <class 'str'>
ID after change: 140... (different)
Note: The memory address (id) changes, meaning a new object was created.

2. Mutable Types
 Mutable means: The value can be changed without creating a new
object.
 Examples:
-Lists (list)
-Dictionaries (dict)
-Sets (set)
Example:
a = [1, 2] # List (mutable)
print("a =", a)
print("Type:", type(a))
print("ID before change:", id(a)) # Memory address before change

a.append(3) # Modifying the list


print("a =", a)
print("Type:", type(a))
print("ID after change:", id(a)) # Same memory address

Output:

a = [1, 2]
Type: <class 'list'>
ID before change: 140... (example)
a = [1, 2, 3]
Type: <class 'list'>
ID after change: 140... (same)
Note: The memory address stays the same, meaning the same object was
modified.
Key Differences Table

Feature Mutable Immutable

Can value change? ✅ Yes ❌ No

Memory address Same after modification Changes when value changes

Examples list, dict, set int, float, str, tuple

PROBLEM: What is the output of the following code:


a=” coding is fun”
print(a[1])
print(type(a))
del a
print(a)

Multiple Assignment in Python:


You can assign values to multiple variables in a single statement:
x, y, z = 3, 4, 5 # Multiple assignment in one line

You can also assign the same value to multiple variables:


x=y=z=5 # All three variables refer to the same value

Example 1: Using == and is:


x=y=z=5
print(x == y) # True → values of x and y are equal
print(x is z) # True → x and z refer to the same memory location
Explanation:
 == checks if values are the same.
 is checks if both variables point to the same memory object.
 Since x, y, and z were assigned the same object (5), both checks are True.
Example 2: With Lists:
a = [1, 2]
b = [1, 2]
print(a == b) # True → contents are the same
print(id(a)) # Memory address of list a
print(a is b) # False → different memory objects
print(id(b)) # Memory address of list b

Explanation:
 a == b is True because the elements [1, 2] are the same.
 id(a) and id(b) are different because they are two separate list objects.
 a is b is False because they are stored in different memory locations.
Key Point:
 == → compares values
 is → compares memory addresses (object identity)
Question:
# Multiple assignment: same value to all
x = y = z = 10

print(x == y) # True → values are equal


print(x is z) # True → same memory object
# Multiple assignment: different values
a, b, c = 1, 2, 3
print(a, b, c) # 1 2 3

# Example with lists


list1 = [5, 6]
list2 = [5, 6]

print(list1 == list2) # True → contents match


print(list1 is list2) # False → different objects in memory

SWAPPING VALUES IN PYTHON:


Swapping means exchanging the values of two variables.
Example: if x=10 and y=50, after swapping: x=50 y=10.

1.Swapping Without a Third Variable (Python Shortcut)


Python allows swapping in one line using tuple unpacking.
Example:
x = 10
y = 50

x, y = y, x # Swap values

print("x =", x) # 50
print("y =", y) # 10

How it works:
 x, y = y, x creates a tuple (y, x) and assigns it back to (x, y).

3. Swapping Using Arithmetic Operations:


You can swap values without a temporary variable using addition and
subtraction.
Example:
x = 10
y = 50

x = x + y # x becomes 60
y = x - y # y becomes 10
x = x - y # x becomes 50

print("x =", x) # 50
print("y =", y) # 10

How it works:
1. Add both values and store in x.
2. Subtract new y from x to get the old x value into y.
3. Subtract new y from x to get the old y value into x.

OPERATORS IN PYTHON:
In Python, operators are special symbols that perform operations on variables
and values. Here's a comprehensive overview of different types of operators in
Python:
1. Arithmetic Operators:
Arithmetic operators are used to perform mathematical operations.

Operator Description Example Result

+ Addition 5+3 8

- Subtraction 5-3 2

* Multiplication 5*3 15

/ Division (float result) 5/2 2.5

// Floor division (integer part) 5 // 2 2

% Modulus (remainder) 5%2 1


Operator Description Example Result

** Exponentiation (power) 2 ** 3 8

Example: Adding Two Numbers:


num1 = 1.5
num2 = 6.3
sum = num1 + num2
print('The sum of two numbers is', sum)
Output:
The sum of two numbers is 7.8

PROBLEMS:
Problem 1:
print(9 % 4)
Problem 2:
# Addition (+)
a=5
b=3
print("Addition:", a + b) # 8

# Subtraction (-)
a = 10
b=4
print("Subtraction:", a - b) # 6

# Multiplication (*)
x=7
y=6
print("Multiplication:", x * y) # 42

# Division (/)
m = 15
n=2
print("Division:", m / n) # 7.5

# Floor Division (//)


m = 15
n=2
print("Floor Division:", m // n) # 7

# Modulus (%)
p=9
q=4
print("Remainder:", p % q) # 1

# Exponentiation (**)
base = 2
power = 5
print("Power:", base ** power) # 32
2.Comparison Operators:
Comparison operators are used to compare two values.
They return either:
 True → if the comparison is correct
 False → if the comparison is incorrect
List of Comparison Operators:

Operator Meaning Example (a = 5, b = 3) Result

== Equal to a == b False

!= Not equal to a != b True

> Greater than a>b True

< Less than a<b False

>= Greater than or equal to a >= b True

<= Less than or equal to a <= b False

Example Program:
a=5
b=3

print(a == b) # False (5 is not equal to 3)


print(a != b) # True (5 is not equal to 3)
print(a > b) # True (5 is greater than 3)
print(a < b) # False (5 is not less than 3)
print(a >= b) # True (5 is greater or equal to 3)
print(a <= b) # False (5 is not less or equal to 3)

Output:
False
True
True
False
True
False
2. Assignment Operators:
Definition:
Assignment operators are used to assign values to variables.
They can also combine assignment with another operation (addition,
subtraction, multiplication, etc.).

Operator Example Meaning Equivalent To

= x=5 Assign value x=5

+= x += 3 Add and assign x=x+3

-= x -= 2 Subtract and assign x=x-2

*= x *= 4 Multiply and assign x=x*4

/= x /= 5 Divide and assign (float result) x=x/5

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

%= x %= 3 Modulus and assign x=x%3

**= x **= 2 Exponent and assign x = x ** 2

Example Program:
x = 10 # = assignment
print("x =", x)

x += 5 # x = x + 5
print("After += 5:", x)

x -= 3 # x = x - 3
print("After -= 3:", x)

x *= 2 # x = x * 2
print("After *= 2:", x)

x /= 4 # x = x / 4
print("After /= 4:", x)

x //= 2 # x = x // 2
print("After //= 2:", x)

x %= 3 # x = x % 3
print("After %= 3:", x)

x **= 4 # x = x ** 4
print("After **= 4:", x)
Output:
x = 10
After += 5: 15
After -= 3: 12
After *= 2: 24
After /= 4: 6.0
After //= 2: 3.0
After %= 3: 0.0
After **= 4: 0.0
Easy Assignment Operator Problems:
Problem 1: Increase Salary by Bonus
salary = 20000
bonus = 5000

salary += bonus # Add bonus to salary


print("Updated Salary:", salary)
Problem 2: Decrease Price After Discount
price = 1000
discount = 200

price -= discount
print("Price after discount:", price)
Problem 3: Double the Pocket Money
money = 150
money *= 2
print("Doubled money:", money)

Problem 4: Convert Rupees to Dollars


rupees = 500
rupees /= 82 # Assuming 1 USD = 82 INR
print("Dollars:", rupees)

Problem 5: Find Remainder Using Assignment


num = 29
num %= 5
print("Remainder:", num)
Problem 6: Power of a Number
x=2
x **= 5
print("2 to the power 5 is:", x)
3. LOGICAL OPERATORS:
Definition:
Logical operators are used to combine conditional statements.
They return a Boolean value (True or False).

Types of Logical Operators:

Example (a=5,
Operator Description Result
b=3)

Returns True if both conditions (a > 2) and (b <


And True
are True 5)

Returns True if at least one (a > 10) or (b <


Or True
condition is True 5)

Reverses the result (True → False,


Not not(a > 2) False
False → True)

Example Program:
a=5
b=3

# AND operator
print((a > 2) and (b < 5)) # True (both conditions True)
print((a > 2) and (b > 5)) # False (second condition False)
# OR operator
print((a > 10) or (b < 5)) # True (second condition True)
print((a > 10) or (b > 5)) # False (both False)

# NOT operator
print(not(a > 2)) # False (because a > 2 is True)
print(not(b > 5)) # True (because b > 5 is False)

Output:
True
False
True
False
False
True

Example Program:
# Example 1: AND operator
a=5
b=3
print(a > 2 and b < 5) # True
print(a > 2 and b > 5) # False

# Example 2: OR operator
x = 10
y = 20
print(x > 15 or y > 15) # True
print(x > 15 or y < 15) # False

# Example 3: NOT operator


p = True
q = False
print(not p) # False
print(not q) # True

# Example 4: Combined conditions


m=7
n=4
print((m % 2 == 1) and (n % 2 == 0)) # True (m is odd AND n is even)

# Example 5: Mixing all operators


age = 25
has_ticket = False
print((age >= 18 and has_ticket) or (age < 18 and not has_ticket))

Logical Operators – Quick Quiz


# Q1
print(10 > 5 and 8 < 6)
#?

# Q2
print(4 == 4 or 7 < 2)
#?
# Q3
print(not (3 >= 3))
#?

# Q4
print((5 % 2 == 0) and (10 % 5 == 0))
#?

# Q5
print((7 > 3) or (2 > 10) and (4 < 1))
#?
5.BITWISE OPERATORS:
Definition:
Bitwise operators perform operations bit by bit on integers.
They treat numbers as a sequence of binary digits (0 and 1).

List of Bitwise Operators:

Example (a=5,
Operator Name Binary Example Result
b=3)

0101 & 0011 →


& AND a&b 1
0001

` ` OR `a b`

0101 ^ 0011 →
^ XOR a^b 6
0110

NOT (invert
~ ~a ~0101 → 1010 -6
bits)

0101 << 1 →
<< Left Shift a << 1 10
1010
Example (a=5,
Operator Name Binary Example Result
b=3)

0101 >> 1 →
>> Right Shift a >> 1 2
0010

Example Program:
a = 5 # 0101 in binary
b = 3 # 0011 in binary

print("a & b =", a & b) # 1


print("a | b =", a | b) # 7
print("a ^ b =", a ^ b) # 6
print("~a =", ~a) # -6 (inverts bits)
print("a << 1 =", a << 1) # 10 (shift left by 1)
print("a >> 1 =", a >> 1) # 2 (shift right by 1)

Output:
a&b=1
a|b=7
a^b=6
~a = -6
a << 1 = 10
a >> 1 = 2

Bitwise Operators – Simple Examples


# Example 1: Bitwise AND
a = 5 # Binary: 0101
b = 3 # Binary: 0011
print(a & b) # 1 (0001)

# Example 2: Bitwise OR
print(a | b) # 7 (0111)

# Example 3: Bitwise XOR


print(a ^ b) # 6 (0110)

# Example 4: Bitwise NOT


print(~a) # -6 (inverts bits)

# Example 5: Left Shift


print(a << 1) # 10 (shifts bits left by 1)

# Example 6: Right Shift


print(a >> 1) # 2 (shifts bits right by 1)

Membership Operators:
Definition:
Membership operators are used to check if a value exists in a sequence (like a
string, list, tuple, set, or dictionary).

Operators:
1. in → Returns True if the value is found in the sequence.
2. not in → Returns True if the value is not found in the sequence.
Examples:

Example 1: With a String


text = "Python is fun"

print("Python" in text) # True → "Python" is inside text


print("java" in text) # False → "java" not found
print("fun" not in text) # False → "fun" is present, so not in returns False
Example 2: With a Set
numbers = {1, 2, 3, 4, 5}

print(3 in numbers) # True → 3 exists in the set


print(10 not in numbers) # True → 10 not in the set

Example 3: With a Range


r = range(1, 10) # Numbers from 1 to 9

print(5 in r) # True → 5 is in the range


print(10 in r) # False → 10 is not in the range

Example 4: With a String (character check)


word = "hello"

print('h' in word) # True → 'h' found in "hello"


print('x' not in word) # True → 'x' not found

5. Identity Operators:
Definition:
Identity operators are used to check if two variables point to the same
object in memory.
Operators:
1. is → Returns True if two variables refer to the same object (same
memory address).
2. is not → Returns True if two variables do not refer to the same object.
Example 1: With Numbers
x=5
y=5
print(x is y) # True → both point to the same integer object in memory
print(x is not y) # False → they are the same object

Example 2: With Lists


a = [1, 2, 3]
b = [1, 2, 3]

print(a == b) # True → values are the same


print(a is b) # False → stored in different memory locations
print(a is not b)# True → they are not the same object

Example 3: Multiple Assignment


x = y = [4, 5]
print(x is y) # True → both variables point to the same list

Key Difference:
 == → compares values (data stored inside objects)
 is → compares identity (memory address of the objects)
TYPE( ) FUNCTION AND TYPECASTING:
TYPE( ) FUNCTION:
Definition:
The type() function is used to find the data type of a variable or value.
Examples:
x = 10
print(type(x)) # <class 'int'>

y = 3.14
print(type(y)) # <class 'float'>

z = "Hello"
print(type(z)) # <class 'str'>

Typecasting:
Definition:
Typecasting means converting one data type into another.
Python provides built-in functions for this.

Common Typecasting Functions:

Function Converts to

int() Integer

Floating-point
float()
number

str() String

list() List
Function Converts to

tuple() Tuple

set() Set

Example: Typecasting in Action


# Integer to float
a=5
b = float(a)
print(b, type(b)) # 5.0 <class 'float'>

# String to integer
s = "100"
n = int(s)
print(n + 50) # 150

# List to tuple
my_list = [1, 2, 3]
my_tuple = tuple(my_list)
print(my_tuple, type(my_tuple)) # (1, 2, 3) <class 'tuple'>

Important Notes for Students:


 You can only typecast if it’s possible — e.g., int("abc") will cause an
error.
 type() just tells you the type; it does not convert.
 Typecasting changes the type.

INPUT ( ) FUNCTION:
Definition:
The input() function is used to take input from the user as a string.
Whatever the user types is always returned as a string, even if they enter a
number.

Syntax:
variable_name = input("Your message here: ")
The message inside "" is called a prompt — it tells the user what to enter.

Example 1: Taking a String Input


name = input("Enter your name: ")
print("Hello,", name)

Output (if user enters "Amit"):


Enter your name: Amit
Hello, Amit
Example 2: Taking a Number Input
age = input("Enter your age: ")
print(type(age)) # <class 'str'>
Even if you type 25, Python still stores it as a string.

Example 3: Converting Input to Integer or Float


(Using typecasting with input())
age = int(input("Enter your age: ")) # Convert to integer
height = float(input("Enter your height in meters: ")) # Convert to float

print("Age:", age, type(age))


print("Height:", height, type(height))

Key Points for Students


 input() always returns a string.
 Use typecasting (int(), float(), etc.) if you need numeric input.
 Always give a clear prompt to the user.

PRINT() FUNCTION:
Definition:
The print() function is used to display output on the screen.
It can print strings, numbers, variables, or even multiple values together.
Syntax:
print(object1, object2, ..., sep=' ', end='\n')
 object1, object2, ... → values you want to print
 sep → separator between values (default is a space " ")
 end → what to print at the end (default is a newline \n)
Example 1: Printing Text
print("Hello, World!")
Output:
Hello, World!

Example 2: Printing Variables


name = "Amit"
age = 20
print("Name:", name, "Age:", age)

Output:
Name: Amit Age: 20

Example 3: Using sep Parameter


print("Python", "Java", "C++", sep=", ")

Output:
Python, Java, C++

Example 4: Using end Parameter


print("Hello", end=" ")
print("World")

Output:
Hello World

Key Points for Students:


 You can print multiple values in one statement.
 Use sep to change the separator between values.
 Use end to change what happens at the end of the print statement.
 You can print strings, numbers, variables, or expressions.
DATA TYPES IN PYTHON:
Definition:
In Python, data types are categories that classify the type of value a variable
holds.
The data type determines what kind of operations can be done on that value.

1. Numeric Types
 int → Whole numbers (positive, negative, or zero)
 float → Decimal (floating-point) numbers
 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'>

2. Sequence Types
 str → String (text, enclosed in quotes ' ' or " ")
 list → Ordered, changeable collection of items []
 tuple → Ordered, unchangeable collection of items ()
Example:
name = "Python" # str
numbers = [1, 2, 3, 4] # list
coordinates = (10, 20) # tuple
3. Set Types
 set → Unordered collection with no duplicates {}
 frozenset → Same as set but immutable (unchangeable)
Example:
fruits = {"apple", "banana", "mango"} # set
unique_numbers = frozenset([1, 2, 2, 3]) # frozenset

4. Mapping Type
 dict → Key–value pairs {key: value}
Example:
student = {"name": "John", "age": 21}

5. Boolean Type
 bool → Represents True or False
Example:
is_active = True
is_logged_in = False
6. None Type
 None → Represents the absence of a value
Example:
x = None
Tip for Students:
Use the type() function in Python to check the data type of any value.
Example:
print(type(42)) # int
print(type(3.14)) # float
print(type("Hello")) # str
print(type([1, 2, 3])) # list
Python Blocks:
In Python, a block is a group of statements that are executed together under a
certain condition or context. Blocks are an essential part of Python’s structure
because they determine which statements belong to loops, functions,
conditionals, or classes.
Unlike some other programming languages that use curly braces {} to define
blocks, Python uses indentation (spaces or tabs) to define blocks. This makes
the code cleaner and more readable.

1. Indentation in Python
 Indentation is the number of spaces at the beginning of a line.
 Python requires consistent indentation within a block.
 Typically, 4 spaces per indentation level are used.
 All statements at the same indentation level belong to the same
block.

2. Blocks in Different Contexts


A. Conditional Blocks (if, elif, else)
age = 18

if age >= 18:


print("You are an adult.")
print("You can vote.")
else:
print("You are a minor.")
print("You cannot vote.")
Explanation:
 The lines inside if and else are indented, forming their respective
blocks.
 Only the indented statements under the if or else run depending on
the condition.
B. Loop Blocks (for, while)
for i in range(3):
print("Iteration:", i)
print("This is inside the loop.")

print("This is outside the loop.")


Explanation:
 The two print statements inside the loop are indented and part of the
loop block.
 The last print is outside the loop block because it is not indented.

C. Function Blocks
def greet(name):
print("Hello,", name)
print("Welcome to Python.")

greet("Ankit")
Explanation:
 The two print statements form the function block.
 They execute only when the function is called.

D. Class Blocks
class Person:
def __init__(self, name):
self.name = name

def greet(self):
print("Hello,", self.name)
p = Person("Ankit")
p.greet()
Explanation:
 The methods inside the class (__init__ and greet) are indented to
form blocks inside the class.
 The statements inside each method are further indented.

3. Key Points About Python Blocks


 Indentation defines the block; curly braces {} are not used.
 All statements at the same indentation level belong to the same
block.
 Consistent indentation is required; mixing tabs and spaces can cause
errors.
 Blocks can be nested inside other blocks, e.g., a loop inside an if
statement.

You might also like