SSM INSTITUTE OF ENGINEERING AND TECHNOLOGY
DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING
PYTHON BASIC PROGRAMS
1.# python program to add two numbers
# take inputs
num1 = 5
num2 = 10
# add two numbers
sum = num1 + num2
# displaying the addition result
print(sum)
2.#Python program to subtract two numbers
# take inputs
num1 = 10
num2 = 7
# subtract two numbers
sub = num1 - num2
# print the subtraction result
print('The subtraction of numbers =', sub)
3.# Python program to multiply two number
# take inputs
num1 = 3
num2 = 5
# calculate product
product = num1*num2
# print multiplication value
print("The Product of Number:", product)
4.# Python program to divide two numbers
# take inputs
num1 = 10
num2 = 2
# Divide numbers
division = num1/num2
# print value
print(division)
5.# Python program to find average of two numbers
# first number
num1 = 10
# second number
num2 = 20
# calculate average of those numbers
avg = (num1 + num2) / 2
# print average value
print('The average of numbers = %0.2f' %avg)
6.# Python program to find average of two numbers
# take inputs
num1 = float(input('Enter first number: '))
num2 = float(input('Enter second number: '))
# calculate average of those numbers
avg = (num1 + num2) / 2
# print average value
print('The average of numbers = %0.2f' %avg)
7# Python program to find average of two numbers using function
def avg_num(num1, num2): #user-defined function
avg = (num1 + num2) / 2 #calculate average
return avg #return value
# take inputs
num1 = float(input('Enter first number: '))
num2 = float(input('Enter second number: '))
# function call
average = avg_num(num1, num2)
# display result
print('The average of numbers = %0.2f' %average)
8.# Python program to find the average of two numbers using loop
# denotes total sum of numbers
total_sum = 0
for n in range (2):
# take inputs
num = float(input('Enter number: '))
# calculate total sum of numbers
total_sum += num
# calculate average of numbers
avg = total_sum / 2
# print average value
print('Average of numbers = %0.2f' %avg)
9.# Python program to find average of three numbers
# take inputs
num1 = 3
num2 = 5
num3 = 14
# calculate average
avg = (num1 + num2 + num3)/3
# display result
print('The average of numbers = %0.2f' %avg)
10.# python program to add two numbers with user input
# store input numbers
num1 = input('Enter First Number: ')
num2 = input('Enter Second Number: ')
# add two numbers
# User might also enter float numbers
sum = float(num1) + float(num2)
# displaying the adding result
# value will print in float
print(“The sum of number is:” sum))
11.# Python program to add two numbers using function
def add_num(a,b): #user-defined function
sum = a + b #adding numbers
return sum #return value
# take input
num1 = float(input('Enter first number : '))
num2 = float(input('Enter second number : '))
# function call
print('The sum of numbers {0} and {1} is {2}'.format(num1, num2, add_num(num1,
num2)))
12.# Python program to find square root of the number
# take inputs
num = 25
# calculate square root
sqrt = num ** 0.5
# display result
print('Square root of %0.2f is %0.2f '%(num, sqrt))
13.# python program to find area of circle
# take inputs
r = 10
# calculate area of circle
area = 3.14 * r * r
# display result
print('Area of circle = ',area)
14.# python program to find the area of the triangle
# take inputs
base = float(input('Enter the base of the triangle: '))
height = float(input('Enter the height of the triangle: '))
# calculate area of triangle
area = (1/2) * base * height
# display result
print('Area of triangle = ',area)
15.# python program to find area of rectangle
# take inputs
length = 2
width = 5
# calculate area of rectangle
area = length * width
# display result
print('Area of rectangle = ',area)
16.# Python program to convert kilometers to miles
# take inputs
km = float(input('Enter distance in kilometers: '))
# conversion factor
conv_fac = 0.621371
# calculate Miles
mile = km * conv_fac
# display result
print('%0.2f kilometers is equal to %0.2f miles' %(km, mile))
17.# Python program to swap two variables using temporary variable
# take inputs
a = input('Enter the value of a: ')
b = input('Enter the value of b: ')
print('Values Before Swapping')
print('a = ',a, 'and b = ',b)
# create a temporary variable and swap the value
temp = a
a = b
b = temp
# display swapping values
print('Values After Swapping')
print('a = ',a, 'and b = ',b)
18.# Python program to swap two numbers
# without using temporary variable
# take inputs
a = input('Enter the value of a: ')
b = input('Enter the value of b: ')
print('Values Before Swapping')
print('a = ',a, 'and b = ',b)
# swap the value
a, b = b, a
# display swapping values
print('Values After Swapping')
print('a = ',a, 'and b = ',b)
19.# Python program to calculate simple interest
# store the inputs
P = float(input('Enter principal amount: '))
R = float(input('Enter the interest rate: '))
T = float(input('Enter time: '))
# calculate simple interest
SI = (P * R * T) / 100
# display result
print('Simple interest = ',SI )
print('Total amount = ',( P + SI ))
20.# Python program to calculate simple interest using function
def calculate_simple_interest(P, R, T):
# calculate simple interest
SI = (P * R * T) / 100
return SI;
if __name__ == '__main__':
# store the inputs
P = float(input('Enter principal amount: '))
R = float(input('Enter the interest rate: '))
T = float(input('Enter time: '))
# calling function
simple_interest = calculate_simple_interest(P, R, T)
# display result
print('Simple interest = %.2f' %simple_interest)
print('Total amount = %.2f' %(P + simple_interest))
21.# Python program to find compound interest
# store the inputs
principal = float(input('Enter principal amount: '))
rate = float(input('Enter the interest rate: '))
time = float(input('Enter time (in years): '))
number = float(input('Enter the number of times that
interest is compounded per year: '))
# convert rate
rate = rate/100
# calculate total amount
amount = principal * pow( 1+(rate/number), number*time)
# calculate compound interest
ci = amount - principal
# display result
print('Compound interest = %.2f' %ci)
print('Total amount = %.2f' %amount)
22.# Python program to calculate compound interest using function
def compound_interest(principal, rate, time, number):
# calculate total amount
amount = principal * pow( 1+(rate/number), number*time)
return amount;
# store the inputs
principal = float(input('Enter principal amount: '))
rate = float(input('Enter the interest rate: '))
time = float(input('Enter time (in years): '))
number = float(input('Enter the number of times that
interest is compounded per year: '))
# convert rate
rate = rate/100
# calling function
amount = compound_interest(principal, rate, time, number)
# calculate compound interest
ci = amount - principal
# display result
print('Compound interest = %.2f' %ci)
print('Total amount = %.2f' %amount)
PYTHON FLOW CONTROL PROGRAMS
23.# Python program to check number is perfect square or not
import math #importing math-module
# take inputs
num = int(input('Enter number: '))
root = math.sqrt(num)
# check number is perfecct square
if int(root + 0.5) ** 2 == num:
print(num, 'is a perfect square')
else:
print(num, 'is not a perfect square')
24.# Python program to check perfect square without sqrt()
def PerfectSquare(x) :
i = 1
while(i**2 <= x):
if ((x%i == 0) and (x/i == i)):
return True
i += 1
return False
# take inputs
num = int(input('Enter number: '))
# calling function and display result
if (PerfectSquare(num)):
print(num, 'is a perfect square')
else:
print(num, 'is not a perfect square')
25.# Python program to find absolute value of number for integer
# take input
num = int(input('Enter the integer number: '))
# display result
print('Absolute value of number is =',abs(num))
26.# Python program to find absolute value of number for float
# take input
num = float(input('Enter a float number: '))
# display result
print('Absolute value of number is =',abs(num))
27.# Python program to find absolute value of complex number
# take input
num = complex(input('Enter a complex number: '))
# display result
print('Magnitude of complex number is =',abs(num))
28.# Python program to make a simple calculator
# take inputs
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# choise operation
print("Operation: +, -, *, /")
select = input("Select operations: ")
# check operations and display result
# add(+) two numbers
if select == "+":
print(num1, "+", num2, "=", num1+num2)
# subtract(-) two numbers
elif select == "-":
print(num1, "-", num2, "=", num1-num2)
# multiplies(*) two numbers
elif select == "*":
print(num1, "*", num2, "=", num1*num2)
# divides(/) two numbers
elif select == "/":
print(num1, "/", num2, "=", num1/num2)
else:
print("Invalid input")
29.# Python program to make a simple calculator using function
# This function adds two numbers
def add(a, b):
return a + b
# This function subtracts two numbers
def subtract(a, b):
return a - b
# This function multiplies two numbers
def multiply(a, b):
return a * b
# This function divides two numbers
def divide(a, b):
return a / b
# take inputs
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# choise operation
print("Operation: +, -, *, /")
select = input("Select operations: ")
# check operations and display result
if select == "+":
print(num1, "+", num2, "=", add(num1, num2))
elif select == "-":
print(num1, "-", num2, "=", subtract(num1, num2))
elif select == "*":
print(num1, "*", num2, "=", multiply(num1, num2))
elif select == "/":
print(num1, "/", num2, "=", divide(num1, num2))
else:
print("Invalid input")
30.# Python program to print fibonacci series up to n-th term
# take input
num = int(input('Enter number of terms: '))
# print fibonacci series
a, b = 0, 1
i = 0
# check if the number of terms is valid
if num <= 0:
print('Please enter a positive integer.')
elif num == 1:
print('The Fibonacci series: ')
print(a)
else:
print('The Fibonacci series: ')
while i < num:
print(a, end=' ')
c = a + b
a = b
b = c
i = i+1
31.# Python program to find ASCII value of character
# take input
ch = input("Enter any character: ")
# printing ascii value of character
print("The ASCII value of " + ch + " is:", ord(ch))
32.# Python program to find ASCII value of all characters
#importing string function
import string
# printing ascii value of character
for c in string.ascii_letters:
print(c,':', ord(c), end = ', ')
33.# Python program to reverse a number
# take inputs
num = int(input('Enter an integer number: '))
# calculate reverse of number
reverse = 0
while(num > 0):
last_digit = num % 10
reverse = reverse * 10 + last_digit
num = num // 10
# display result
print('The reverse number is = ', reverse)
34.# Python program to reverse a number using recursion
reverse, base = 0, 1
def findReverse(num):
global reverse #function definition
global base #function definition
if(num > 0):
findReverse((int)(num/10))
reverse += (num % 10) * base
base *= 10
return reverse
# take inputs
num = int(input('Enter an integer number: '))
# display result
print('The reverse number is =', findReverse(num))
35.# Python program to reverse a number using slicing
# take inputs
num = int(input('Enter an integer number: '))
# calculate reverse of number
reverse = int(str(num)[::-1])
# display result
print('The reverse number is = ', reverse)
36.# Python program to find prime factors of a number
# take inputs
num = int(input('Enter number: '))
# find prime factors
for i in range(2, num + 1):
if(num % i == 0):
isPrime = 1
for j in range(2, (i //2 + 1)):
if(i % j == 0):
isPrime = 0
break
if (isPrime == 1):
print(i,end=' ')
print('are the prime factors of number',num)
37.# Python Program to get the first digit of number
# take input
num = int(input('Enter any Number: '))
# get the first digit
while (num >= 10):
num = num // 10
# printing first digit of number
print('The first digit of number:', num)
38.# Python program to find the factorial of a number using math function
import math #math module
# take input
num = 5
# find factorial of a number and display result
print('The factorial of',num,'is', math.factorial(num))
39.# Python program to find the factorial of a number
# take input
num = int(input("Enter number: "))
# check number is positive, negative, or zero
if num < 0:
print('Factorial does not exist for negative numbers')
elif num == 0:
print('The factorial of 0 is 1')
else:
# find factorial of a number
fact = 1
i = 1
while(i <= num):
fact = fact*i
i = i+1
print('The factorial of',num,'is',fact)
40.# Python program to find the factorial of a number using recursion
def recur_factorial(n): #user-defined function
if n == 1:
return n
else:
return n*recur_factorial(n-1)
# take input
num = int(input("Enter number: "))
# check number is positive, negative, or zero
if num < 0:
print('Factorial does not exist for negative numbers')
elif num == 0:
print('The factorial of 0 is 1')
else:
# calling function
print('The factorial of',num,'is', recur_factorial(num))
41.# Python program to find the factorial of a number using function
def factorial(num): #user-defined function
# find factorial of a number
fact = 1
for i in range(1,num + 1):
fact = fact*i
return fact
# take input
num = int(input("Enter number: "))
# check number is positive, negative, or zero
if num < 0:
print('Factorial does not exist for negative numbers')
elif num == 0:
print('The factorial of 0 is 1')
else:
# calling function
print('The factorial of',num,'is',factorial(num))
42.# Python program to find the factorial of a number using math function
import math #math module
def factorial(num):
# find factorial of a number
print('The factorial of',num,'is', math.factorial(num))
# take input
num = int(input("Enter number: "))
# calling function
factorial(num)
43.# Python program to check given number is an even or odd
# take inputs
num = 5
# check number is even or odd
if(num % 2 == 0):
print('even number'(num))
else:
print('odd number'(num))
44.# Python program to check given number is an even or odd using function
# Returns true if num is even, else odd
def oddEven(num):
# check number is even or odd
return (num % 2 == 0)
# take inputs
num = int(input('Enter a number: '))
# display result
if oddEven(num):
print('even number'(num))
else:
print('odd number'(num))
45.# Python program to print all even and odd numbers in given range
# take range
start = int(input('Start: '))
end = int(input('End: '))
for num in range(start, end + 1):
# check number is odd or not
if num % 2 == 0:
print(num, end = ':Even ')
else:
print(num, end = ':Odd ')
46.# Python program to print all even and odd numbers in given range
# take range
start, end = 1, 100
for num in range(start, end + 1):
# check number is odd or not
if num % 2 == 0:
print(num,end = ':Even ')
else:
print(num, end = ':Odd ')
47.# Python program to print multiplication table
# take inputs
num = int(input('Display multiplication table of: '))
# print multiplication table
for i in range(1, 11):
print ("%d * %d = %d" % (num, i, num * i))
48.# Python program to print multiplication table using loop
# take inputs
num = int(input('Display multiplication table of: '))
# print multiplication table
i = 1
while i <= 10:
print ("%d * %d = %d" %(num, i, num * i))
i = i+1
49.# Python program to check year is a leap year or not
# take input
year = int(input('Enter a year: '))
# check leap year or not
if (year % 400) == 0:
print('{0} is a leap year'.format(year))
elif (year % 100) == 0:
print('{0} is not a leap year'.format(year))
elif (year % 400) == 0:
print('{0} is a leap year'.format(year))
else:
print('{0} is not a leap year'.format(year))
50.# Python program to find factors of a number
# take inputs
num = int(input('Enter number: '))
# find factor of number
print('The factors of', num, 'are:')
for i in range(1, num+1):
if(num % i) == 0:
print(i, end=' ')
51.# Python program to find difference between two numbers
# take inputs
num1 = float(input('Enter first number: '))
num2 = float(input('Enter second number: '))
# num1 is greater than num2
if num1 > num2:
diff = num1 - num2
# num1 is less than num2
else:
diff = num2 - num1
# print difference value
print('The difference between numbers = %0.2f' %diff)
52.# Python program to find roots of quadratic equation
import math #importing math-module
# take inputs
a = int(input('Enter the value of a: '))
b = int(input('Enter the value of b: '))
c = int(input('Enter the value of c: '))
# calculate discriminant
dis = (b**2) - (4*a*c)
# checking condition for discriminant
if(dis > 0):
root1 = (-b + math.sqrt(dis) / (2 * a))
root2 = (-b - math.sqrt(dis) / (2 * a))
print("Two distinct real roots are %.2f and %.2f" %(root1, root2))
elif(dis == 0):
root1 = root2 = -b / (2 * a)
print("Two equal and real roots are %.2f and %.2f" %(root1, root2))
elif(dis < 0):
root1 = root2 = -b / (2 * a)
imaginary = math.sqrt(-dis) / (2 * a)
print("Two distinct complex roots are %.2f+%.2f and %.2f-%.2f"
%(root1, imaginary, root2, imaginary))
53.# Python program to compute sum of digits in number
def ComputeSum(num): #user-defined function
sum = 0
while (num != 0):
sum += (num % 10)
num //= 10
return sum
# take input
num = int(input('Enter a number: '))
# calling function & display result
print('Sum of digits in number =', ComputeSum(num))
54.# Python program to find largest of 3 numbers
# take inputs
num1 = 5
num2 = 3
num3 = 9
# find largest numbers
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
# display result
print('The largest number = ', largest)
55.# Python program to find the largest among
# three numbers using max() function
# take inputs
num1 = float(input('Enter first number: '))
num2 = float(input('Enter second number: '))
num3 = float(input('Enter third number: '))
# find largest numbers and display result
print('The largest number = ', max(num1, num2, num3))
56.# Python program to find greatest of three numbers using function
def findLargest(num1, num2, num3): #user-defined function
# find largest numbers
if (num1 >= num2) and (num1 >= num3):
largest = num1
elif (num2 >= num1) and (num2 >= num3):
largest = num2
else:
largest = num3
return largest #return value
# take inputs
num1 = float(input('Enter first number: '))
num2 = float(input('Enter second number: '))
num3 = float(input('Enter third number: '))
# function call
maximum = findLargest(num1, num2, num3)
# display result
print('The largest number = ',maximum)
57.# Python program to find sum of n natural numbers
# take input
num = int(input('Enter a number: '))
# find sum of natural number
sum = 0
x = 1
while x <= num:
sum += x
x += 1
# display result
print('The sum of natural number =', sum)
58.# Python program to print ASCII table
# print ASCII table from 0 to 255
for i in range(256):
ch = chr(i)
print('ASCII value of', i, 'is =', ch)
59.# Python pandas divide two columns
# import pandas
import pandas as pd
# take inputs
df = pd.DataFrame({'column1':[4,9,10,15], 'column2':[2,3,5,15]})
# divide columns
df['division'] = df['column1'] / df['column2']
# print division value
print(df)
60.# Python program to check character is vowel or consonant
# take input
ch = input('Enter any character: ')
# check vowel or constant and display result
if(ch=='A' or ch=='a' or ch=='E' or ch =='e' or ch=='I'
or ch=='i' or ch=='O' or ch=='o' or ch=='U' or ch=='u'):
print(ch, "is a Vowel")
else:
print(ch, "is a Consonant")
61.# Python program to check whether a character is alphabet or not
# take input
ch = input("Enter any character: ")
# check charater is alphabet or not
if((ch>='a' and ch<= 'z') or (ch>='A' and ch<='Z')):
print(ch, "is an Alphabet.")
else:
print(ch, "is not an Alphabet.")
62.# Python program to print numbers from 1 to 100
print('Numbers from 1 to 100:')
for n in range(1, 101):
print(n, end=' ')
63.# Python program to find the average of n numbers
# total number you want to enter
n = int(input('How many numbers: '))
# denotes total sum of n numbers
total_sum = 0
for i in range (n):
# take inputs
num = float(input('Enter number: '))
# calculate total sum of numbers
total_sum += num
# calculate average of numbers
avg = total_sum / n
# print average value
print('The average value of numbers = %0.2f' %avg)
64.# Python program to find sum of n numbers
# total number you want to enter
n = int(input('How many numbers: '))
# denotes total sum of n numbers
total_sum = 0
for i in range (n):
# take inputs
num = float(input('Enter number: '))
# calculate total sum of numbers
total_sum += num
# print sum of numbers
print('The sum of numbers = %0.2f' %total_sum)
65.# Python program to count number of digits in a number
# take input
num = int(input('Enter any number: '))
# count number of digits
count = 0
while (num>0):
num = num//10
count = count+1
# printing number of digits
print('Number of digits:', count)
66.# Python program to find the LCM of the two numbers
# take inputs
num1 = int(input('Enter first number: '))
num2 = int(input('Enter second number: '))
# choose the greater number
if (num1 > num2):
greater = num1
else:
greater = num2
while(True):
# find LCM
if(greater % num1 == 0 and greater % num2 == 0):
print('The LCM of',num1,'and',num2,'is',greater)
break
greater += 1
67.# Python program to find the LCM using function
def find_lcm(a, b): #user-defined function
# choose the greater number
if a > b:
greater = a
else:
greater = b
while(True):
# find LCM
if((greater % a == 0) and (greater % b == 0)):
lcm = greater
break
greater += 1
return lcm
# take inputs
num1 = int(input('Enter first number: '))
num2 = int(input('Enter second number: '))
# calling function & display result
print('The LCM of',num1,'and',num2,'is',find_lcm(num1, num2))
68.# Python program to find GCD of two numbers
# take inputs
x = int(input('Enter First Number: '))
y = int(input('Enter Second Number: '))
# choose the smaller number
if x > y:
smaller = y
else:
smaller = x
# find gcd of the number
for i in range (1,smaller+1):
if((x % i == 0) and (y % i == 0)):
gcd = i
# display result
print('The GCD of',x,'and',y,'is',gcd)
69.# Python program to find GCD of two numbers using while loop
# take inputs
x = int(input('Enter First Number: '))
y = int(input('Enter Second Number: '))
# find gcd of the numbers
i = 1
while(i <= x and i <= y):
if(x % i == 0 and y % i == 0):
gcd = i
i += 1
# display result
print('The GCD of',x,'and',y,'is',gcd)
70.# Python program to find GCD of two numbers using function
def compute_gcd(x, y): #user-defined function
# choose the smaller number
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
gcd = i
return gcd
# take inputs
num1 = int(input('Enter First Number: '))
num2 = int(input('Enter Second Number: '))
# calling function & display result
print('The GCD of',num1,'and',num2,'is',compute_gcd(num1, num2))
PYTHON CONVERSION PROGRAMS
71.# Python program to find ASCII value of character
# take input
ch = input("Enter any character: ")
# printing ascii value of character
print("The ASCII value of " + ch + " is:", ord(ch))
72.# Python program to conversion ASCII to string
# take list
l = [75, 110, 111, 119, 32, 80, 114, 111, 103, 114, 97, 109]
# printing list
print("List of ASCII value =", l)
# ASCII to string using naive method
string = ""
for num in l:
string = string + chr(num)
# Printing string
print ("String:", str(string))
73.# Python program to find ASCII value of string
# take input
string = input("Enter any string: ")
# find ascii value of string
ASCII_value = sum(map(ord, string))
# printing ascii value
print("The ASCII value of characters:", ASCII_value)
74.# Python program to convert hex string to ASCII string
# importing codecs.decode()
import codecs
# take hexadecimal string
hex_str = '0x68656c6c6f'[2:]
# convert hex string to ASCII string
binary_str = codecs.decode(hex_str, 'hex')
ascii_str = str(binary_str,'utf-8')
# printing ASCII string
print('ASCII String:', ascii_str)
75.# Python program to convert decimal to binary
# take input
num = int(input('Enter any decimal number: '))
# display result
print('Binary value:', bin(num))
76.# Python program to convert Binary to Decimal using while loop
def BinaryDecimal(n): #user-defined function
num, dec, base = n, 0, 1
temp = num
while(temp):
digit = temp % 10
temp = int(temp / 10)
dec += digit * base
base = base * 2
return dec
# take inputs
num = int(input('Enter a binary number: '))
# display result
print('The decimal value is =', BinaryDecimal(num))
77.# Python program to convert decimal to octal
def DecimalOctal(num):
octal = [0] * 100
# counter for octal number array
i = 0
while (num != 0):
# store remainder in octal array
octal[i] = num % 8
num = int(num / 8)
i += 1
# print octal number array in reverse order
for j in range(i - 1, -1, -1):
print(octal[j], end='')
# take inputs
num = int(input('Enter a decimal number: '))
# calling function and display result
print('Octal value: ', end='')
DecimalOctal(num)
78.# Python program to convert octal to decimal
def OctalDecimal(num): #user-defined function
decimal = 0
base = 1 #Initializing base value to 1, i.e 8^0
while (num):
# Extracting last digit
last_digit = num % 10
num = int(num / 10)
decimal += last_digit * base
base = base * 8
return decimal
# take inputs
num = int(input('Enter an octal number: '))
# calling function and display result
print('The decimal value is =',OctalDecimal(num))
79.# Python program to convert Celsius to Fahrenheit
# take inputs
cel = 10
# find temprature in Fahrenheit
fahr = (cel * 1.8) + 32
# print temperature in Fahrenheit
print('%0.1f degrees Celsius is equivalent to %0.1f degrees Fahrenheit' %(cel,
fahr))
80.# Python program to convert Celsius to Kelvin
# take inputs
cel = 10
# find temprature in Kelvin
kelvin = cel + 273.15
# print temperature in Kelvin
print('%0.1f degrees Celsius is equivalent to %0.1f Kelvin' %(cel, kelvin))
PYTHON NUMBER PROGRAMS
81.# Python program to check if a number is prime or not
# take inputs
num = int(input('Enter a number: '))
count = 0
i = 2
# If number is greater than 1
while(i <= num//2):
if(num % i ==0):
count += 1
break
i += 1
# display result
if(count == 0 and num != 1):
print(num, "is a prime number")
else:
print(num, "is not a prime number")
82.# Python program to check if number is Palindrome
# take inputs
num = int(input('Enter the number : '))
# calculate reverse of number
reverse = 0
number = num
while(num != 0):
remainder = num % 10
reverse = reverse * 10 + remainder
num = int(num / 10)
# compare reverse to original number
if(number == reverse):
print(number,'is a Palindrome')
else:
print(number,'is not a Palindrome')
83.# Python program to check perfect number
# take inputs
N = int(input("Enter a number: "))
# check perfect number
sum = 0
for i in range(1,N):
if(N%i == 0):
sum = sum+i
# display result
if(sum == N):
print(N, "is a perfect number")
else:
print(N, "is not a perfect number")
84.# Python program to check perfect number using function
def perfect_numbers(N):
sum = 0
for i in range(1,N):
if(N%i == 0):
sum = sum+i
return sum
# take inputs
N = int(input("Enter a number: "))
# check perfect number
if(N == perfect_numbers(N)):
print(N, "is a perfect number")
else:
print(N, "is not a perfect number")
85.# Python program to reverse a number using for loop
# take inputs
num = '105'
# calculate reverse of number
reverse = ''
for i in range(len(num), 0, -1):
reverse += num[i-1]
# print reverse of number
print('The reverse number is =', reverse)
86.# Python program to reverse a number using for loop
# take inputs
num = input('Enter the number: ')
# calculate reverse of number
reverse = ''
for i in range(len(num), 0, -1):
reverse += num[i-1]
# print reverse of number
print('The reverse number is =', reverse)
87.# Palindrome Program in Python using for loop
# take inputs
num = '22'
# check number is palindrome or not
i=0
for i in range(len(num)):
if num[i]!=num[-1-i]:
print(num,'is not a Palindrome')
break
else:
print(num,'is a Palindrome')
break
PYTHON LIST PROGRAMS
88.# Python program to remove element from list by index
# take list
my_list = ['C', 'Java', 'Python', 'HTML', 'Javascript']
# printing original list
print('List:', my_list)
# removed index 3 item from the list
my_list.pop(3)
# print list after item deletion
print('New list:', my_list)
89.# Python program to remove item from list
# take list
my_list = ['C', 'Java', 'Python', 'HTML', 'Javascript']
# printing original list
print('List:', my_list)
# removed all item from the list
my_list.clear()
# print list after all item deletion
print('New list:', my_list)
90.# Python program to remove item from list
# take list
my_list = ['C', 'Java', 'Python', 'HTML', 'Javascript']
# printing original list
print('List:', my_list)
# removed HTML from the list
my_list.remove('HTML')
# print list after item deletion
print('New list:', my_list)
91.# Python program to delete user-defined object
# user-defined object
class My_Project:
x = 5
def func(self):
print('Know Program')
# Output
print(My_Project)
# deleting My_Project
del My_Project
# check if class exists
print(My_Project)
92.# Python program to subtract two lists
# take list
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
b = [1, 3, 4, 7, 9]
# print original list
print('list1 =', a)
print('list2 =', b)
# subtraction of list
sub = list(set(a) - set(b))
# print subtraction value
print('list1 - list2 =', sub)
93.# Python program to calculate the average of numbers in a given list
def find_Average(n):
sum_num = 0
for i in n:
# calculate sum of numbers in list
sum_num = sum_num + i
# calculate average of numbers in list
avg = sum_num / len(n)
return avg
# take list
l = [5, 3, 8, 20, 15]
# calling function and display result
print('The average of list = %0.2f' %find_Average(l))
94.# Python program to remove item from list
# take list
my_list = ['C', 'Java', 'Python', 'HTML', 'Javascript']
# printing original list
print('List:', my_list)
# removed HTML from the list
my_list.remove('HTML')
# print list after item deletion
print('New list:', my_list)
95.# Python program to duplicates item from list
# take list
my_list = ['C', 'Java', 'Python', 'Java', 'Javascript', 'Java']
# printing original list
print('List:', my_list)
# removed Java from the list
my_list.remove('Java')
# print list after item deletion
print('New list:', my_list)
96.# Python program to remove first element from list
# take list
my_list = ['C', 'Python', 'Java', 'Javascript', 'Know Program']
# printing original list
print('List:', my_list)
# removed first element using remove()
my_list.remove(my_list[0])
# print list after first item deletion
print('New list:', my_list)
97.# Python program to remove first element from list using pop
# take list
my_list = ['C', 'Python', 'Java', 'Javascript', 'Know Program']
# printing original list
print('List:', my_list)
# removed first element using pop()
my_list.pop(0)
# print list after first item deletion
print('New list:', my_list)
98.# Python program to remove last element from list
# take list
mylist = ['C', 'C++', 'Java', 'Python', 'Javascript']
# printing original list
print('The original list:', mylist)
# remove last element using list.pop()
mylist.pop()
# printing list without last element
print('The list after removing last elements:', mylist)
99.# Python program to remove last element from list using “del”
# take list
mylist = ['C', 'C++', 'Java', 'Python', 'Javascript']
# printing original list
print('The original list:', mylist)
# remove last element using del()
del(mylist[-1])
# printing list without last element
print('The list after removing last elements:', mylist)
100.# Python program to remove last element from list using slicing
# take list
mylist = ['C', 'C++', 'Java', 'Python', 'Javascript']
# printing original list
print('The original list:', mylist)
# remove last element using slicing
remove_list = mylist[:-1]
# printing list without last element
print('The list after removing last elements:', remove_list)
101.# Python program to delete all elements in list
# take list
my_list = ['C', 'Java', 'Python', 'Javascript', 'Know Program']
# printing original list
print('List:', my_list)
# removed all item from the list
my_list.clear()
# print list after item deletion
print('New list:', my_list)
102.# Python program to check for duplicates in list
# take list
my_list = [1, 3, 5, 1]
# printing original list
print('List:', my_list)
# check duplicates using set()
seen = set()
duplicate_item = {x for x in my_list if x in seen or (seen.add(x) or False)}
if duplicate_item:
print('Yes, the list contains duplicates.')
else:
print('No, the list does not contains duplicates.')
103.# Python program to find duplicate items in list
# take list
my_list = [1, 3, 7, 1, 2, 7, 5, 3, 8, 1]
# printing original list
print('List:', my_list)
# find duplicate items using set()
seen = set()
duplicate_item = [x for x in my_list if x in seen or (seen.add(x) or False)]
# printing duplicate elements
print('Duplicate Elements:', duplicate_item)
PYTHON Basic String Programs
104. # Python program to conversion ASCII to string
# take list
l = [75, 110, 111, 119, 32, 80, 114, 111, 103, 114, 97, 109]
# printing list
print("List of ASCII value =", l)
# ASCII to string using naive method
string = ""
for num in l:
string = string + chr(num)
# Printing string
print ("String:", str(string))
105. # Python program to find ASCII value of each character in
string
# take input
string = input("Enter any string: ")
# printing ascii value of each character
for i in range(len(string)):
print("The ASCII value of character %c = %d" %(string[i],
ord(string[i])))
106. # Python program to print list of alphabets
# initializing empty list
list_upper = []
list_lower = []
upper = 'A'
for c in range(0, 26):
list_upper.append(upper)
upper = chr(ord(upper) + 1)
lower = 'a'
for c in range(0, 26):
list_lower.append(lower)
lower = chr(ord(lower) + 1)
# print uppercase alphabets
print('Uppercase Alphabets: ', list_upper)
# print lowercase alphabets
print('Lowercase Alphabets: ', list_lower)
107. # Python program to check special character
# import required package
import re
# take inputs
string = input('Enter any string: ')
# special characters
special_char = re.compile('[@_!#$%^&*()<>?/\|}{~:]')
# check string contains special characters or not
if(special_char.search(string) == None):
print('String does not contain any special characters.')
else:
print('The string contains special characters.')
108. # Python program to print alphabets
import string #importing string function
# function to print all alphabets
def allAlpha():
for c in string.ascii_letters:
print(c, end = ' ')
print('')
# print alphabets
print('Alphabets:')
allAlpha()
109. Python program to concatenate string and int
string = 'Know Program'
integer = 100
print(string + str(integer))
110. # Python program to check if string is Palindrome
# take inputs
string = input('Enter the string: ')
# find reverse of string
reverse = str(string)[::-1]
# compare reverse to original string
if(reverse == string):
print(string,'is a Palindrome')
else:
print(string,'is not a Palindrome')
# Python program to swapping characters in given string
# take input
string = input('Enter any string: ')
# swapcase() function to changing case
print('Swap Case:', string.swapcase())
111. # Python program to check if two strings are equal
# first string
string1 = input('Enter first string: ')
# second string
string2 = input('Enter second string: ')
# check strings is equal or not
if(string1 == string2):
print('The strings are the same.')
else:
print('The strings are not the same.')
112. # Python program to capitalize the first letter of string
# take string
string = input('Enter any string: ')
# capitalize using capitalize() function
cap_string = string.capitalize()
# printing capitalize string
print('Capitalized String:', cap_string)
113. Python program to print vowels in a string
def printVowels(string):
# to print the vowels
for char in string:
if char in "aeiouAEIOU":
print(char, end=', ')
return char
# take input
string = input('Enter any string: ')
# calling function
printVowels(string)
# Python program to print consonants in a string
def printConsonants(string):
# to print the consonants
for char in string:
if char not in "aeiouAEIOU ":
print(char, end=', ')
return char
# take input
string = input('Enter any string: ')
# calling function
printConsonants(string)
113. # Python program to print vowels and consonants in a string
def vowelConsonant(string):
#check alphabet or not
if not string.isalpha():
return 'Neither'
#check vowel or consonant
if string.lower() in 'aeiou':
return 'Vowel'
else:
return 'Consonant'
# take input
string = input('Enter any string: ')
# calling function and display result
for ch in string:
#print vowels and consonants
print(ch,'is',vowelConsonant(ch),end=', ')
114. # Python program to separate vowels and consonants in a string
# take input
string = input('Enter any string: ')
print('Vowels: ')
for char in string:
if char in "aeiouAEIOU":
print(char, end=', ')
print('\nConsonants: ')
for char in string:
if char not in "aeiouAEIOU ":
print(char, end=', ')
115. # Python program to find vowels in a string
# take input
string = input('Enter any string: ')
# to find the vowels
vowels = [each for each in string if each in "aeiouAEIOU"]
# print number of vowels in string
print('Number of vowels in string:', len(vowels))
# print all vowels in string
print(vowels)
116. Python program to count vowels in a string
def countVowels(string):
num_vowels=0
# to count the vowels
for char in string:
if char in "aeiouAEIOU":
num_vowels = num_vowels+1
return num_vowels
# take input
string = input('Enter any string: ')
# calling function and display result
print('No of vowels =',countVowels(string))
117. # Python program to find consonants in a string
# take input
string = input('Enter any string: ')
# to find the consonants
consonant = [each for each in string if each not in "aeiouAEIOU "]
# print number of consonants in string
print('Number of consonants in string:', len(consonant))
# print all consonants in string
print(consonant)
118. # Python program to count consonant in a string
def countConsonants(string):
num_consonants = 0
# to count the consonants
for char in string:
if char not in "aeiouAEIOU ":
num_consonants += 1
return num_consonants
# take input
string = input('Enter any string: ')
# calling function and display result
print('No of consonants:',countConsonants(string))
118. # Python program to find character is vowel or consonant
# take input
ch = input('Enter any character: ')
# find vowel or constant and display result
if(ch=='A' or ch=='a' or ch=='E' or ch =='e'
or ch=='I' or ch=='i' or ch=='O'
or ch=='o' or ch=='U' or ch=='u'):
print(ch, "is a Vowel")
else:
print(ch, "is a Consonant")
119. # Python program to check if string contains vowels
def checkVowels(string): #use-defined function
# check the string contains vowels
for char in string:
if char in 'aeiouAEIOU':
return True
return False
# take inputs
string = input('Enter any String: ')
# calling function
if (checkVowels(string) == True):
print('Yes, String contains vowels.')
else:
print('No, String does not contain vowels.')
120. # Python program to check if string starts with vowel
# take inputs
string = input('Enter any String: ')
# vowel alphabet
vowel = 'aeiou'
# check string starts with vowel or consonant
if string[0].lower() in vowel:
print(string,'starts with vowel',string[0])
else:
print(string,'starts with consonant',string[0])
121. Python program to remove all vowels from string
def removeVowels(string):
vowel = 'aeiou'
#find vowel in string
for ch in string.lower():
if ch in vowel:
#remove vowels
string = string.replace(ch, '')
#print string without vowels
print(string)
# take input
string = input('Enter any string: ')
# calling function
removeVowels(string)
122. # Python Program get first character of string
# take input
string = input('Enter any string: ')
# get first character
first_char = ""
for i in range(0, 1):
first_char = first_char + string[i]
# printing first character of string
print('First character:', first_char)
123. # Python Program get last character of string
# take input
string = input('Enter any string: ')
# get last character
last_char = string[-1]
# printing last character of string
print('Last character:', last_char)
124. # Python Program get first n characters of string
# take string
string = input('Enter any string: ')
# take value of n
n = int(input('Enter n: '))
# get first n characters
first_char = ""
for i in range(0, n):
first_char = first_char + string[i]
# printing first n characters of string
print('First', n, 'character:', first_char)
125. Python program to extract number from string
# take string
string = "2 Java developer and 5 Python developer"
# print original string
print("The original string:", string)
# using str.split() + isdigit()
num = []
for i in string.split():
if i.isdigit():
num.append(int(i))
# print extract numbers
print("Extract Numbers:", num)
126. # Python program to remove character from string
# take input
string = "Python"
# print original string
print ("Original string:", string)
# remove character from string
out_string = ""
for i in range(0, len(string)):
if i != 4:
out_string = out_string + string[i]
# print string after removal
print ("New string:", out_string)
127. # Python program to remove first character from string
# take input
string = input("Enter any string: ")
# remove first character from string
out_string = ""
for i in range(1, len(string)):
out_string = out_string + string[i]
# print string after removal
print ("New string:", out_string)
128. # Python program to remove last character from string
# take input
string = input("Enter any string: ")
# remove last character from string
out_string = ""
for i in range(0, len(string)-1):
out_string = out_string + string[i]
# print string after removal
print ("New string:", out_string)
130. # Python program to remove all special characters from string
# importing RegEx module
import re
# take string
string = input('Enter any string: ')
# using regular expression to remove special characters
new_string = re.sub(r'[^a-zA-Z0-9]','',string)
# print string without special characters
print('New string:', new_string)
131. # python program to compute sum of digits in a string
# take input
string = input("Enter any string: ")
# find sum of digits
sum_digit = 0
for x in string:
if x.isdigit():
sum_digit += int(x)
# display result
print("Sum of digits =", sum_digit)
132. # Python program to convert uppercase to lowercase
#take input
string = input('Enter any string: ')
# lower() function to convert uppercase to lowercase
print('In Upper Case:', string.lower())
133. # Python program to convert lowercase to uppercase
#take input
string = input('Enter any string: ')
# upper() function to convert lowercase to uppercase
print('In Upper Case:', string.upper())
134. # Python program to count uppercase and lowercase characters
# take input
string = input('Enter any string: ')
upper, lower = 0, 0
for i in string:
#count lowercase characters
if(i.islower()):
lower = lower + 1
#count uppercase characters
elif(i.isupper()):
upper = upper + 1
# print number of lowercase characters
print('Lowercase characters:',lower)
# print number of uppercase characters
print('Uppercase characters:',upper)
135. # Python program to print uppercase letters in the string
# take input
string = input('Enter any string: ')
upper = ''
for char in string:
#check uppercase characters
if char.isupper():
upper += char
# print uppercase characters
print('Uppercase characters:', upper)
136. # Python program to reverse a string using for loop
# take inputs
string = input('Enter the string: ')
# calculate reverse of string
reverse = ''
for i in range(len(string), 0, -1):
reverse += string[i-1]
# print reverse of string
print('The reverse string is', reverse)
137. # Python program to reverse words in a string
# take inputs
string = 'Know Program'
# splitting the string into list of words
words = string.split(' ')
# reversing the split string list and join using space
reverseString = " ".join(reversed(words))
# print reverse of each word in a string
print('The reverse is', reverseString)
138. # Python program to reverse each word in a string
# take inputs
string = 'Know Program'
# splitting the string into list of words
words = string.split(' ')
# reversing each word and creating a new list of words
reverseWords = [word[::-1] for word in words]
# joining the new list of words to for a new string
reverseString = " ".join(reverseWords)
# print reverse of each word in a string
print('The reverse is', reverseString)
139. # Palindrome number in python using for loop
# take inputs
num = input('Enter the number: ')
# check number is palindrome or not
i=0
for i in range(len(num)):
if num[i]!=num[-1-i]:
print(num,'is not a Palindrome')
break
else:
print(num,'is a Palindrome')
break