Name:- Shivam Santosh Bansode
Course:- Diploma in computer engineering
Year:- Third year
Page 1
❖ BASIC PYTHON PROGRAMS
1. Factorial
fact=1
num=int(input("enter the no="))
for i in range(num,0,-1):
fact=fact*ii
print("factorial is-=",fact)
Output:-
enter the no= 5
factorial is= 120
2. Fibonacci
a=0
b=1
count=10;
print( a,b)
for i in range (2,count,+1):
c=a+b
print(c)
a=b
b=c
Output:-
0
1
1
2
3
5
8
13
21
34
3. Check No is Prime or Not
a=int(input("enter the number="))
flag=0
Page 2
for i in range (0,a):
if(a%2==0):
flag=1
break;
if(flag==1):
print("no is not prime")
else:
print("no is prime")
Output:-
enter the number= 12
no is not prime
4. Check No is even or odd
a=int(input("enter the number="))
if(a%2==0):
print("no is even")
else:
print("no is odd")
Output:-
enter the number= 3
no is odd
5. Check Year is leap or not
a=int(input("enter the year="))
if(a%4==0):
print("year is leap")
else:
print("year is not leap")
Output:-
enter the year= 2021
year is not leap
6. Largest no among three no
a=int(input("enter the First no="))
b=int(input("enter the Second no="))
c=int(input("enter the Third no="))
if(a>b):
if(a>c):
print("First no is greater")
else:
Page 3
print("Third no is greater")
elif(b>c):
print("second no is greater")
else:
print("third no is greater")
Output:-
enter the First no= 12
enter the Second no= 34
enter the Third no= 65
third no is greater
7. Covert Celcius to Faranite
c=int(input("enter the celcius="))
f=(9/5)*c+32
print("conversion in farnite is =",f)
Output:-
enter the celcius= 8
conversion in farnite is = 46.4
8. Reverse String
a=input("enter string=")
a[::-1]
Output:-
enter string= rushi
'ihsur'
9. Pallindrome
a=input("enter the string=")
b=a[::-1]
if(a==b):
print("string is pallindrome")
else:
print("string is not pallindrome")
Output:-
enter the string= nitin
string is palindrome
10. Find Ascci value
Page 4
a=input("enter the string=")
ord(a)
Output:-
enter the character= H
72
11.Cout no.of Words in String
a="om is handsome guy"
b=len(a.split())
print("No of words in string is =",b)
Output:-
No of words in string is = 4
12.Factorial using function
def factorial(num):
fact=1
for i in range(num,0,-1):
fact=fact*i
print("factorial is-=",fact)
num=int(input("enter the no="))
factorial(num)
Output:-
enter the no= 5
factorial is= 120
13.Cout Vowels in String
string =input("enter string=")
vowels = "aeiouAEIOU"
count = sum(string.count(vowel) for vowel in vowels)
print(count)
Page 5
Output:-
enter string=shivaji
3
14.Print Multiplicatio table
no=int(input("enter the no ="))
for i in range(1,11):
print(no*i)
Output:-
enter the no =12
12
24
36
48
60
72
84
96
108
120
15.Generate a simple pattern
rows = int(input("Enter number of rows: "))
for i in range(rows):
for j in range(i+1):
print("* ", end="")
print()
Output:-
Enter number of rows: 5
*
**
***
****
*****
16.Generate Random number
import random
print(random.random())
Page 6
Output:-
0.7658840982392084
17.Write a program to check age criteria
9,
if(age>18):
print("your eligible for voting")
else:
print("your not eligible for voting")
Output:-
enter the age=22
your eligible for voting
18.Write a program of sum of Nth number
no=int(input("enter the no="))
r=0
for i in range(no+1):
r=r+i
print(r)
Output:-
enter the no=5
15
19.Write a program to reverse integer
no=int(input("enter the no="))
reverse=0
while(no!=0):
reminder=no%10
reverse=reverse*10+reminder
no//=10
print(reverse)
Output:-
enter the no=123
321
20.Write a program to print opposite rigth angle triangle
rows = int(input("Please Enter the Total Number of Rows : "))
Page 7
for i in range(1, rows + 1):
for j in range(1, rows + 1):
if(j <= rows - i):
print(' ', end = ' ')
else:
print("*", end = ' ')
print()
Output:-
Please Enter the Total Number of Rows : 8
*
* *
* * *
* * * *
* * * * *
* * * * * *
* * * * * * *
* * * * * * * *
21.Write a program to calculate x^n by for loop
num = int(input("Enter the number of which you have to find power: "))
pw = int(input("Enter the power: "))
kj = 1
for n in range(pw):
kj = kj*num
print(kj)
Output:-
Enter the number of which you have to find power: 2
Enter the power: 3
8
22.Write a program to create a list of values inputted by user
list=[]
n=int(input("enter the no of element="))
for i in range(0,n):
ele=int(input())
list.append(ele)
print(list)
Output:-
enter the no of element=5
12
Page 8
26
56
22
25
[12, 26, 56, 22, 25]
23.Write a program to create a list of values inputted by user & sort in increasing
order
list=[]
n=int(input("enter the no of element="))
for i in range(0,n):
ele=int(input())
list.append(ele)
list.sort()
print(list)
Output:-
enter the no of element=3
452
2
3
[2, 3, 452]
24.Sorting in acending order use bubble sort
arr = [64, 34, 25, 12, 22, 11, 90]
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
print("Sorted array is:")
for i in range(len(arr)):
print("% d" % arr[i], end=" ")
Output:-
Sorted array is:
11 12 22 25 34 64 90
25.Write a program to creat a Phone dictionary
phone_dict = {}
while True:
name = input("Enter name (or 'exit' to stop): ").strip()
if name.lower() == 'exit':
Page 9
break
phone = input(f"Enter phone number for {name}: ").strip()
phone_dict[name] = phone
print("\nPhone Dictionary:")
for name, phone in phone_dict.items():
print(f"{name}: {phone}")
Output:-
Enter name (or 'exit' to stop): rushi
Enter phone number for rushi: 7035857070
Enter name (or 'exit' to stop): sandy
Enter phone number for sandy: 7972413282
Enter name (or 'exit' to stop): chaitanya
Enter phone number for chaitanya: 9423363448
Enter name (or 'exit' to stop): exit
Phone Dictionary:
rushi: 7035857070
sandy: 7972413282
chaitanya: 9423363448
26.Write a program to create a tuple of values inputted by user
def create_tuple_from_input():
input_str = input("Enter values separated by spaces: ")
values_list = input_str.split()
values_tuple = tuple(values_list)
return values_tuple
if __name__ == "__main__":
user_tuple = create_tuple_from_input()
print("Tuple created:", user_tuple)
Output:-
Enter values separated by spaces: rushi chaitanya deva
Tuple created: ('rushi', 'chaitanya', 'deva')
27.Reverse a interger
n=int(input("enter the number="))
reverse=0
while n!=0:
reminder=n%10
reverse=reverse*10+reminder
n //= 10
Page 10
print(reverse)
Output:-
enter the number=123
321
28.Write a program to create a new string made of an input strings first ,middle
and last character
f=(input("enter the first name="))
m=(input("enter the middle name="))
l=(input("enter the last name="))
print(f+m+l)
Output:-
enter the first name=rushi
enter the middle name=sunil
enter the last name=kolekar
rushisunilkolekar
29. Random Number
import random
a=[1,2,3,4,5,6,7,8,9,0]
print(random.choice(a))
print(random.sample(range(1000,9999),1))
Output:-
3
[9230]
30.Find the power of the number
Page 11
a=int(input("Enter the base value"))
b=int(input("Enter the power of value"))
c=1
for i in range(1,b+1):
c=c*a
print(c)
Output:-
Enter the base value 2
Enter the power of value 3
8
31.Merge 2 sorted list
a=[20,18,10,50,45]
a.sort()
b=[99,45,63,21,11,2]
b.sort()
b.extend(a)
b.sort()
print(b)
Output:- [2, 10, 11, 18, 20, 21, 45, 45, 50, 63, 99]
32.Draw pyramid
def draw_pyramid(rows):
for i in range(1, rows + 1)
print(' ' * (rows - i), end='')
print('* ' * i)
rows = int(input("Enter the number of rows for the pyramid: "))
draw_pyramid(rows)
Output:-
Page 12
Enter the number of rows for the pyramid: 5
*
**
***
****
*****
33.Creating list of prime number in range 1 to 50
a=list()
for i in range(1,50)
flag=0
if(i==0 or i==1):
flag=1
else:
if(i%2==0):
flag=1
if(flag==0 or i==2):
a.append(i)
print(a)
Output:-
[2, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39, 41, 43, 45, 47, 49]
34.GCD of 2 numbers
a=int(input("Enter the 1st number"))
b=int(input("Enter the 2nd number"))
if(a>b):
small=b
else:
small=a
for i in range(1,small+1):
if((a%i==0) & (b%i==0)):
gcd=i
print("GCD of given numbers is ",gcd)
Output:-
Enter the 1st number 60
Enter the 2nd number 48
Page 13
GCD of given numbers is 12
35.Cheak the year is leap or not using function
def cheak(year):
if(year%4==0):
print(year,"is leap year")
else:
print(year,"is not leap year")
cheak(2020)
Output:-
2020 is leap year
36.Cheak perfect number
n=int(input("Enter the number"))
sum=0
for i in range(1,n):
if(n%i==0):
sum=sum+i
if(n==sum):
print(n,"is perfect number")
else:
print(n,"is not perfect number")
Output:-
Enter the number 6
6 is perfect number
37.concating 2 strings
a=input("Enter 1st string")
b=input("Enter 2nd string")
print(a+b)
Output:-
Enter 1st string omkar
Page 14
Enter 2nd string jadhav
omkarjadhav
38.Perfect square numbers
import math
i=int(input("Enter the number"))
if(math.sqrt(i) == math.floor(math.sqrt(i))):
print(i,"is perfect square number")
else:
print(i,"is not perfect square number")
Output:-
Enter the number 16
16 is perfect square number
39.print the factors of the number
n=int(input("Enter the number"))
factors=list()
for i in range(2,n+1):
if(n%i==0):
factors.append(i)
print("factors=",factors)
Output:-
Enter the number 26
factors= [2, 13, 26]
40.Cheak string is pangram or not
import string
def ispangram(str):
alphabet = "abcdefghijklmnopqrstuvwxyz"
for char in alphabet:
if char not in str.lower():
return False
Page 15
return True
str=input("Enter string")
if(ispangram(str)):
print("string is pangram")
else:
print("string is pangram")
Output:-
Enter string omkar
string is pangram
41.find volume of cylinder
r=int(input("Enter the radius of Cylinder:"))
h=int(input("Enter the height of Cylinder:"))
volume=3.14*r*r*h
print("Volume of Cylinder is",volume)
Output:-
Enter the radius of Cylinder: 5
Enter the height of Cylinder: 10
Volume of Cylinder is 785.0
42.Sort the list
a=['z','a','g','b','e','q','x']
a.sort()
print(a)
Output:-
['a', 'b', 'e', 'g', 'q', 'x', 'z']
43.Calculate exponatial value
a=int(input("Enter the base number"))
b=int(input("Enter the power of base number"))
Page 16
c=a**b
print("The exponatial value is=",c)
Output:-
Enter the base number 2
Enter the power of base number 3
The exponatial value is= 8
44.sum of natural number
def sum(n):
if n <= 0:
return 0
else:
return n + sum(n - 1)
n = int(input("Enter the number"))
result = sum(n)
print(f"The sum of natural numbers from 1 to {n} is: {result}")
Output:-
Enter the number 5
The sum of natural numbers from 1 to 5 is: 15
45.find the median of three number
def median(a, b, c):
if a >= b >= c or c >= b >= a:
return b
elif b >= a >= c or c >= a >= b:
return a
else:
return c
num1 =int(input("Enter 1st number"))
num2 = int(input("Enter 2nd number"))
num3 = int(input("Enter 3rd number"))
Page 17
median = median(num1, num2, num3)
print(f"The median of {num1}, {num2}, {num3} is: {median}")
Output:-
Enter 1st number 10
Enter 2nd number 15
Enter 3rd number 20
The median of 10, 15, 20 is: 15
46.decimal to binary number
decimal_number = 65
binary_number = bin(decimal_number)[2:]
print(f"Binary representation of {decimal_number}: {binary_number}")
Output:-
Binary representation of 65: 1000001
47.decimal to octal
decimal_number = 65
octal_number = oct(decimal_number)[2:]
print(f"Octal representation of {decimal_number}: {octal_number}")
Output:-
Octal representation of 65: 101
48.decimal to hexadecimal
decimal_number = 65
hexadecimal_number = hex(decimal_number)[2:]
print(f"Hexadecimal representation of {decimal_number}:
{hexadecimal_number.upper()}")
Output:-
Hexadecimal representation of 65: 41
49.find the sum of digits in number
def sum(number):
sum_digits = 0
while number > 0:
sum_digits += number % 10
number //= 10
return sum_digits
num = int(input("Enter the number"))
result = sum(num)
Page 18
print(f"The sum of digits in {num} is: {result}")
Output:-
Enter the number 4578
The sum of digits in 4578 is: 24
50.Find the Sum of Elements in a List
def elements(lst):
sum_elements = 0
for element in lst:
sum_elements += element
return sum_elements
my_list = [1, 2, 3, 4, 5]
result = elements(my_list)
print(f"The sum of elements in the list {my_list} is: {result}")
Output:-
The sum of elements in the list [1, 2, 3, 4, 5] is: 15
51.Calculate the Area of a Triangle Using Heron's Formula
import math
def calculate(a, b, c):
s = (a + b + c) / 2
area = math.sqrt(s * (s - a) * (s - b) * (s - c))
return area
side_a = 5
side_b = 7
side_c = 8
area = calculate(side_a, side_b, side_c)
print(f"The area of the triangle with sides {side_a}, {side_b}, {side_c} is: {area}")
Output:-
The area of the triangle with sides 5, 7, 8 is: 17.320508075688775
52.Sort a List of Dictionaries by a Specific Key
people = [
{'name': 'Alice', 'age': 25},
{'name': 'Bob', 'age': 30},
Page 19
{'name': 'Charlie', 'age': 20},
{'name': 'David', 'age': 35},
{'name': 'Eve', 'age': 28}
]
sorted_people = sorted(people, key=lambda x: x['age'],reverse="True")
print("Sorted by age (ascending):")
for person in sorted_people:
print(person)
Output:-
Sorted by age (ascending):
{'name': 'David', 'age': 35}
{'name': 'Bob', 'age': 30}
{'name': 'Eve', 'age': 28}
{'name': 'Alice', 'age': 25}
{'name': 'Charlie', 'age': 20}
53.To create a new string made of the middle three characters of
an input string
def get_middle_three_chars(s):
length = len(s)
if length < 3:
return "String length is less than 3"
else:
mid = length // 2
return s[mid-1:mid+2]
s = input("Enter a string: ")
print(get_middle_three_chars(s))
Output:-
Enter a string: Hello
ell
54.Append new string in the middle of a given string :
my_string = "Hello"
new_string = "World"
index = 5 my_string = f"{my_string[:index]}{new_string}{my_string[index:]}" print(my_stri
ng)
Page 20
Output:
HelloWorld
55.Create a new string made of the first, middle, and last characters of
each input string:
def create_new_string(*strings):
new_string = ''
for s in strings:
if len(s) < 3:
new_string += s
else:
new_string += s[0] + s[len(s)//2] + s[-1]
return new_string
print(create_new_string('abc', 'hello', 'python'))
Output:-
abchlophn
56.Arrange string characters such that lowercase letters should come fir
st:
def arrange_string(s):
lowercase_chars = [c for c in s if c.islower()]
uppercase_chars = [c for c in s if c.isupper()]
return ''.join(lowercase_chars + uppercase_chars)
s = "Hello World"
print(arrange_string(s))
Output:-
elloorldHW
57.Count all letters, digits, and special symbols from a given string:
def count_characters(s):
letters = 0
digits = 0
symbols = 0
for char in s:
if char.isalpha():
Page 21
letters += 1
elif char.isdigit():
digits += 1
else:
symbols += 1
return letters, digits, symbols
s = input("Enter a string: ")
letters, digits, symbols = count_characters(s)
print(f"Letters: {letters}")
print(f"Digits: {digits}")
print(f"Symbols: {symbols}")
Output:
Enter a string: Hello World
Letters: 10
Digits: 0
Symbols: 1
58.Create a mixed String using the following rules
Given two strings, s1 and s2. Write a program to create a new string s3 made of the
first char of s1, then the last char of s2, Next, the second char of s1 and second last char
of s2, and so on. Any leftover chars go at the end of the result:
def mix_strings(s1, s2):
result = []
for i in range(min(len(s1), len(s2))):
result.append(s1[i])
result.append(s2[-i-1])
result.extend(s1[min(len(s1), len(s2)):][::-1])
result.extend(s2[max(len(s1), len(s2)):][::-1])
return ''.join(result)
s1 = "abc"
s2 = "pqr"
print(mix_strings(s1, s2))
Output:-
Page 22
arbqcp
59.String characters balance Test
Write a program to check if two strings are balanced. For example, strings s1 and s2
are balanced if all the characters in the s1 are present in s2. The character’s position
doesn’t matter:
def are_strings_balanced(s1, s2):
set1 = set(s1)
set2 = set(s2)
if set1.issubset(set2):
return True
else:
return False
s1 = "abc"
s2 = "abccba"
print(are_strings_balanced(s1, s2))
s1 = "abc"
s2 = "def"
print(are_strings_balanced(s1, s2))
Output:
True
False
60.Generate a Random Matrix
import random
rows = 3
columns = 3
random_matrix = [[random.randint(111,999) for j in range(columns)] for i in range(rows)]
for row in random_matrix:
print(row)
Output:-
[910, 550, 361]
[688, 617, 338]
[322, 578, 187]
61.Calculate sum of average of digits in string
def sum_digits(digit):
return sum(int(x) for x in digit if x.isdigit())
print(sum_digits('hihello153john'))
Page 23
Output:-
9
62.Write a program to count occurrences of all characters
within a string
input_string = "Pythonforbeginners is a great source ."
print("The input string is:", input_string)
mySet = set(input_string)
for element in mySet:
countOfChar = 0
for character in input_string:
if character == element:
countOfChar += 1
print(f"Count of character '{element}' is {countOfChar}")
Output:-
The input string is: Pythonforbeginners is a great source .
Count of character 'a' is 2
Count of character 'f' is 1
Count of character 'r' is 4
Count of character 'o' is 3
Count of character 't' is 2
Count of character 'g' is 2
Count of character 'c' is 1
Count of character '.' is 1
Count of character 'b' is 1
Count of character 'y' is 1
Count of character 'i' is 2
Count of character 'e' is 4
Count of character 's' is 3
Count of character 'h' is 1
Count of character 'u' is 1
Count of character 'P' is 1
Count of character 'n' is 3
Count of character ' ' is 5
63.Reverse a given string
str = "Hello World"[::-1]
print(str)
Output:-
dlroW olleH
Page 24