0% found this document useful (0 votes)
6 views32 pages

67 Py

The document contains a series of Python programming assignments for a student named Chauhan Krish, enrolled in an MSC CS-IV course. Each assignment includes a specific task, such as adding two numbers, finding the greatest number among three, or checking for prime numbers, along with example code and output. The document serves as a practical guide for learning Python programming through various exercises.
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)
6 views32 pages

67 Py

The document contains a series of Python programming assignments for a student named Chauhan Krish, enrolled in an MSC CS-IV course. Each assignment includes a specific task, such as adding two numbers, finding the greatest number among three, or checking for prime numbers, along with example code and output. The document serves as a practical guide for learning Python programming through various exercises.
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

NAME : Chauhan krish

COURSE : MSC CS-IV


SUBJECT : PROGRAMMING WITH PYTHON
ROLL NO.: 67
BATCH : 2
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ASSIGNMENT1~~~~~~~~~~~~~~~~~~~~~~~
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

______________________________________________________________________________
1))Write a python program to add two numbers.
______________________________________________________________________________ a
= 100
b = 50
print("the sum of" ,a+b) a = int(input("Enter
value of a:")) b = int(input("Enter value of
b:")) print("the sum is %d and %d =
%d"%(a,b,a+b))

-----------------------------------
OUTPUT
----------------------------------- the sum
of 150
Enter value of a:100 Enter
value of b:50 the sum is 100
and 50 = 150
______________________________________________________________________________
2))Write a python program to find quotient and remainder.
_____________________________________________________________________________
_ a = float(input("Enter value of a:")) b = float(input("Enter value of b:")) print("%.2f / %.2f = %.2f"

%(a,b,a/b)) print("%.2f mod %.2f = %.2f" %(a,b,a%b))

----------------------
OUTPUT
---------------------- Enter
value of a:12 Enter
value of b:5
12.00 / 5.00 = 2.40
12.00 mod 5.00 = 2.00
___________________________________________________________________________________
__
3) Write a python program to find type of objects in your system.
___________________________________________________________________________________
__

objects_to_check = [1, "Hello", [1, 2, 3], {’a’: 1, ’b’: 2}, (1, 2, 3), True, None]

for obj in objects_to_check: print(f"The type of {obj} is:

{type(obj).__name__}")

------------------------------------------
OUTPUT
------------------------------------------
The type of 1 is: int
The type of Hello is: str
The type of [1, 2, 3] is: list
The type of {’a’: 1, ’b’: 2} is: dict
The type of (1, 2, 3) is: tuple
The type of True is: bool The
type of None is: NoneType
______________________________________________________________________________
4) Write a python program to read two numbers and display the greatest number
_____________________________________________________________________________
_ a=(input("enter value of a: ")) b=(input("enter value of b:

")) if a<b: print("b is greater") elif

b<a: print("a is greater")

else: print("both are equal")


----------------------
OUTPUT
----------------------
enter value of a: 06
enter value of b: 18 b is
greater
____________________________________________________________________________ 5)
Write a python program to check whether number is even or odd.
____________________________________________________________________________

num=int(input("enter a number:")) if num%2==0: print("it is an even number")


else: print("it is an odd number")
----------------------
OUTPUT
----------------------
enter a number:20 it

is an even number

enter a number:17 it

is an odd number

_____________________________________________________________________________
6) Write a python program to check whether a character is vowel or consonant
___________________________________________________________________________
__ c=str(input("enter a character:")) if
c==’a’ or c==’e’or c==’i’ or c==’o’ or c==’u’:
print("it is a vowel")
else: print("it is a
consonant")
----------------------
OUTPUT
----------------------
enter a character:n

it is a consonant

enter a character:i

it is a vowel

___________________________________________________________________________________
_

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


___________________________________________________________________________________
_

a=int(input("enter a:"))
b=int(input("enter b:"))
c=int(input("enter c:"))
if a>b and a>c: print("a
is largest")
elif b>a and b>c:
print("b is largest") else:
print("c is
largest")
------------------
OUTPUT
------------------
enter a:1 enter
b:2 enter c:3 c is
largest
___________________________________________________________________________________
_

8) Write a python program to find all roots of a quadratic equation


___________________________________________________________________________________
_

# Get input from user a = float(input("Enter the coefficient


of x^2: ")) b =
float(input("Enter the coefficient of x: ")) c = float(input("Enter
the constant term: "))
# Calculate discriminant discriminant
= b**2 - 4*a*c

# Check if roots are real or complex if


discriminant > 0: # Calculate real roots
root1 = (-b + discriminant**0.5) / (2*a)
root2 = (-b - discriminant**0.5) / (2*a)
print("The roots are real and distinct.")
print("Root 1:", root1) print("Root 2:",
root2) elif discriminant == 0:
# Calculate real and equal roots root
= -b / (2*a) print("The roots are real
and equal.") print("Root:",
root)
else:
# Calculate complex roots real_part = -b / (2*a)
imaginary_part = (-discriminant)**0.5 / (2*a)
print("The roots are complex.") print("Root 1:",
real_part, "+", imaginary_part, "i") print("Root 2:",
real_part, "-", imaginary_part, "i")

---------------------------------
OUTPUT
---------------------------------
Enter the coefficient of x^2: 2
Enter the coefficient of x: 8
Enter the constant term: 3
The roots are real and distinct.
Root 1: -0.41886116991581024
Root 2: -3.58113883008419
___________________________________________________________________________________
_

9) Write a python program to calculate sum of natural numbers.


___________________________________________________________________________________
_ num=int(input("enter a

number:")) a=0 for i in

range(1,num+1): a+=i;

print(a); -----------------
OUTPUT
------------------
enter a number:10
55
___________________________________________________________________________________
10) Write a python program to check leap year
__________________________________________________________________________________ _

year=int(input("enter a year :")) if(year%4==0 and year%100!=0) or (year%400==0):

print("it is a leap year")


else: print("it is not a leap year")
-------------------
OUTPUT
-------------------
enter a year :2024 it
is a leap year
___________________________________________________________________________________
11) Write a python program to find factorial.
___________________________________________________________________________________

num = int(input("Enter a number: ")) fact = 1 for i in range(1, num + 1):

fact *= i

print("Factorial of %d is %d" % (num, fact))


------------------------
OUTPUT
------------------------
Enter a number: 5 Factorial
of 5 is 120
__________________________________________________________________________________
12) Write a python program to generate multiplication table.
__________________________________________________________________________________
result=1
a=int(input("enter a number :")) for i
in range(1, 11):
result = a * i
print(f"{a} x {i} = {result}")
--------------------
OUTPUT
--------------------
enter a number :5
5x1=5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50
___________________________________________________________________________________
_ ______

13) Write a python program to display fibonacci series. (eg. 0, 1, 1, 2, 3, 5, 8, 13, …)


___________________________________________________________________________________
_ ______
def fibonacci(n): first_term, second_term =
0, 1 count = 0 if n <= 0: print("Please enter
a positive integer.")
elif n == 1: print("Fibonacci
series:") print(first_term) else:
print("Fibonacci series:")
while count < n: print(first_term, end=",
") next_term = first_term +
second_term first_term =
second_term second_term =
next_term
count += 1 num = int(input("Enter the number
of terms: "))

fibonacci(num)
---------------------------------
OUTPUT
---------------------------------
Enter the number of terms: 10 Fibonacci series:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34,
______________________________________________________________________________
14) Write a python program to find gcd.
______________________________________________________________________________ def
gcd(a,b):
while b != 0:
a,b = b, a % b;
return a num1 = int(input("Enter first number : "))

num2 = int(input("Enter second number : ")) result

= gcd(num1, num2) print("The GCD

of",num1,"and",num2,"is:" ,result)

-----------------------------------
OUTPUT
-----------------------------------
Enter first number : 3
Enter second number : 2
The GCD of 3 and 2 is: 1
______________________________________________________________________________
_ 15) Write a python program to find lcm.
______________________________________________________________________________
_

def gcd(a,b):
while b != 0: a,b = b, a % b; return a num1 =

int(input("Enter first number : ")) num2 =

int(input("Enter second number : ")) result =


gcd(num1, num2) print("The GCD

of",num1,"and",num2,"is:" ,result) def lcm(a,b): return

(a *

b)//gcd(a, b) num1 = int(input("Enter first

number : ")) num2 = int(input("Enter second

number : ")) result = lcm(num1, num2) print("The

LCM of",num1,"and",num2,"is : ",result)


-----------------------------------
OUTPUT
-----------------------------------
Enter first number : 2
Enter second number : 3
The GCD of 2 and 3 is: 1
Enter first number : 2
Enter second number : 3
The LCM of 2 and 3 is : 6
______________________________________________________________________________
_ 16) Write a python program to reverse a number.
______________________________________________________________________________
_ num = int(input("Enter a number : "))
rev_num = 0 while num > 0:
remainder = num %
10 rev_num =
(rev_num * 10) +
remainder num =
num // 10

print("The reversed number is : " , rev_num)

-----------------------------------
OUTPUT
-----------------------------------
Enter a number : 18
The reversed number is : 81
______________________________________________________________________________ _
17) Write a python program to calculate power of a number.
______________________________________________________________________________
_ base = int(input("Enter the base : ")) exponent = int(input("Enter the exponent : ")) result

= 1 for _ in range(exponent): result *= base print(f"{base} raised to the power of {exponent}

is : {result}")

-----------------------------------
OUTPUT
-----------------------------------
Enter the base : 2
Enter the exponent : 2
2 raised to the power of 2 is : 4
______________________________________________________________________________
_ 18) Write a python program to find binary value of a character.
______________________________________________________________________________
_ x = input("Enter a character: ") binary

= bin(ord(x)) print("Binary value of", x,

"is", binary)

-----------------------------------
OUTPUT
----------------------------------- Enter
a character: n
Binary value of n is 0b1101110
___________________________________________________________________________________
_ ____

19) Write a python program to display two separate strings in single line continuously.
___________________________________________________________________________________
_ ____ str1 = input("Enter the first
string : ") str2 = input("Enter the
second string : ") while True:
print(str1,end="
")
print(str2, end=" ") break

--------------------------------------
OUTPUT
-------------------------------------- Enter the
first string : NIRALI
Enter the second string : CHAUDHARY NIRALI
CHAUDHARY
______________________________________________________________________________
_

20) Write a python program to check whether a number is palindrome or not.


______________________________________________________________________________
_ num = int(input("Enter number : ")) def palindrome(num):
or_num = num rev_num
= 0 while num > 0: digit = num%10
rev_num
= rev_num * 10 + digit
num = num // 10 return
or_num == rev_num if
palindrome(num):

print("number is palindrome")
else: print("number is not palindrome")

-----------------------------------
OUTPUT
-----------------------------------
Enter number : 181 number is
palindrome

Enter number : 123 number is


not palindrome
______________________________________________________________________________
_ 21) Write a python program to check whether a number is prime or not.
______________________________________________________________________________

_ num=int(input("enter a number :")) prime=False

if num==1: print(num," is not prime") elif num>1:

for i in range(2,num): if
num%i==0:
prime=True break if prime:
print(num,"is not prime") else:
print(num,"is prime")

-----------------------------------
OUTPUT
---------------------------------enter a
number :11 11 is prime
enter a number :20
20 is not prime
______________________________________________________________________________
_ 22) Write a python program to display prime numbers between two intervals.
_______________________________________________________________________________ def
is_prime(num): if num<2:
return False
for i in range(2,int(num ** 0.5)+1): if
num%2==0: return
False return
True
def display(start,end): print(f"prime numbers between
{start} and {end} :") for num
in range(start,end+1):
if is_prime(num):
print(num,end=’ ’)

start = int(input("Enter the start of the interval: "))

end = int(input("Enter the end of the interval: "))

display(start,end)

-----------------------------------
OUTPUT
-----------------------------------
Enter the start of the interval: 1
Enter the end of the interval: 20 prime numbers
between 1 and 20 :
2 3 5 7 9 11 13 15 17 19
______________________________________________________________________________
_
23) Write a python program to check armstrong number. (eg. 13 + 33 + 53 = 153)
______________________________________________________________________________
_ num=int(input("enter a number :")) sum=0
temp=num while temp>0:
digit=temp%10 sum+=digit

** 3

temp=temp//10

if num==sum: print(num," is an
armstrong number")
else: print(num," is not an armstrong number")

-----------------------------------
OUTPUT
----------------------------------
enter a number :153 153 is an armstrong
number

enter a number :152


152 is not an armstrong number
______________________________________________________________________________
_ 24) Write a python program to display armstrong number between two intervals.
_______________________________________________________________________________
start=int(input("enter start :")) end=int(input("enter end :"))

for num in range(start,end+1):


sum=0 temp=num while
temp>0:
digit=temp%10
sum+=digit ** 3
temp=temp//10
if num==sum:
print(num)

-----------------------------------
OUTPUT
----------------------------------- enter
start :100
enter end :200 153
______________________________________________________________________________
_ 25) Write a python program to display factors of a number.
______________________________________________________________________________
_ def fact(num): factors=[] for i in range(1,num+1): if num % i==0: [Link](i) return
factors

a=int(input("enter a number :")) result=fact(a) print(f"the


factors of {a} are : {result}")
----------------------------------------
OUTPUT
----------------------------------------
enter a number :10
the factors of 10 are : [1, 2, 5, 10]
______________________________________________________________________________
_
26) Write a python programs to create pyramid and pattern
______________________________________________________________________________
_
# Generating Pyramid rows = int(input("Enter the
number of rows: "))

for i in range(1, rows+1): print(" "*(rows-i) +


"*"*(2*i-1))

# Generating Pattern num = int(input("enter


number of rows ")) for i in range(1,num +
1):
print("*"*i) ----------------------------------
OUTPUT
-----------------------------------
Enter the number of rows: 6
*
***
*****
*******
*********
***********
enter number of rows 6
*
**
***
****
*****
******
___________________________________________________________________________________
_ _________

27) Write a python program to make a simple calculator to add, subtract, multiply or divide
___________________________________________________________________________________
_ _________

num1 = float(input("Enter first number : ")) num2


= float(input("Enter second number : ")) operator
= input("Enter operator (+, -, *, /) : ") if operator
== ’+’:

Addition = num1 + num2


print("Addition : ", Addition)
elif operator == ’-’:
Subtraction = num1 - num2 print("Subtraction
: ", Subtraction) elif
operator == ’*’:
Multiplication = num1 * num2 print("Multiplication
: ", Multiplication)
elif operator == ’/’: if
num2 != 0:
Divison = num1 / num2 print("Divison
: ", Divison) else:
print("enter valid number")
else: print("enter valid choice.!!")

-----------------------------------
OUTPUT
----------------------------------- Enter
first number : 1
Enter second number : 2
Enter operator (+, -, *, /) : +
Addition : 3.0
Enter first number : 2
Enter second number : 2
Enter operator (+, -, *, /) : Subtraction
: 0.0

Enter first number : 2


Enter second number : 10
Enter operator (+, -, *, /) : *
Multiplication : 20.0

Enter first number : 1


Enter second number : 2
Enter operator (+, -, *, /) : /
Divison : 0.5
Enter first number : 1
Enter second number : 0
Enter operator (+, -, *, /) : / enter valid
number

Enter first number : 1


Enter second number : 2
Enter operator (+, -, *, /) : ] enter valid
choice.!!
_________________________
_________________________
_________________________
___
_
28) Write a python program to display Simple Number Triangle Pattern
______________________________________________________________________________
_ rows = int(input("Enter number of rows to be printed : "))

for i in range(1,rows+1): print("


" * (rows-i),end="") for
j in range(1,i+1):
print(j,end=" ")
print()
-----------------------------------------

OUTPUT

-----------------------------------------

Enter number of rows to be printed : 16

1 16

12 16

123 16

1234 17

1
1234

5_____________________________________________________________________________

__ 15

29) Write a python program to display inverted pyramid of numbers


______________________________________________________________________________
_ rows = int(input("Enter number of rows to be printed : "))

for i in range(rows+1,0,-1): print("


"*(rows-i),end="") for
j in range(1,i,1):
print(j,end=" ")
print()

----------------------------------------
OUTPUT
----------------------------------------
Enter number of rows to be printed : 6
123456
12345
1234
123
12
1
______________________________________________________________________________
_ 30) Write a python program to display inverted pyramid of descending numbers
______________________________________________________________________________
_ rows = int(input("Enter number of rows to be printed : ")) for
i in range(rows,0,-1): print("
"*(rows-i),end="") for
j in range(i,0,-1):
print(j,end=" ")
print()

-----------------------------------------
OUTPUT
-----------------------------------------
Enter number of rows to be printed : 6
654321
54321
4321
321
21
1
______________________________________________________________________________
_ 31) Write a python program to display inverted pyramid of the same digit
______________________________________________________________________________
_ rows = int(input("Enter the number of rows to be printed :

")) digit = int(input("Enter the digit to be printed : "))

for i in range(rows, 0, -1):


# Print the same digit for each row print(str(digit)
* i)

------------------------------------------------
OUTPUT
------------------------------------------------
Enter the number of rows to be printed : 8
Enter the digit to be printed : 6
66666666
6666666
666666
66666
6666
666
66
6
______________________________________________________________________________ _
32) Write a python program to display reverse pyramid of numbers
______________________________________________________________________________
_ def rev_pyr(n):
for i in range(n, 0, -1): print("
" * (n - i), end="") for
j in range(i, 0, -1):
print(j, end=" ")
print()

-----------------------------------
OUTPUT
-----------------------------------
rows = 5 rev_pyr(rows)
54321
4321
321
21
1
______________________________________________________________________________
_ 33) Write a python program to display inverted half pyramid number pattern
______________________________________________________________________________
_ rows=int(input("enter number of rows:")) for

i in range(rows,0,-1): for j in range(1,i+1):

print(i,end=" ")
print()

-----------------------------------
OUTPUT
----------------------------------- enter number
of rows:10
10 10 10 10 10 10 10 10 10 10
999999999
88888888
7777777
666666
55555
4444
333
221
______________________________________________________________________________
_ 34) Write a python program to display pyramid of natural numbers less than 10
______________________________________________________________________________
_ n=10 for i in range(1,n):
for j in
range(n-i):
print("",end=" ") for k
in range(1,i+1):
print(k,end=" ")
print()
-----------------------------------
OUTPUT
-----------------------------------
1
12
123
1234
12345
123456
1234567
12345678
123456789
______________________________________________________________________________
_ 35) Write a python program to display reverse pattern of digits from 10
______________________________________________________________________________
_ num = 10
for i in range(num,0,-1):
for j in range(i,0,-1):
print(j,end=" ")
print()
---------------------
OUTPUT
---------------------
10 9 8 7 6 5 4 3 2 1
987654321
87654321
7654321
654321
54321
4321
321
21
1
___________________________________________________________________________________
_

36) Write a python program to display connected inverted pyramid pattern of numbers
___________________________________________________________________________________
_ rows=int(input("enter number of rows:"))

for i in range(rows,0,-1):

for j in range(rows-i):

print(" ",end=" ")


for k in range(1,i+1): print(k,end="
")
for l in range(i-1,0,-1): print(l,end="
")
print()
-------------------------
OUTPUT
-------------------------
enter number of rows:6
12345654321
123454321
1234321
12321
121
1
______________________________________________________________________________
_ 37) Write a python program to display even number pyramid pattern
______________________________________________________________________________
_ rows = int(input("Enter rows : ")) num
= 2 for i in range(1,rows+1):
print("
"*(rows-i+1),end=" ") for
k in range(1,i+1):
print(num,end=" ")
num+=2 print()

---------------------
OUTPUT
---------------------
Enter rows : 6
2
46
8 10 12
14 16 18 20
22 24 26 28 30
32 34 36 38 40 42
______________________________________________________________________________
_ 38) Write a python program to display pyramid of horizontal tables
______________________________________________________________________________
_ rows = int(input("Enter the number of rows for the horizontal table pyramid: ")) for
i in range(1,rows+1): for j in range(1, i+1): print(f"{j} x {i} = {i * j}",end="\t") print()
------------------------------------------------------------------
OUTPUT
------------------------------------------------------------------
Enter the number of rows for the horizontal table pyramid: 6
1x1=1
1x2=22x2=4
1x3=32x3=63x3=9
1 x 4 = 4 2 x 4 = 8 3 x 4 = 12 4 x 4 = 16
1 x 5 = 5 2 x 5 = 10 3 x 5 = 15 4 x 5 = 20 5 x 5 = 25
1 x 6 = 6 2 x 6 = 12 3 x 6 = 18 4 x 6 = 24 5 x 6 = 30 6 x 6 = 36
___________________________________________________________________________
___ _ 39) Write a python program to display pyramid pattern of alternate numbers
______________________________________________________________________________
_ rows = int(input("Enter the number of rows for the alternate number pyramid: ")) num = 1 for i in

range(1,rows+1): print(" " * (rows-i),end="") for j in range(1,i+1): print(num,end="

")
num+=2 print()

---------------------------------------------------------------
OUTPUT
---------------------------------------------------------------
Enter the number of rows for the alternate number pyramid: 6 1
35
7 9 11
13 15 17 19
21 23 25 27 29
31 33 35 37 39 41
______________________________________________________________________________
_
40) Write a python program to display mirrored pyramid (right-angled triangle) pattern of numbers
______________________________________________________________________________
_ rows = int(input("Enter the number of rows for the mirrored pyramid: "))

for i in range(1,rows+1):
for j in range(1,i+1): print(j,end="
")
print() for i in

range(rows-1,0,-1):
for j in range(1,i+1):
print(j,end=" ")
print()

-------------------------------------------------------
OUTPUT
-------------------------------------------------------
Enter the number of rows for the mirrored pyramid: 6 1
12
123
1234
12345
123456
12345
1234
123
121
______________________________________________________________________________
_
41) Write a python program to display equilateral triangle with stars (asterisk symbol)
______________________________________________________________________________
_ rows = int(input("Enter number of rows to be printed : "))

for i in range(rows): print("


"*(rows-i),end="")
print("* " * (i+1))

----------------------------------------
OUTPUT
----------------------------------------
Enter number of rows to be printed : 6
*
**
***
****
*****
******
______________________________________________________________________________
_
42) Write a python program to display downward triangle pattern of stars
______________________________________________________________________________
_ rows = int(input("Enter number of rows to be printed : "))

for i in range(rows,0,-1):
print(" " * (rows-i),end=" ")
print("* " * i)

-----------------------------------------
OUTPUT
-----------------------------------------
Enter number of rows to be printed : 6
******
*****
****
***
**
*
______________________________________________________________________________
_
43) Write a python program to display pyramid pattern of stars
______________________________________________________________________________

_ rows = int(input("Enter number of rows to be printed : ")) for i in range(rows): print("


"*(rows-i),end="")
print("* " * (i+1))

----------------------------------------
OUTPUT
----------------------------------------
Enter number of rows to be printed : 6
*
**
***
****
*****
******
______________________________________________________________________________
_
44) Write a python program to display hourglass pattern program
______________________________________________________________________________
_ rows = int(input("Enter the number of rows : "))

for i in range(1,rows+1):
for k in range(1,i): print("",end="
")
for j in range(i,rows+1): print(j,end="
")
print() for i in

range(rows-1,0,-1):

for k in range(1,i): print("",end="


")
for j in range(i , rows+1): print(j,end="
")
print()

-----------------------------------
OUTPUT
-----------------------------------
Enter the number of rows : 6
123456
23456
3456
456
56
6
56
456
3456
23456
123456
______________________________________________________________________________
_
45) Write a python program to display pascal’s triangle program
______________________________________________________________________________
_ n=5 for i in
range(1,n+1):
for j in range(0,n-i+1):
print("",end="")
C = 1 for j in range(1,i+1):
print("",C,sep="",end="")

C = C*(i-j)//j print()
-----------------------------------
OUTPUT
----------------------------------- 1
11
121
1331
14641

ASSIGNMENT-2
Question 1: Reverse a String # Reverse a
string input_str = "hello world" reversed_str =
input_str[::-1] print("Reversed String:",
reversed_str) # Output: Reversed String:
dlrow olleh

Question 2: Count Vowels in a String


# Count vowels in a string input_str
= "hello world" vowels =
"aeiouAEIOU"
count = sum(1 for char in input_str if char in vowels) print("Number
of Vowels:", count)
# Output: Number of Vowels: 3
Question 3: Remove Duplicate Characters from a String # Remove
duplicate characters from a string input_str = "hello world" seen = set()
result = [] for char in input_str: if char not in seen: [Link](char)
[Link](char) without_duplicates = ''.join(result) print("String
without
Duplicates:", without_duplicates) # Output: String without
Duplicates: helo wrd

Question 4: Check if a String is a Palindrome


# Check if a string is a palindrome input_str =
"level" is_palindrome = input_str ==
input_str[::-1] print("Is
Palindrome:", is_palindrome) # Output: Is
Palindrome: True

Question 5: Count the Number of Words in a String


# Count the number of words in a string input_str = "Hello
world, how are you?" num_words = len(input_str.split())
print("Number of Words:", num_words) # Output:
Number of Words: 5

Question 6: Convert CamelCase to snake_case # Convert CamelCase to


snake_case import re input_str = "ThisIsCamelCase" snake_case_str =
[Link](r'(?<!^)(?=[A-Z])', '_', input_str).lower() print("Snake Case String:",
snake_case_str)
# Output: Snake Case String: this_is_camel_case
Question 7: Convert the First Letter of Each Word to Uppercase # Convert the
first letter of each word to uppercase input_str = "hello world" capitalized_str
= ' '.join([Link]() for word in input_str.split()) print("Capitalized
String:", capitalized_str) # Output: Capitalized String: Hello World

Question 8: Count the Frequency of a Substring within a String # Count the


frequency of a substring within a string input_str = "hello world hello" sub_string
= "hello" frequency =
input_str.count(sub_string) print("Frequency
of Substring:", frequency) # Output:
Frequency of Substring: 2

Question 9: Swap the Case of Each Character in a String # Swap the


case of each character in a string input_str = "Hello World"
swapped_str = input_str.swapcase() print("Swapped Case
String:", swapped_str)
# Output: Swapped Case String: hELLO wORLD
Question 10: Remove All Whitespace Characters from a String #
Remove all whitespace characters from a string input_str = "
hello world " without_whitespace = ''.join(input_str.split())
print("String without Whitespace:", without_whitespace)
# Output: String without Whitespace: helloworld
Question 11: Extract Even and Odd Indexed Elements from a List Using Slicing # Extract
even and odd indexed elements from a list using slicing input_list = [1, 2, 3, 4, 5, 6, 7, 8,
9] even_elements = input_list[::2] # Extract even indexed elements
odd_elements = input_list[1::2] # Extract odd indexed elements print("Even
Indexed Elements:", even_elements) print("Odd Indexed Elements:",
odd_elements) # Output:
# Even Indexed Elements: [1, 3, 5, 7, 9]
# Odd Indexed Elements: [2, 4, 6, 8]

Question 12: Reverse a Given List Using Slicing


# Reverse a given list using slicing
input_list = [1, 2, 3, 4, 5]
reversed_list = input_list[::-1]
print("Reversed List:", reversed_list)
# Output: Reversed List: [5, 4, 3, 2, 1]
Question 13: Extract a Sublist from a Given List Using Slicing
# Extract a sublist from a given list using slicing input_list
= [1, 2, 3, 4, 5] sublist = input_list[2:5] # Extract elements from index 2 to 4
(exclusive of index 5) print("Sublist:", sublist)
# Output: Sublist: [3, 4, 5]

Question 14: Extract Alternate Elements from a Given List Using Slicing # Extract alternate
elements from a given list using slicing input_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]
alternate_elements = input_list[::2] # Extract elements at even indices
print("Alternate Elements:", alternate_elements) # Output: Alternate
Elements: [1, 3, 5, 7, 9]

Question 15: Replace a Sublist Within a List with Another Sublist Using Slicing # Replace a
sublist within a list with another sublist using slicing input_list = [1, 2, 3, 4, 5, 6]
replacement_list = [7, 8, 9] start_index = 2

end_index = 5 input_list[start_index:end_index] =
replacement_list print("Modified List:", input_list)
# Output: Modified List: [1, 2, 7, 8, 9, 6]

Question 16: Compute the Factorial of a Given Number Recursively # Compute the
factorial of a given number recursively def factorial(n): if n == 0 or n == 1:
return 1 else: return n * factorial(n
- 1)
# Example usage number
= 5 result = factorial(number)
print(f"Factorial of {number}: {result}")
# Output: Factorial of 5: 120

Question 17: Generate Multiplication Table of a Given Number # Generate


multiplication table of a given number def multiplication_table(n): for i in
range(1, 11): print(f"{n} x {i} = {n * i}")

# Example usage number


=7
print(f"Multiplication Table of {number}:") multiplication_table(number)
# Output:
# Multiplication Table of 7:
#7x1=7
# 7 x 2 = 14
# 7 x 3 = 21
# 7 x 4 = 28
# 7 x 5 = 35
# 7 x 6 = 42
# 7 x 7 = 49
# 7 x 8 = 56
# 7 x 9 = 63
# 7 x 10 = 70
Question 18: Check if a Given Number is Prime
# Check if a given number is prime def
is_prime(n): if n <= 1: return False for i in
range(2, int(n**0.5) + 1):
if n % i == 0: return False
return True #
Example usage number
= 11 if is_prime(number):
print(f"{number} is a prime number.") else:
print(f"{number} is not a prime number.") #
Output: 11 is a prime number.

Question 19: Generate the Fibonacci Sequence


# Generate the Fibonacci sequence up to a specified number of terms def
fibonacci_sequence(n): sequence = []
a, b = 0, 1 while
len(sequence) < n:
[Link](a) a,
b = b, a + b return
sequence

# Example usage terms = 8 fib_sequence = fibonacci_sequence(terms)


print(f"Fibonacci Sequence ({terms} terms): {fib_sequence}") #
Output: Fibonacci Sequence (8 terms): [0, 1, 1, 2, 3, 5, 8, 13]

Question 20: Convert Temperature Between Celsius and Fahrenheit.


# Convert temperature from Celsius to Fahrenheit and vice versa def
celsius_to_fahrenheit(celsius): return (celsius * 9/5) + 32

def fahrenheit_to_celsius(fahrenheit): return


(fahrenheit - 32) * 5/9

# Example usage celsius_temp


= 30
fahrenheit_temp = celsius_to_fahrenheit(celsius_temp) print(f"{celsius_temp}°C
is equal to {fahrenheit_temp}°F") fahrenheit_temp = 86 celsius_temp =
fahrenheit_to_celsius(fahrenheit_temp) print(f"{fahrenheit_temp}°F is equal to
{celsius_temp}°C") # Output:
# 30°C is equal to 86.0°F
# 86°F is equal to 30.0°C

Question 21: Calculate the Sum of All Elements in a List.

# Calculate the sum of all elements in a list


def sum_of_elements(lst): return sum(lst)

# Example usage
numbers = [1, 2, 3, 4, 5]
total_sum = sum_of_elements(numbers) print("Sum of
Elements:", total_sum)
# Output: Sum of Elements: 15
Question 22: Remove Duplicates from a List
# Remove duplicates from a list def
remove_duplicates(lst):
return list(set(lst))

# Example usage elements = [1, 2, 2, 3, 4, 4, 5]


unique_elements = remove_duplicates(elements)
print("List with Duplicates Removed:", unique_elements)
# Output: List with Duplicates Removed: [1, 2, 3, 4, 5]
Question 24: Generate a List of Squares Using List Comprehension

# Generate a list of squares of numbers from 1 to N using list comprehension


def squares_list(n): return [i**2 for i in range(1, n+1)]
# Example usage N
=5
squares = squares_list(N) print(f"Squares of numbers
from 1 to {N}:", squares)
# Output: Squares of numbers from 1 to 5: [1, 4, 9, 16, 25] Question
25: Sort a List of Strings in Alphabetical Order # Sort a list of strings in alphabetical
order def sort_strings_alphabetically(lst): return sorted(lst)

# Example usage words = ["banana", "apple", "orange",


"grape"] sorted_words
= sort_strings_alphabetically(words) print("Sorted List of Strings:",
sorted_words)
# Output: Sorted List of Strings: ['apple', 'banana', 'grape', 'orange'] Dictionary
Operations
Question 26: Merge Two Dictionaries

# Merge two dictionaries def


merge_dictionaries(dict1, dict2):
return {**dict1, **dict2}

# Example usage
dict1 = {'a': 1, 'b': 2} dict2 = {'c': 3, 'd': 4}
merged_dict = merge_dictionaries(dict1, dict2)
print("Merged Dictionary:", merged_dict)
# Output: Merged Dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4} Question 27: Access Value
Associated with a Given Key in a Dictionary
# Access value associated with a given key in a dictionary def
access_dictionary_value(dictionary, key): return
[Link](key)

# Example usage
student_scores = {'Alice': 85, 'Bob': 92, 'Charlie': 78} score =
access_dictionary_value(student_scores, 'Bob') print("Score for 'Bob':",
score)
# Output: Score for 'Bob': 92
Question 28: Get All Keys from a Dictionary
# Get all keys from a dictionary def
get_dictionary_keys(dictionary): return
list([Link]())

# Example usage fruit_inventory = {'apple': 10, 'banana': 20, 'orange':


15} keys =
get_dictionary_keys(fruit_inventory)
print("Dictionary Keys:", keys)
# Output: Dictionary Keys: ['apple', 'banana', 'orange']
Question 29: Update a Dictionary with Key-Value Pairs from Another Dictionary

# Update a dictionary with key-value pairs from another dictionary def


update_dictionary(dict1, dict2):
[Link](dict2)
return dict1

# Example usage
original_dict = {'a': 1, 'b': 2} update_dict = {'c': 3, 'd': 4} updated_dict =
update_dictionary(original_dict, update_dict) print("Updated Dictionary:",
updated_dict)
# Output: Updated Dictionary: {'a': 1, 'b': 2, 'c': 3, 'd': 4}
Question 30: Create a Dictionary with Keys as Numbers from 1 to N and Values as Squares

# Create a dictionary with keys as numbers from 1 to N and values as squares of the keys
def create_squared_dictionary(n): return {i: i**2 for i in range(1, n+1)}

# Example usage N
=4
squared_dict = create_squared_dictionary(N) print(f"Dictionary with Keys (1 to {N})
and Squared Values:", squared_dict) # Output: Dictionary with Keys (1 to 4) and
Squared Values: {1: 1, 2: 4, 3: 9, 4: 16}

You might also like