Unit 1 Python
Unit 1 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.
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
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).
Thonny Beginner-friendly
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
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.
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
Basic Commands
Action Command Example
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.
3. Example
# Correct indentation
if True:
print("Inside the if block")
print("Still inside the if block")
print("Outside the if block")
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.
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.
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.).
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
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.
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'
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
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
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.
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()
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
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
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
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
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).
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.
+ Addition 5+3 8
- Subtraction 5-3 2
* Multiplication 5*3 15
** Exponentiation (power) 2 ** 3 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
# 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:
== Equal to a == b False
Example Program:
a=5
b=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.).
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
price -= discount
print("Price after discount:", price)
Problem 3: Double the Pocket Money
money = 150
money *= 2
print("Doubled money:", money)
Example (a=5,
Operator Description Result
b=3)
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
# 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).
Example (a=5,
Operator Name Binary Example Result
b=3)
` ` 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
Output:
a&b=1
a|b=7
a^b=6
~a = -6
a << 1 = 10
a >> 1 = 2
# Example 2: Bitwise OR
print(a | b) # 7 (0111)
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:
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
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.
Function Converts to
int() Integer
Floating-point
float()
number
str() String
list() List
Function Converts to
tuple() Tuple
set() Set
# 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'>
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.
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!
Output:
Name: Amit Age: 20
Output:
Python, Java, C++
Output:
Hello World
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
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.
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.