Python Programs for Practice
Welcome to our section dedicated to the Python programming language. You will find a set of information related to this language (course support, code examples, …).
Here is a small examples of python programming language.
How to Print “Hello World!” in Python
Python 3 Code:
1 2 3 4 5 |
# This program prints Hello, world! print('Hello, world!') |
Output:
How to Add Two Variables in Python
Python 3 Code:
1 2 3 4 5 6 7 8 9 |
# This program adds two numbers num1 = 5.5 num2 = 1.15 # Add two numbers sum = float(num1) + float(num2) # Display the sum print('The sum of {0} and {1} is {2}'.format(num1, num2, sum)) |
Output:
How to Find the Square Root in Python
Python 3 Code:
1 2 3 4 5 6 7 8 9 |
# Python Program to calculate the square root #to take the input from the user num = float(input('Enter a number: ')) num_sqrt = num ** 0.5 print('The square root of %0.3f is %0.3f'%(num ,num_sqrt)) |
Output:
How to Calculate the Area of a Triangle in Python
Python 3 Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Python Program to find the area of triangle # to take inputs from the user a = float(input('Enter first side: ')) b = float(input('Enter second side: ')) c = float(input('Enter third side: ')) # calculate the semi-perimeter s = (a + b + c) / 2 # calculate the area area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 print('The area of the triangle is %0.2f' %area) |
Output:
How to Calculate the Area of a Circle in Python
Code:
1 2 3 4 5 6 7 8 9 10 11 |
# Python program to find Area of a circle def findArea(r): PI = 3.142 return PI * (r*r); # Driver method num=float(input("Enter r value:")) print("Area is %.6f" % findArea(num)); |
Output:
How to Solve Quadratic Equation in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# Solve the quadratic equation ax**2 + bx + c = 0 # import complex math module import cmath # To take coefficient input from the users a = float(input('Enter a: ')) b = float(input('Enter b: ')) c = float(input('Enter c: ')) # calculate the discriminant d = (b**2) - (4*a*c) # find two solutions sol1 = (-b-cmath.sqrt(d))/(2*a) sol2 = (-b+cmath.sqrt(d))/(2*a) print('The solution are {0} and {1}'.format(sol1,sol2)) |
Output:
How to Swap Two Variables in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Python program to swap two variables # To take input from the user x = input('Enter value of x: ') y = input('Enter value of y: ') # create a temporary variable and swap the values temp = x x = y y = temp print('The value of x after swapping: {}'.format(x)) print('The value of y after swapping: {}'.format(y)) |
Output:
How to Generate a Random Number in Python
1 2 3 4 5 6 7 8 |
# Program to generate a random number between 0 and 100 # import the random module import random print(random.randint(0,100)) |
Output:
How to Convert Kilometers to Miles in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 |
kilometers = 10 # To take kilometers from the user kilometers = float(input("Enter value in kilometers")) # conversion factor conv_fac = 0.621371 # calculate miles miles = kilometers * conv_fac print('%0.3f kilometers is equal to %0.3f miles' %(kilometers,miles)) |
How to Convert Celsius To Fahrenheit in Python
1 2 3 4 5 6 7 8 9 10 |
# Python Program to convert temperature in celsius to fahrenheit # To take celsius from the user celsius= float(input("Enter value in celsius")) # calculate fahrenheit fahrenheit = (celsius * 1.8) + 32 print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit)) |
How to Find the Sum of Numbers in a List in Python
Example Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# Python 3 code to find sum # of elements in given array def _sum(arr,n): # return sum using sum # inbuilt sum() function return(sum(arr)) # driver function arr=[] # input values to list arr = [120, 30, 24, 5] # calculating length of array n = len(arr) ans = _sum(arr,n) # display sum print ('Sum of the array is ',ans) |
Output:
How to to Check if a Number is Positive, Negative or 0 in Python
1 2 3 4 5 6 7 8 9 |
num = float(input("Enter a number: ")) if num > 0: print("Positive number") elif num == 0: print("Zero") else: print("Negative number") |
How to Check if a Number is Odd or Even in Python
1 2 3 4 5 6 7 8 9 10 |
# Python program to check if the input number is odd or even. # A number is even if division by 2 give a remainder of 0. # If remainder is 1, it is odd number. num = int(input("Enter a number: ")) if (num % 2) == 0: print("{0} is Even".format(num)) else: print("{0} is Odd".format(num)) |
How to Check Leap Year in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Python program to check if the input year is a leap year or not year = int(input("Enter a year: ")) if (year % 4) == 0: if (year % 100) == 0: if (year % 400) == 0: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) else: print("{0} is a leap year".format(year)) else: print("{0} is not a leap year".format(year)) |
How to Find the Largest Among Three Numbers in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# Python program to find the largest number among the three input numbers # change the values of num1, num2 and num3 for a different result num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) num3 = float(input("Enter third number: ")) if (num1 >= num2) and (num1 >= num3): largest = num1 elif (num2 >= num1) and (num2 >= num3): largest = num2 else: largest = num3 print("The largest number between",num1,",",num2,"and",num3,"is",largest) |
How to Check Prime Number in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
# Python program to check if the input number is prime or not num = int(input("Enter a number: ")) # prime numbers are greater than 1 if num > 1: # check for factors for i in range(2,num): if (num % i) == 0: print(num,"is not a prime number") print(i,"times",num//i,"is",num) break else: print(num,"is a prime number") # if input number is less than # or equal to 1, it is not prime else: print(num,"is not a prime number") |
How to Print all Prime Numbers in an Interval in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# Python program to display all the prime numbers within an interval # change the values of lower and upper for a different result lower = int(input("Enter lower range: ")) upper = int(input("Enter upper range: ")) print("Prime numbers between",lower,"and",upper,"are:") for num in range(lower,upper + 1): # prime numbers are greater than 1 if num > 1: for i in range(2,num): if (num % i) == 0: break else: print(num) |
How to Find the Factorial of a Number in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
# Python program to find the factorial of a number provided by the user. num = int(input("Enter a number: ")) factorial = 1 # check if the number is negative, positive or zero if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: for i in range(1,num + 1): factorial = factorial*i print("The factorial of",num,"is",factorial) |
How to Display the multiplication Table in Python
1 2 3 4 5 6 7 8 |
# To take input from the user num = int(input("Display multiplication table of? ")) # use for loop to iterate 10 times for i in range(1, 11): print(num,'x',i,'=',num*i) |
How to Print the Fibonacci sequence in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# Program to display the Fibonacci sequence up to n-th term where n is provided by the user #take input from the user nterms = int(input("How many terms? ")) # first two terms n1 = 0 n2 = 1 count = 0 # check if the number of terms is valid if nterms <= 0: print("Please enter a positive integer") elif nterms == 1: print("Fibonacci sequence upto",nterms,":") print(n1) else: print("Fibonacci sequence upto",nterms,":") while count < nterms: print(n1,end=' , ') nth = n1 + n2 # update values n1 = n2 n2 = nth count += 1 |
How to Check Armstrong Number in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
# Python program to check if the number provided by the user is an Armstrong number or not # take input from the user num = int(input("Enter a number: ")) # initialize sum sum = 0 # find the sum of the cube of each digit temp = num while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 # display the result if num == sum: print(num,"is an Armstrong number") else: print(num,"is not an Armstrong number") |
How to Find Armstrong Number in an Interval in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
# Program to check Armstrong numbers in certain interval # To take input from the user lower = int(input("Enter lower range: ")) upper = int(input("Enter upper range: ")) for num in range(lower, upper + 1): # order of number order = len(str(num)) # initialize sum sum = 0 # find the sum of the cube of each digit temp = num while temp > 0: digit = temp % 10 sum += digit ** order temp //= 10 if num == sum: print(num) |
How to Find the Sum of Natural Numbers in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
# Python program to find the sum of natural numbers up to n where n is provided by user #to take input from the user num = int(input("Enter a number: ")) if num < 0: print("Enter a positive number") else: sum = 0 # use while loop to iterate un till zero while(num > 0): sum += num num -= 1 print("The sum is",sum) |
How to Display Powers of 2 Using Anonymous Function in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Python Program to display the powers of 2 using anonymous function #to take number of terms from user terms = int(input("How many terms? ")) # use anonymous function result = list(map(lambda x: 2 ** x, range(terms))) # display the result print("The total terms is:",terms) for i in range(terms): print("2 raised to power",i,"is",result[i]) |
How to Find Numbers Divisible by Another Number in Python
1 2 3 4 5 6 7 8 9 10 11 12 |
# Python Program to find numbers divisible by fifteen from a list using anonymous function # Take a list of numbers my_list = [300, 45, 65, 12, 77, 145, 5,] # use anonymous function to filter result = list(filter(lambda x: (x % 15 == 0), my_list)) # display the result print("Numbers divisible by 13 are",result) |
How to Convert Decimal to Binary, Octal and Hexadecimal in Python
1 2 3 4 5 6 7 8 9 10 11 |
# Python program to convert decimal number into binary, octal and hexadecimal number system # Change this line for a different result dec = int(input("Enter a decimal number ")) print("The decimal value of",dec,"is:") print(bin(dec),"in binary.") print(oct(dec),"in octal.") print(hex(dec),"in hexadecimal.") |
How to Find ASCII Value of Character in Python
1 2 3 4 5 6 7 8 |
# Program to find the ASCII value of the given character #to take character from user c = input("Enter a character: ") print("The ASCII value of '" + c + "' is",ord(c)) |
How to Find HCF or GCD in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# Python program to find the H.C.F of two input number # define a function def computeHCF(x, y): # 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)): hcf = i return hcf # take input from the user num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2)) |
How to Find LCM in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
# Python Program to find the L.C.M. of two input number # define a function def lcm(x, y): """This function takes two integers and returns the L.C.M.""" # choose the greater number if x > y: greater = x else: greater = y while(True): if((greater % x == 0) and (greater % y == 0)): lcm = greater break greater += 1 return lcm #to take input from the user num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) print("The L.C.M. of", num1,"and", num2,"is", lcm(num1, num2)) |
How to Find Factors of Number in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# Python Program to find the factors of a number # define a function def print_factors(x): # This function takes a number and prints the factors print("The factors of",x,"are:") for i in range(1, x + 1): if x % i == 0: print(i) #to take input from the user num = int(input("Enter a number: ")) print_factors(num) |
How to Make a Simple Calculator in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 |
# Program make a simple calculator that can add, subtract, multiply and divide using functions # This function adds two numbers def add(x, y): return x + y # This function subtracts two numbers def subtract(x, y): return x - y # This function multiplies two numbers def multiply(x, y): return x * y # This function divides two numbers def divide(x, y): return x / y print("Select operation.") print("1.Add") print("2.Subtract") print("3.Multiply") print("4.Divide") # Take input from the user choice = input("Enter choice(1/2/3/4):") num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) if choice == '1': print(num1,"+",num2,"=", add(num1,num2)) elif choice == '2': print(num1,"-",num2,"=", subtract(num1,num2)) elif choice == '3': print(num1,"*",num2,"=", multiply(num1,num2)) elif choice == '4': print(num1,"/",num2,"=", divide(num1,num2)) else: print("Invalid input") |
How to Display Calendar in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# Python program to display calendar of given month of the year # import module import calendar # To ask month and year from the user yy = int(input("Enter year: ")) mm = int(input("Enter month: ")) # display the calendar print(calendar.month(yy, mm)) |
How to Display Fibonacci Sequence Using Recursion in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# Python program to display the Fibonacci sequence up to n-th term using recursive functions def recur_fibo(n): """Recursive function to print Fibonacci sequence""" if n <= 1: return n else: return(recur_fibo(n-1) + recur_fibo(n-2)) #to take input from the user nterms = int(input("How many terms? ")) # check if the number of terms is valid if nterms <= 0: print("Plese enter a positive integer") else: print("Fibonacci sequence:") for i in range(nterms): print(recur_fibo(i)) |
How to Find Sum of Natural Numbers Using Recursion in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# Python program to find the sum of natural numbers up to n using recursive function def recur_sum(n): """Function to return the sum of natural numbers using recursion""" if n <= 1: return n else: return n + recur_sum(n-1) #to take input from the user num = int(input("Enter a number: ")) if num < 0: print("Enter a positive number") else: print("The sum is",recur_sum(num)) |
How to Find Factorial of Number Using Recursion in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# Python program to find the factorial of a number using recursion def recur_factorial(n): """Function to return the factorial of a number using recursion""" if n == 1: return n else: return n*recur_factorial(n-1) #to take input from the user num = int(input("Enter a number: ")) # check is the number is negative if num < 0: print("Sorry, factorial does not exist for negative numbers") elif num == 0: print("The factorial of 0 is 1") else: print("The factorial of",num,"is",recur_factorial(num)) |
How to Convert Decimal to Binary Using Recursion in Python
1 2 3 4 5 6 7 8 9 10 11 12 |
def convertToBinary(n): # Function to print binary number for the input decimal using recursion if n > 1: convertToBinary(n//2) print(n % 2,end = '') # decimal number dec = int(input("Enter a number:")) convertToBinary(dec) |
How to Add Two Matrices in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
# Program to add two matrices using nested loop X = [[5, 7, 13], [41, 5, 16], [47, 5, 19]] Y = [[5 ,5 ,1], [6 ,4 ,3], [4 ,4 ,9]] result = [[0,0,0], [0,0,0], [0,0,0]] # iterate through rows for i in range(len(X)): # iterate through columns for j in range(len(X[0])): result[i][j] = X[i][j] + Y[i][j] for r in result: print(r) |
How to Transpose a Matrix in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# Program to transpose a matrix using nested loop X = [[12,7], [42 ,5], [32 ,8]] result = [[0,0,0], [0,0,0]] # iterate through rows for i in range(len(X)): # iterate through columns for j in range(len(X[0])): result[j][i] = X[i][j] for r in result: print(r) |
How to Multiply Two Matrices in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# Program to multiply two matrices using nested loops # 3x3 matrix X = [[12,7,3], [4 ,5,6], [7 ,8,9]] # 3x4 matrix Y = [[5,8,1,2], [6,7,3,0], [4,5,9,1]] # result is 3x4 result = [[0,0,0,0], [0,0,0,0], [0,0,0,0]] # iterate through rows of X for i in range(len(X)): # iterate through columns of Y for j in range(len(Y[0])): # iterate through rows of Y for k in range(len(Y)): result[i][j] += X[i][k] * Y[k][j] for r in result: print(r) |
How to Check Whether a String is Palindrome or Not in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# Program to check if a string # is palindrome or not # change this value for a different output my_str = 'ababa' # make it suitable for caseless comparison my_str = my_str.casefold() # reverse the string rev_str = reversed(my_str) # check if the string is equal to its reverse if list(my_str) == list(rev_str): print(my_str," is palindrome") else: print(my_str," is not palindrome") |
How to Remove Punctuations From a String in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
# define punctuation punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~''' # To take input from the user my_str = input("Enter a string: ") # remove punctuation from the string no_punct = "" for char in my_str: if char not in punctuations: no_punct = no_punct + char # display the unpunctuated string print(no_punct) |
How to Sort Words in Alphabetic Order in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# Program to sort alphabetically the words form a string provided by the user #to take input from the user my_str = input("Enter a string: ") # breakdown the string into a list of words words = my_str.split() # sort the list words.sort() # display the sorted words print("The sorted words are:") for word in words: print(word) |
How to Illustrate Different Set Operations in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
# Program to perform different set operations like in mathematics # define three sets E = {0, 2, 4, 6, 8}; N = {1, 2, 3, 4, 5}; # set union print("Union of E and N is",E | N) # set intersection print("Intersection of E and N is",E & N) # set difference print("Difference of E and N is",E - N) # set symmetric difference print("Symmetric difference of E and N is",E ^ N) |
How to Count the Number of Each Vowel in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# Program to count the number of each vowel in a string # string of vowels vowels = 'aeiou' #to take input from the user ip_str = input("Enter a string: ") # make it suitable for caseless comparisions ip_str = ip_str.casefold() # make a dictionary with each vowel a key and value 0 count = {}.fromkeys(vowels,0) # count the vowels for char in ip_str: if char in count: count[char] += 1 print(count) |