Python Installation and Basic Operations Guide
Python Installation and Basic Operations Guide
a=10
b=9
c=a+b
print("The sum of two number is : ",c)
a=10
b=9
c=a-b
print("The sub of two number is : ",c)
a=10
b=9
c=a*b
print("The mul of two number is : ",c)
a=10
b=9
c=a/b
print("The div of two number is : ",c)
a=10
b=9
c=a%b
print("The modules of two number is : ",c)
a=10
b=9
c=a//b
print("The floor division of two number is : ",c)
a=10
b=9
c=a**b
print("The Exponent of two number is : ",c)
op:-
The sum of two number is : 19
The sub of two number is : 1
The mul of two number is : 90
The div of two number is : 1.1111111111111112
The modules of two number is : 1
The floor division of two number is : 1
The Exponent of two number is : 1000000000
Enter a Variable : 13
enter a variable : 14
The sum of two number is : 27
Enter a Variable : 20
enter a variable : 4
The sub of two number is : 16
Enter a Variable : 98
enter a variable : 8
The mul of two number is : 784
Enter a Variable : 77
enter a variable : 87
The div of two number is : 0.8850574712643678
Enter a Variable : 45
enter a variable : 45
The modules of two number is : 0
Enter a Variable : 76
enter a variable : 3
The floor division of two number is : 25
Enter a Variable : 47
enter a variable : 35
The exponent of two number is :
33375288443717156087424983475677821467175245957737145158543
op:
Enter the principle amount : 23
Enter the rate of interest : 43
Enter the time taken : 55
The simple intrest is : 543.95
[Link] of Rectangle
Algorithm:
1. Start
2. Read length and breadth
3. Calculate area = length × breadth
4. Display the area
5. Stop
Code:
length = float(input("Enter the length of rectangle: "))
breadth = float(input("Enter the breadth of rectangle: "))
area = length * breadth
print("Area of Rectangle:", area)
Output:
Enter the length of rectangle: 8
Enter the breadth of rectangle: 4
Area of Rectangle: 32.0
[Link] of Square
Algorithm:
1. Start
2. Read side
3. Calculate area = side × side
4. Display the result
5. Stop
Code:
side = float(input("Enter the side of square: "))
area = side * side
print("Area of Square:", area)
Output:
Enter the side of square: 5
Area of Square: 25.0
[Link] of Rectangle
Algorithm:
1. Start
2. Read length and breadth
3. Calculate perimeter = 2 × (length + breadth)
4. Display the result
5. Stop
Code:
length = float(input("Enter the length of rectangle: "))
breadth = float(input("Enter the breadth of rectangle: "))
perimeter = 2 * (length + breadth)
print("Perimeter of Rectangle:", perimeter)
Output:
Enter the length of rectangle: 8
Enter the breadth of rectangle: 4
Perimeter of Rectangle: 24.0
[Link] of Parallelogram
Algorithm:
1. Start
2. Read base and height
3. Calculate area = base × height
4. Display the area
5. Stop
Code:
base = float(input("Enter the base of parallelogram: "))
height = float(input("Enter the height of parallelogram: "))
area = base * height
print("Area of Parallelogram:", area)
Output:
Enter the base of parallelogram: 6
Enter the height of parallelogram: 4
Area of Parallelogram: 24.0
[Link] of Rhombus
Algorithm:
1. Start
2. Read both diagonals (d1 and d2)
3. Calculate area = (d1 × d2) / 2
4. Display the area
5. Stop
Code:
d1 = float(input("Enter first diagonal: "))
d2 = float(input("Enter second diagonal: "))
area = (d1 * d2) / 2
print("Area of Rhombus:", area)
Output:
Enter first diagonal: 8
Enter second diagonal: 6
Area of Rhombus: 24.0
[Link] of Trapezium
Algorithm:
1. Start
2. Read base1, base2, and height
3. Calculate area = ½ × (base1 + base2) × height
4. Display the result
5. Stop
Code:
base1 = float(input("Enter base1: "))
base2 = float(input("Enter base2: "))
height = float(input("Enter height: "))
area = 0.5 * (base1 + base2) * height
print("Area of Trapezium:", area)
Output:
Enter base1: 6
Enter base2: 8
Enter height: 4
Area of Trapezium: 28.0
[Link] of Cube
Algorithm:
1. Start
2. Read side of cube
3. Calculate area = 6 × side²
4. Display the result
5. Stop
Code:
side = float(input("Enter the side of cube: "))
area = 6 * (side ** 2)
print("Area of Cube:", area)
Output:
Enter the side of cube: 4
Area of Cube: 96.0
2. Conditional Statements
[Link] whether a character is a vowel or consonant
Algorithm:
1. Start
2. Read a letter from the user
3. Check if the letter is one of: a, e, i, o, u
4. If yes → print “Vowel”
5. Otherwise → print “Consonant”
6. Stop
Code:
letter= str(input("Enter a letter: "))
if letter in ("a", "e", "i", "o", "u", "A", "E", "I", "O", "U"):
print("The letter is vowel")
else:
print("The letter is consonant")
Output:
Enter a letter: e
The letter is vowel
or
Enter a letter: B
The letter is consonant
number=703.5
print(type(number))
word="sakshi"
print(type(word))
letter="A"
print(type(letter))
a=True
print(type(a))
op:
<class 'int'>
<class 'float'>
<class 'str'>
<class 'str'>
<class 'bool'>
Or
Loops in Python
Loops are used to repeat a block of code multiple times without writing it again and again.
1. for loop
Algorithm:
1. Start
4. If True,
5. Stop
Code:
if num > 1:
if num % i == 0:
break
else:
else:
Enter a number: 7
Prime number
Algorithum
1. Start
5. After loop ends, print the value of fact as the factorial of the number
6. Stop
Program:
fact = fact * i
Output:
Enter a number: 5
Algorithm:
1. Start
2. Read a number n
3. Repeat i from 1 to 10
4. Print n * i
5. Stop
Code:
Output:
Enter a number: 5
5x1=5
5 x 2 = 10…
5 x 10 = 50
2. while loop
• Reverse a number
• Palindrome number
Palindrome Number
Algorithm:
Start
Input a number or text and store it in a variable text
Reverse the string using slicing:
→ reversed_text = text[::-1]
Display the reversed text using print(reversed_text)
Stop
Program:
text=input("Enter a number: ",)
reversed_text=text[::-1]
print(reversed_text)
Output:
Enter a number: mom
Mom
Data Collections
• List ,Tuple ,Set, Dictionary, Indexing ,Slicing, All common operations ,Simple
programs.
1. LIST
Definition:
• Ordered
• Changeable (mutable)
• Allows duplicates
Example:
a = [10, 20, 30, 40]
Indexing:
print(a[0]) # 10
print(a[-1]) # 40
Slicing:
print(a[1:3]) # [20, 30]
print(a[:3]) # [10,20,30]
Operations:
[Link](50)
[Link](1, 99)
[Link](20)
[Link]()
[Link]()
[Link]()
Program:
a=[10,20,30,40]
[Link](50)
[Link](20)
print(a)
Algorithm
1. Start
2. Initialize a list with predefined values
3. Loop forever:
o Display menu: Add, Delete, Display, Sort, Reverse, Search, Exit
o Read user choice
o If choice = 1:
▪ Read a value
▪ Append value to list
o Else if choice = 2:
▪ Delete last element using pop()
o Else if choice = 3:
▪ Display the list
o Else if choice = 4:
▪ Sort the list
o Else if choice = 5:
▪ Reverse the list
o Else if choice = 6:
▪ Read search value
▪ If value in list → print found
▪ Else → print not found
o Else if choice = 7:
▪ Print exiting
▪ Break loop
o Else print invalid choice
4. Stop
Code:-
l=[]
n = int(input("How many elements you want to add initially? "))
for i in range(n):
ele = int(input("Enter element: "))
[Link](ele)
print(l)
while True:
print("[Link] [Link] [Link] [Link] [Link] [Link] [Link]")
choice = int(input("ENTER YOUR CHOICE: "))
if choice == 1:
add = int(input("Enter element to add: "))
[Link](add)
print(l)
elif choice==2:
rem=int(input("Enter a element to remove : ",))
if rem in l:
[Link](rem)
print("The element is removed from the list")
else:
print("The element is not found ")
elif choice == 3:
print(l)
elif choice == 4:
[Link]()
print(l)
elif choice == 5:
[Link]()
print(l)
elif choice == 6:
item = int(input("Enter element to search: "))
if item in l:
print("Item is present")
else:
print("Item not found")
elif choice == 7:
print("Exiting...")
break
else:
print("Invalid choice, enter between 1–7")
2. TUPLE
Definition:
• Ordered
• Not changeable (immutable)
• Allows duplicates
Example:
t = (10, 20, 30, 40)
Indexing:
print(t[0]) # 10
Slicing:
print(t[1:3]) # (20, 30)
Tuple can't change:
This is wrong ↓
[Link](20)
Program:
t = (5, 10, 15, 20)
print("Length = ", len(t))
print("Max = ", max(t))
print("Min = ", min(t))
Algorithm: Tuple Operations
1. Start
2. Define a tuple t with some integer values
3. Display the tuple
4. Repeat the following steps
a. Display menu
1. Length
2. Maximum
3. Minimum
4. Display
5. Search
6. Exit
b. Read the user's choice
c. If choice = 1
Print length of tuple using len(t)
d. Else if choice = 2
Print maximum value using max(t)
e. Else if choice = 3
Print minimum value using min(t)
f. Else if choice = 4
Display entire tuple
g. Else if choice = 5
Read item
If item present in tuple
Print “Item found”
Else
Print “Item not found”
h. Else if choice = 6
Print “Exiting” and break the loop
i. Else
Print “Invalid choice”
7. Stop
Code:-
temp = []
n = int(input("Enter how many elements you want: "))
for i in range(n):
ele = int(input(f"Enter element "))
[Link](ele)
t = tuple(temp)
print("Your tuple is:", t)
while True:
print("[Link] [Link] [Link] [Link] [Link] [Link]")
choice = int(input("Enter your choice : "))
if choice == 1:
print("The length of the tuple is :", len(t))
elif choice == 2:
print("The maximum number in the tuple is :", max(t))
elif choice == 3:
print("The minimum number in the tuple is :", min(t))
elif choice == 4:
print(t)
elif choice == 5:
item = int(input("Enter an item to search : "))
if item in t:
print("The item is present")
else:
print("The item is not present")
elif choice == 6:
print("The program is exiting")
break
else:
print("Invalid choice! Enter between 1 to 6")
3. SET
Definition:
• Unordered
• No duplicates
• Mutable
Example:
s = {10, 20, 30, 10}
print(s) # {10,20,30}
Operations:
[Link](40)
[Link](20)
[Link]([50,60])
Set operations (very important):
A = {1,2,3}
B = {3,4,5}
print([Link](B)) # {1,2,3,4,5}
print([Link](B)) # {3}
print([Link](B)) # {1,2}
Algorithm: Start
1. Create an empty set s
2. Repeat the following steps:
a. Display menu:
1. Add
2. Delete
3. Display
4. Search
5. Exit
b. Read the user’s choice
c. If choice = 1
Ask user to enter an element
Add the element to the set using add()
d. Else if choice = 2
If set is not empty
Remove an element using pop()
Else
Display “Set is empty”
e. Else if choice = 3
Display the set
f. Else if choice = 4
Read the search item
If item present in set
Display “Item present”
Else
Display “Item not present”
g. Else if choice = 5
Display “Exiting”
Break the loop
h. Else
Display “Invalid choice”
3. Stop
Code:
s=set()
n = int(input("How many elements you want to add initially? "))
for i in range(n):
ele = int(input("Enter element: "))
[Link](ele)
print(s)
while True:
print("[Link] [Link] [Link] [Link] 5EXIT")
choice=int(input("Enter your choice : "))
if choice==1:
add=int(input("Enter a element which you wat to be added :",))
[Link](add)
print(s)
elif choice==2:
rem = int(input("Enter an element which you want to remove : "))
if rem in s:
[Link](rem)
print("The element removed from the list : ", s)
else:
print("The element not in the list : ", s)
elif choice==3:
print(s)
elif choice==4:
item=int(input("Enter a item which you want to search : ",))
if item in s:
print("THe item is present in the set ")
else:
print("The item is not present in the set ")
elif choice==5:
print("The program is exiting ")
break
else:
print("The choice is invalid choose between 1 to 5 ")
4. DICTIONARY
Definition:
• Key:Value pairs
• Mutable
• No duplicates in keys
Example:
d = {"name": "Sakshi", "age": 20}
Access:
print(d["name"])
Add / Update:
d["city"] = "Bengaluru"
Delete:
[Link]("age")
Loop:
for x,y in [Link]():
print(x, y)
Algorithm: Perform Dictionary Operations Using User Choice
1. Start
2. Create a dictionary d with some initial key-value pairs
3. Repeat the following steps:
a. Display the menu:
1. Add
2. Delete
3. Display Keys
4. Display Values
5. Display Both
6. Sort
7. Exit
b. Read user choice
c. If choice = 1
Read a key and value
Add them to the dictionary
d. Else if choice = 2
If dictionary not empty
Remove last inserted item using popitem()
Else
Display “Dictionary is empty”
e. Else if choice = 3
Display all keys
f. Else if choice = 4
Display all values
g. Else if choice = 5
Display all key–value pairs
h. Else if choice = 6
Sort dictionary items using sorted()
i. Else if choice = 7
Display “Exiting” and break loop
j. Else
Display “Invalid choice”
4. Stop
Code:-
d = {}
n = int(input("How many key-value pairs? "))
for i in range(n):
k = input("Enter key: ")
v = input("Enter value: ")
d[k] = v
while True:
print("[Link] [Link] [Link] KEYS [Link] VALUES [Link] BOTH [Link] BOTH
[Link]")
choice = int(input("Enter your choice: "))
if choice == 1:
key = input("Enter your key: ")
value = int(input("Enter your value: "))
d[key] = value
print(d)
elif choice == 2:
if len(d) > 0:
[Link]()
print(d)
else:
print("Dictionary is empty!")
else:
print("Dictionary is empty, nothing to delete")
elif choice == 3:
print([Link]())
for x in [Link]():
print(x)
elif choice == 4:
print([Link]())
for x in [Link]():
print(x)
elif choice == 5:
print([Link]())
for x in [Link]():
print(x)
elif choice == 6:
print( sorted([Link]()))
elif choice == 7:
print("Exiting the program")
break
else:
print("Invalid choice")
5. INDEXING
Used to access elements:
a = [10,20,30]
print(a[1]) # 20
print(a[-1]) # 30
6. SLICING
Get part of a list/string/tuple:
a = [10,20,30,40,50]
print(a[1:4]) # [20,30,40]
print(a[:3]) # [10,20,30]
print(a[2:]) # [30,40,50]
print(a[::2]) # [10,30,50]
Code:-
import array
arr = [Link]('i', [])
n = int(input("How many numbers? "))
for i in range(n):
num = int(input("Enter number: "))
[Link](num)
print("Array =", arr)
while True:
print("[Link] [Link] [Link] [Link] [Link]")
choice=int(input("Enter the choice : ",))
if choice==1:
val=int(input("Enter the elememt to Add in the array : ",))
[Link](val)
print("The element Add to the array is : ",val )
elif choice==2:
val=int(input("Enter the elememt to Remove from the array : ",))
if val in arr:
[Link](val)
print("The element removed from the array is : ",val)
else:
print("The element not in the array ")
elif choice==3:
print("The array is : ",arr)
elif choice==4:
[Link]()
print("The reverse array is : ",arr)
elif choice==5:
print("exiting")
break
else:
print("The choce is invalid")
op:-
[Link] [Link] [Link] [Link] [Link]
Enter the choice : 1
Enter the elememt to Add in the array : 34
The element Add to the array is : 34
[Link] [Link] [Link] [Link] [Link]
Enter the choice : 2
Enter the elememt to Remove from the array : 22
The element not in the array
[Link] [Link] [Link] [Link] [Link]
Enter the choice : 2
Enter the elememt to Remove from the array : 45
The element removed from the array is : 45
[Link] [Link] [Link] [Link] [Link]
Enter the choice : 3
The array is : array('i', [12, 44, 65, 89, 54, 89, 54, 90, 294, 62, 34])
[Link] [Link] [Link] [Link] [Link]
Enter the choice : 4
The reverse array is : array('i', [34, 62, 294, 90, 54, 89, 54, 89, 65, 44, 12])
[Link] [Link] [Link] [Link] [Link]
Enter the choice : 5
exiting
print(a)
elif choice==4:
[Link]()
print(a)
elif choice==5:
print("exiting")
break
else:
print("Invalid choice")
String
Creating and Assigning Strings
name = "Sakshi"
greet = 'Hello'
Indexing
print(name[0]) # S
print(name[-1]) # i
Algorithm
1. Start
2. Read the input string
3. Initialize counters: u = l = d = s = 0
4. For each character in the string
o If it’s between ‘A’ and ‘Z’, increment u
o Else if between ‘a’ and ‘z’, increment l
o Else if between ‘0’ and ‘9’, increment d
o Else increment s
5. Display all counts
6. Stop
Code:-
text=input("Enter the text : ")
u=0
l=0
n=0
s=0
for i in range (len(text)):
if text[i]>='A' and text[i]<='Z':
u+=1
elif text[i]>='a' and text[i]<='z':
l+=1
elif text[i]>='0' and text[i]<='9':
n+=1
else:
s+=1
print("The text is : ",text)
print("The number of upper case is :",u)
print("The number of lower case is :",l)
print("The number is :",n)
print("The number of Special character is :",s)
Op:-
print("Number of uppercase letters:", u)
print("Number of lowercase letters:", l)
print("Number of digits:", d)
print("Number of special characters:", s)
Reverse a String
s = input("Enter a string: ")
print("Reversed string:", s[::-1])
Palindrome Check
s = input("Enter a string: ")
if s == s[::-1]:
print("Palindrome")
else:
print("Not Palindrome")
FUNCTIONS IN PYTHON
Algorithm: Function-Based Calculator
Step 1: Start the program
Step 2: Define the following functions:
• sum(a, b) → returns the addition of two numbers
• sub(a, b) → returns the subtraction of two numbers
• mul(a, b) → returns the multiplication of two numbers
• div(a, b) → returns the division of two numbers
• rem(a, b) → returns the remainder of two numbers
Step 3: Display the menu with choices:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Remainder
6. Exit
Step 4: Get the user’s choice
Step 5:
If choice = 1, input two numbers and call sum(a, b)
If choice = 2, input two numbers and call sub(a, b)
If choice = 3, input two numbers and call mul(a, b)
If choice = 4, input two numbers and call div(a, b)
If choice = 5, input two numbers and call rem(a, b)
If choice = 6, display “Exit from program” and stop
Step 6:
If user enters any other number, display “Invalid choice! Try again.”
Step 7: Repeat steps 3–6 until the user chooses Exit.
Step 8: Stop the program
Program:
Conditional Statements
Concept: Making decisions using conditions
Examples:
• Check vowel or consonant
• Largest of three numbers
• Check even or odd
• Grading system using if–elif–else
Concepts Covered:
if, elif, else, comparison operators (>, <, ==)
Looping Statements
Concept: Repeating actions
Examples:
• Print numbers 1 to 10 using for loop
• Factorial of a number using while loop
• Prime number check
• Multiplication table
Concepts Covered:
for, while, break, continue, range()
Functions
Concept: Reusable code blocks
Examples:
• Define a function to add two numbers
• Function to check even or odd
• Function to calculate factorial
• Function with return value
Concepts Covered:
def, parameters, return statements
File Handling
Concept: Reading and writing files
Examples:
• Write content to a file
• Read content from file
• Read first 10 bytes
• Read first 2 lines
• Read a character
Concepts Covered:
open(), read(), readline(), write(), file modes ('r', 'w', 'a')
Exception Handling
Concept: Handling errors safely in programs
Examples:
• Handle numeric and name errors
• Handle ZeroDivisionError
• Try–except–else–finally structure
Concepts Covered:
try, except, else, finally