0% found this document useful (0 votes)
30 views12 pages

Python PB 2 System

The document contains 15 programming problems related to Python. It includes problems on lists, dictionaries, tuples, functions, strings, numbers, and patterns. Some key problems are: creating and manipulating lists, dictionaries, and tuples using various methods; defining functions to perform mathematical operations; checking if a string is a palindrome; calculating factorials using functions; printing half and inverted half pyramids of stars and numbers; and generating the Pascal's triangle pattern. The problems cover common data structures and algorithms in Python.

Uploaded by

Nikhil Sharma
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)
30 views12 pages

Python PB 2 System

The document contains 15 programming problems related to Python. It includes problems on lists, dictionaries, tuples, functions, strings, numbers, and patterns. Some key problems are: creating and manipulating lists, dictionaries, and tuples using various methods; defining functions to perform mathematical operations; checking if a string is a palindrome; calculating factorials using functions; printing half and inverted half pyramids of stars and numbers; and generating the Pascal's triangle pattern. The problems cover common data structures and algorithms in Python.

Uploaded by

Nikhil Sharma
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/ 12

Python Problem Sheet - 2 SYSTEM

1. Create a list and perform the following methods.


1) insert() 2) remove() 3) append() 4) len() 5) pop() 6)
clear()
➢ Program :
lst = [10, 20, 30, 40, 50]
print("Create List is:",lst)
lst.insert(2, 25)
print("After insert(2, 25):", lst)
lst.remove(30)
print("After remove(30):", lst)
lst.append(60)
print("After append(60):", lst)
length = len(lst)
print("Length of the list:", length)
pop = lst.pop()
print("Popped element:", pop)
print("After pop():", lst)
lst.clear()
print("After clear():", lst)

➢ Output :
Create List is: [10, 20, 30, 40, 50]
After insert(2, 25): [10, 20, 25, 30, 40, 50]
After remove(30): [10, 20, 25, 40, 50]
After append(60): [10, 20, 25, 40, 50, 60]
Length of the list: 6
Popped element: 60
After pop(): [10, 20, 25, 40, 50]
After clear(): []

2. Create a dictionary and apply the following methods


1) Print the dictionary items
2) access items
3) use get()
4) change values
5) use len()
➢ Program :
dic = {
"apple": 2,
"banana": 3,
"orange": 1,
"grape": 4
}
print("1) Dictionary items:")
print(dic)
print("\n2) Accessing items:")
print("apples:", dic["apple"])
print("grapes:", dic["grape"])
print("\n3) Using get():")
print("oranges:", dic.get("orange", 0))
print("watermelons:", dic.get("watermelon", 0))

1
SYSTEM
Python Problem Sheet - 2 SYSTEM

print("\n4) Changing values:")


dic["banana"] = 5
print("Updated dic:", dic)
print("\n5) Length of the dic:")
print("items in the dic:", len(dic))

➢ Output :
1) Dictionary items:
{'apple': 2, 'banana': 3, 'orange': 1, 'grape': 4}

2) Accessing items:
apples: 2
grapes: 4

3) Using get():
oranges: 1
watermelons: 0

4) Changing values:
Updated dic: {'apple': 2, 'banana': 5, 'orange': 1, 'grape': 4}

5) Length of the dic:


items in the dic: 4

3. Create a tuple and perform the following methods


1) Add items
2) len()
3) check for item in tuple
4) Access items
➢ Program :
tup = (1, 2, 3, 4, 5)
print("Create Tupel is:",tup)
new_tup = tup + (6, 7)
print("1) Tuple after adding items:", new_tup)
print("2) Length of the tuple:", len(tup))
check = 3
if check in tup:
print(f"3) {check} is present in the tuple.")
else:
print(f"3) {check} is not present in the tuple.")
print("4) Accessing items:")
print("First item:", tup[0])
print("Last item:", tup[-1])

➢ Output :
Create Tupel is: (1, 2, 3, 4, 5)
1) Tuple after adding items: (1, 2, 3, 4, 5, 6, 7)
2) Length of the tuple: 5
3) 3 is present in the tuple.
4) Accessing items:
First item: 1
Last item: 5

2
SYSTEM
Python Problem Sheet - 2 SYSTEM

4. Write a python program to add two numbers.


➢ Program :
n1 = int(input("Enter First Number : "))
n2 = int(input("Enter Second Number : "))
print("Addition is : ",n1+n2)
➢ Output :
Enter First Number : 20
Enter Second Number : 10
Addition is : 30

5. Write a python program to print a number is positive/negative using if-


else.
➢ Program :
n = int(input("Enter Number : "))
if n<0:
print(n,"is Nagative")
else:
print(n,"is Positive")
➢ Output :
>>> Enter Number : 183
183 is Positive
>>> Enter Number : -182
-182 is Nagative

6. Write a python program to find largest number among three numbers.


➢ Program :
n1 = int(input("Enter First Number : "))
n2 = int(input("Enter Second Number : "))
n3 = int(input("Enter Third Number : "))
print("Largest Number is : ",max(n1,n2,n3))

➢ Output :
Enter First Number : 20
Enter Second Number : 30
Enter Third Number : 10
Largest Number is : 30

7. Write a python Program to read a number and display corresponding day


using if_elif_else
➢ Program :
n = int(input("Enter Number For Day : "))
if n==1:
day = "Monday"
elif n==2:
day = "Tuesday"
elif n==3:
day = "Wednesday"
elif n==4:
day = "Thursday"

3
SYSTEM
Python Problem Sheet - 2 SYSTEM

elif n==5:
day = "Friday"
elif n==6:
day = "Saturday"
elif n==7:
day = "Sunday"
else:
day = "Invalid Day Number! it's only less then 7"
print(f"Your Day Number : {n} and Day Name : {day}")

➢ Output :
Enter Number For Day : 7
Your Day Number : 7 and Day Name : Sunday

8. Write a program to create a menu with thefollowing options:


1. TO PERFORM ADDITITON
2. TO PERFORM SUBTRACTION
3. TO PERFORM MULTIPICATION
4. TO PERFORM DIVISION Accepts users input and perform the operation
accordingly. Use functions with arguments.
➢ Program :
def add(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return a/b
n1 = int(input("Enter First : "))
n2 = int(input("Enter Second : "))
print("Addtion is :",add(n1,n2))
print("Substraction is :",sub(n1,n2))
print("Multiplication is :",mul(n1,n2))
print("Divison is :",div(n1,n2))
➢ Output :
Enter First : 20
Enter Second : 10
Addtion is : 30
Substraction is : 10
Multiplication is : 200
Divison is : 2.0

9. Write a python program to check whether the given string is palindrome


or not.
➢ Program :
a = input("Enter String : ")
if a == a[::-1]:
print(a,"String is palindrome")
else:
print(a,"String is Not palindrome")

4
SYSTEM
Python Problem Sheet - 2 SYSTEM

➢ Output :
>>> Enter String : Khuhk
Khuhk String is Not palindrome
>>> Enter String : KhuhK
KhuhK String is palindrome

10.Write a python program to find factorial of a given number using functions


➢ Program :
def fact(n):
re = 1
for i in range(1,n+1):
re*=i
return re
n = int(input("Enter Integer :"))
print(f"Factorial of {n} is :",fact(n))
➢ Output :
Enter Integer :5
Factorial of 5 is : 120

11.Write a Python function that takes two lists and returns True if they are
equal otherwise false.
➢ Program :
a = [1,2,3]
b = [1,2,3]
print(a == b)
➢ Output :
True

12.Write a python program to print the Fibonacci series up to a given


number.
➢ Program :
n = int(input("Enter Number : "))
f, s = 0, 1
print(f)
print(s)
for i in range(2, n):
t=f+s
print(t)
f, s = s, t
➢ Output :
Enter Number : 5
0
1
1
2
3

13.Write a program to print half pyramid using *.


➢ Program :
r = int(input("Enter Rows : "))
for i in range(1, r + 1):

5
SYSTEM
Python Problem Sheet - 2 SYSTEM

print("*" * i)
➢ Output :
*
**
***
****
*****

14.Write a program to print inverted half pyramid using Numbers.


➢ Program :
r = int(input("Enter Rows : "))
for i in range(r, 0, -1):
for j in range(1, i + 1):
print(j, end=" ")
print()

➢ Output :
Enter Rows : 5
12345
1234
123
12
1

15.Write a program of Pascal’s triangle.


➢ Program :
r = int(input("Enter rows: "))
triangle = []
for i in range(r):
row = []
for j in range(i + 1):
if j == 0 or j == i:
row.append(1)
else:
prev_row = triangle[i - 1]
value = prev_row[j - 1] + prev_row[j]
row.append(value)
triangle.append(row)

# Print the triangle


for row in triangle:
print(" " * (r - len(row)), end="")
for num in row:
print(num, end=" ")
print()

➢ Output :
Enter rows: 5
1
11
121
1331

6
SYSTEM
Python Problem Sheet - 2 SYSTEM

14641

16.Write a program of Floyd’s Triangle


➢ Program :
n = int(input("Enter Number : "))
number = 1
for i in range(1, n + 1):
for j in range(1, i + 1):
print(number, end=" ")
number += 1
print()

➢ Output :
Enter Number : 5
1
23
456
7 8 9 10
11 12 13 14 15

17.Write a python program to convert Decimal to Binary, Octal and


Hexadecimal.
➢ Program :
n = int(input("Enter Decimal Value : "))
print("Decimal Value is : ",n)
print("Binary Value is : ",bin(n).replace("0b", ""))
print("Octal Value is : ",oct(n).replace("0o", ""))
print("Hexadecimal Value is : ",hex(n).replace("0x", "").upper())

➢ Output :
Enter Decimal Value : 10
Decimal Value is : 10
Binary Value is : 1010
Octal Value is : 12
Hexadecimal Value is : A

18. Write a python program to shuffle Deck of cards.


➢ Program :
import random

# Function to create and return a new deck of cards


def create_deck():
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'Jack', 'Queen', 'King', 'Ace']
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
deck = [(rank, suit) for rank in ranks for suit in suits]
return deck

# Function to shuffle the deck of cards


def shuffle_deck(deck):
random.shuffle(deck)

7
SYSTEM
Python Problem Sheet - 2 SYSTEM

# Function to print the shuffled deck of cards


def print_deck(deck):
for card in deck:
print(f"{card[0]} of {card[1]}")

# Main program
if __name__ == "__main__":
# Create a new deck of cards
deck = create_deck()

print("Deck of cards before shuffling:")


print_deck(deck)

# Shuffle the deck


shuffle_deck(deck)

print("\nDeck of cards after shuffling:")


print_deck(deck)

➢ Output :
Try to Run And Get Output

19.Write a python program to multiply Two Matrices.


➢ Program :
def mul(matrix1, matrix2):
r1 = len(matrix1)
c1 = len(matrix1[0])
r2 = len(matrix2)
c2 = len(matrix2[0])

if c1 != r2:
raise ValueError("Number of columns in the first matrix must be
equal to the number of rows in the second matrix.")

result_matrix = [[0 for _ in range(c2)] for _ in range(r1)]

for i in range(r1):
for j in range(c2):
for k in range(r2):
result_matrix[i][j] += matrix1[i][k] * matrix2[k][j]

return result_matrix

# Input from the user


try:
r1 = int(input("Enter the number of rows for the first matrix: "))
c1 = int(input("Enter the number of columns for the first matrix: "))

matrix1 = []
for i in range(r1):
row = []
for j in range(c1):

8
SYSTEM
Python Problem Sheet - 2 SYSTEM

element = float(input(f"Enter element at position ({i + 1}, {j +


1}): "))
row.append(element)
matrix1.append(row)

r2 = int(input("Enter the number of rows for the second matrix: "))


c2 = int(input("Enter the number of columns for the second matrix: "))
matrix2 = []
for i in range(r2):
row = []
for j in range(c2):
element = float(input(f"Enter element at position ({i + 1}, {j +
1}): "))
row.append(element)
matrix2.append(row)
result = mul(matrix1, matrix2)
print("\nResult of matrix multiplication:")
for row in result:
print(row)
except ValueError:
print("Invalid input! Please enter valid numbers for matrix elements.")

➢ Output :
Enter the number of rows for the first matrix: 3
Enter the number of columns for the first matrix: 3
Enter element at position (1, 1): 10
Enter element at position (1, 2): 20
Enter element at position (1, 3): 15
Enter element at position (2, 1): 20
Enter element at position (2, 2): 30
Enter element at position (2, 3): 20
Enter element at position (3, 1): 50
Enter element at position (3, 2): 10
Enter element at position (3, 3): 20
Enter the number of rows for the second matrix: 3
Enter the number of columns for the second matrix: 3
Enter element at position (1, 1): 20
Enter element at position (1, 2): 4
Enter element at position (1, 3): 10
Enter element at position (2, 1): 20
Enter element at position (2, 2): 30
Enter element at position (2, 3): 20
Enter element at position (3, 1): 50
Enter element at position (3, 2): 60
Enter element at position (3, 3): 10
Result of matrix multiplication:
[1350.0, 1540.0, 650.0]
[2000.0, 2180.0, 1000.0]
[2200.0, 1700.0, 900.0]

20.Write a python program to find Armstrong number in an interval.


➢ Program :

9
SYSTEM
Python Problem Sheet - 2 SYSTEM

def is_armstrong_number(num):
num_str = str(num)
num_digits = len(num_str)
sum_of_digits = sum(int(digit) ** num_digits for digit in num_str)
return num == sum_of_digits
lower = int(input("Enter the lower limit of the interval: "))
upper = int(input("Enter the upper limit of the interval: "))
if lower > upper:
print("Invalid interval! The lower limit should be less than or equal to
the upper limit.")
else:
print("Armstrong numbers in the interval:")
for num in range(lower, upper + 1):
if is_armstrong_number(num):
print(num)

➢ Output :
Enter the lower limit of the interval: 100
Enter the upper limit of the interval: 1000
Armstrong numbers in the interval:
153
370
371
407

21.Write a python program to find HCF Or GCD.


➢ Program :
a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
tmpa = a
tmpb = b
while b:
a, b = b, a % b
print(f"The HCF/GCD of {tmpa} and {tmpb} is: {a}")

➢ Output :
Enter the first number: 10
Enter the second number: 5
The HCF/GCD of 10 and 5 is: 5

22.Write a program to find LCM.


➢ Program :
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
a = num1
b = num2
while b:
a, b = b, a % b
hcf = a
lcm = (num1 * num2) // hcf
print(f"The LCM of {num1} and {num2} is: {lcm}")

10
SYSTEM
Python Problem Sheet - 2 SYSTEM

➢ Output :
Enter the first number: 10
Enter the second number: 5
The LCM of 10 and 5 is: 10

23.Write a python program to find the factors of a number.


➢ Program :
n = int(input("Enter a number to find its factors: "))
if n < 1:
print("Please enter a positive integer.")
else:
factors = []
for i in range(1, n + 1):
if n % i == 0:
factors.append(i)
print(f"The factors of {n} are: {factors}")

➢ Output :
Enter a number to find its factors: 24
The factors of 24 are: [1, 2, 3, 4, 6, 8, 12, 24]

24.Write a python program to make a simple calculator.


➢ Program :
def main():
print(" !! Simple Calculator !!")
while True:
print("\nOperations:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")
print("5. Exit")
choice = int(input("Enter Operation Number (1/2/3/4/5): "))
if choice == 1:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
print("Result:", (num1+num2))
elif choice == 2:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
print("Result:", (num1-num2))
elif choice == 3:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
print("Result:", (num1*num2))
elif choice == 4:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
if y == 0:
print("Cannot divide by zero.")
else:
print("Result:", (num1/num2))

11
SYSTEM
Python Problem Sheet - 2 SYSTEM

elif choice == 5:
print("You are Exited !")
break
else:
print("Invalid Choice! Please try Again")
main()

➢ Output :
!! Simple Calculator !!
Operations:
1. Addition
2. Subtraction
3. Multiplication
4. Division
5. Exit
Enter Operation Number (1/2/3/4/5): 1
Enter the first number: 20
Enter the second number: 30
Result: 50.0

25.Write a python program to convert decimal to binary using .


➢ Program :
def binary(n):
if n == 0:
return "0"
elif n == 1:
return "1"
else:
return binary(n // 2) + str(n % 2)
n = int(input("Enter a decimal number: "))
if n < 0:
print("Please enter a non-negative integer.")
else:
binary_num = binary(n)
print(f"The binary representation of {n} is: {binary_num}")

➢ Output :
Enter a decimal number: 10
The binary representation of 10 is: 1010

12
SYSTEM

You might also like