Python Basic Program
Python program to print "Hello Python"
# Python program to print "Hello Python"
print ('Hello Python')
Python program to do arithmetical operations
1. # Simple Python program to understand the arithmetical operator addition
2. # Here, we are storing the first input numbers in num1
3. num1 = input('Enter first number: ')
4. # Here, we are storing the second input numbers in num2
5. num2 = input('Enter second number: ')
6. # Here, we are declaring a variable sum to store the result
7. # Here, we are using the arithmetical operator to add the two numbers
8. sum = float(num1) + float(num2)
9. # Here, we are printing the sum of the given two numbers
10. print('The sum of {0} and {1} is {2}'.format(num1, num2, sum))
Python program to find the area of a triangle
1. # Three sides of the triangle is a, b and c:
2. a = float(input('Enter first side: '))
3. b = float(input('Enter second side: '))
4. c = float(input('Enter third side: '))
5. # calculate the semi-perimeter
6. s = (a + b + c) / 2
7. # calculate the area
8. area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
9. print('The area of the triangle is %0.2f' %area)
Python program to solve quadratic equation
1. # import complex math module
2. import cmath
3. a = float(input('Enter a: '))
4. b = float(input('Enter b: '))
5. c = float(input('Enter c: '))
6.
7. # calculate the discriminant
8. d = (b**2) - (4*a*c)
9.
10. # find two solutions
11. sol1 = (-b-cmath.sqrt(d))/(2*a)
12. sol2 = (-b+cmath.sqrt(d))/(2*a)
13. print('The solution are {0} and {1}'.format(sol1,sol2))
Python program to swap two variables
1. P = int( input("Please enter value for P: "))
2. Q = int( input("Please enter value for Q: "))
3.
4. # To swap the value of two variables
5. # we will user third variable which is a temporary variable
6. temp_1 = P
7. P = Q
8. Q = temp_1
9.
10. print ("The Value of P after swapping: ", P)
11. print ("The Value of Q after swapping: ", Q)
Python Program to Generate a Random Number
1. # Importing the random module
2. import random
3. # Using random function from the random module
4. n = random.random()
5. # Printing Results
6. print("Random Number between 0 to 1:", n)
7. print("Random Number between 0 to 1:", random.random())
8. print("Random Number between 0 to 1:", random.random())
Python program to convert Kilometres to Miles
1. 1 kilometre equals 0.62137 miles.
2. Miles = kilometre * 0.62137
3. And,
4. Kilometre = Miles / 0.62137
Python program to convert Celsius to Fahrenheit
# Python Program to convert temperature in celsius to fahrenheit
# change this value for a different result
celsius = 37.5
# calculate fahrenheit
fahrenheit = (celsius * 1.8) + 32
print('%0.1f degree Celsius is equal to %0.1f degree Fahrenheit' %(celsius,fahrenheit))
Python program to display calendar
1. import calendar
2. # Enter the month and year
3. yy = int(input("Enter year: "))
4. mm = int(input("Enter month: "))
5.
6. # display the calendar
7. print(calendar.month(yy,mm))
Python Program to check if a Number is Positive, Negative
or Zero
1. # Default function to run if else condition
2. def NumberCheck(a):
3. # Checking if the number is positive
4. if a > 0:
5. print("Number given by you is Positive")
6. # Checking if the number is negative
7. elif a < 0:
8. print("Number given by you is Negative")
9. # Else the number is zero
10. else:
11. print("Number given by you is zero")
12. # Taking number from user
13. a = float(input("Enter a number as input value: "))
14. # Printing result
15. NumberCheck(a)
Python Program to Check if a Number is Odd or Even
1. num = int(input("Enter a number: "))
2. if (num % 2) == 0:
3. print("{0} is Even number".format(num))
4. else:
5. print("{0} is Odd number".format(num))
Python Program to Check Leap Year
1. # Default function to implement conditions to check leap year
2. def CheckLeap(Year):
3. # Checking if the given year is leap year
4. if((Year % 400 == 0) or
5. (Year % 100 != 0) and
6. (Year % 4 == 0)):
7. print("Given Year is a leap Year");
8. # Else it is not a leap year
9. else:
10. print ("Given Year is not a leap Year")
11. # Taking an input year from user
12. Year = int(input("Enter the number: "))
13. # Printing result
14. CheckLeap(Year)
Python Program to Check Prime Number
1. # A default function for Prime checking conditions
2. def PrimeChecker(a):
3. # Checking that given number is more than 1
4. if a > 1:
5. # Iterating over the given number with for loop
6. for j in range(2, int(a/2) + 1):
7. # If the given number is divisible or not
8. if (a % j) == 0:
9. print(a, "is not a prime number")
10. break
11. # Else it is a prime number
12. else:
13. print(a, "is a prime number")
14. # If the given number is 1
15. else:
16. print(a, "is not a prime number")
17. # Taking an input number from the user
18. a = int(input("Enter an input number:"))
19. # Printing result
20. PrimeChecker(a)
Python Program to Print all Prime Numbers in an
Interval
1. # First, we will take the input:
2. lower_value = int(input ("Please, Enter the Lowest Range Value: "))
3. upper_value = int(input ("Please, Enter the Upper Range Value: "))
4.
5. print ("The Prime Numbers in the range are: ")
6. for number in range (lower_value, upper_value + 1):
7. if number > 1:
8. for i in range (2, number):
9. if (number % i) == 0:
10. break
11. else:
12. print (number)
Python Program to Find the Factorial of a
Number
1. num = int(input("Enter a number: "))
2. factorial = 1
3. if num < 0:
4. print(" Factorial does not exist for negative numbers")
5. elif num == 0:
6. print("The factorial of 0 is 1")
7. else:
8. for i in range(1,num + 1):
9. factorial = factorial*i
10. print("The factorial of",num,"is",factorial)
Python Program to Display the Multiplication
Table
1. number = int(input ("Enter the number of which the user wants to print the multiplicatio
n table: "))
2. # We are using "for loop" to iterate the multiplication 10 times
3. print ("The Multiplication Table of: ", number)
4. for count in range(1, 11):
5. print (number, 'x', count, '=', number * count)
Python Program to Print the Fibonacci sequence
1. n_terms = int(input ("How many terms the user wants to print? "))
2. # First two terms
3. n_1 = 0
4. n_2 = 1
5. count = 0
6. # Now, we will check if the number of terms is valid or not
7. if n_terms <= 0:
8. print ("Please enter a positive integer, the given number is not valid")
9. # if there is only one term, it will return n_1
10. elif n_terms == 1:
11. print ("The Fibonacci sequence of the numbers up to", n_terms, ": ")
12. print(n_1)
13. # Then we will generate Fibonacci sequence of number
14. else:
15. print ("The fibonacci sequence of the numbers is:")
16. while count < n_terms:
17. print(n_1)
18. nth = n_1 + n_2
19. # At last, we will update values
20. n_1 = n_2
21. n_2 = nth
22. count += 1
Python Program to check Armstrong Number
1. def power_1(A, B):
2.
3. if B == 0:
4. return 1
5. if B % 2 == 0:
6. return power_1(A, B // 2) * power(A, B // 2)
7.
8. return A * power(A, B // 2) * power(A, B // 2)
9.
10. # Function for calculating "order of the number"
11. def order_1(A):
12.
13. # Variable for storing the number
14. N=0
15. while (A != 0):
16. N=N+1
17. A = A // 10
18.
19. return N
20.
21. # Function for checking if the given number is Armstrong number or not
22. def is_Armstrong(A):
23.
24. N = order_1(A)
25. temp_1 = A
26. sum_1 = 0
27.
28. while (temp_1 != 0):
29. R_1 = temp_1 % 10
30. sum_1 = sum_1 + power_1(R_1, N)
31. temp_1 = temp_1 // 10
32.
33. # If the above condition is satisfied, it will return the result
34. return (sum_1 == A)
35.
36. # Driver code
37. A = int(input("Please enter the number to be checked: "))
38. print(is_Armstrong(A))
Python Armstrong Number
1. lower = int(input("Enter lower range: "))
2. upper = int(input("Enter upper range: "))
3. for num in range(lower,upper + 1):
4. sum = 0
5. temp = num
6. while temp > 0:
7. digit = temp % 10
8. sum += digit ** 3
9. temp //= 10
10. if num == sum:
11. print(num)
Python Program to Find the Sum of Natural
Numbers
1. num = int(input("Enter a number: "))
2.
3. if num < 0:
4. print("Enter a positive number")
5. else:
6. sum = 0
7. # use while loop to iterate un till zero
8. while(num > 0):
9. sum += num
10. num -= 1
11. print("The sum is",sum)
Python function Programs
Python Program to Find LCM
1. # defining a function to calculate LCM
2. def calculate_lcm(x, y):
3. # selecting the greater number
4. if x > y:
5. greater = x
6. else:
7. greater = y
8. while(True):
9. if((greater % x == 0) and (greater % y == 0)):
10. lcm = greater
11. break
12. greater += 1
13. return lcm
14.
15. # taking input from users
16. num1 = int(input("Enter first number: "))
17. num2 = int(input("Enter second number: "))
18. # printing the result for the users
19. print("The L.C.M. of", num1,"and", num2,"is", calculate_lcm(num1, num2))
Python Program to Find HCF
1. # defining a function to calculate HCF
2. def calculate_hcf(x, y):
3. # selecting the smaller number
4. if x > y:
5. smaller = y
6. else:
7. smaller = x
8. for i in range(1,smaller + 1):
9. if((x % i == 0) and (y % i == 0)):
10. hcf = i
11. return hcf
12.
13. # taking input from users
14. num1 = int(input("Enter first number: "))
15. num2 = int(input("Enter second number: "))
16. # printing the result for the users
17. print("The H.C.F. of", num1,"and", num2,"is", calculate_hcf(num1, num2))
Python Program to Convert Decimal to Binary,
Octal and Hexadecimal
1. # First, we will define the function to convert decimal to binary
2. def decimal_into_binary(decimal_1):
3. decimal = int(decimal_1)
4.
5. # then, print the equivalent decimal
6. print ("The given decimal number", decimal, "in Binary number is: ", bin(decimal))
7. # we will define the function to convert decimal to octal
8. def decimal_into_octal(decimal_1):
9. decimal = int(decimal_1)
10.
11. # Then, print the equivalent decimal
12. print ("The given decimal number", decimal, "in Octal number is: ", oct(decimal))
13. # we will define the function to convert decimal to hexadecimal
14. def decimal_into_hexadecimal(decimal_1):
15. decimal = int(decimal_1)
16.
17. # Then, print the equivalent decimal
18. print ("The given decimal number", decimal, " in Hexadecimal number is: ", hex(decim
al))
19.
20. # Driver program
21. decimal_1 = int (input (" Enter the Decimal Number: "))
22. decimal_into_binary(decimal_1)
23. decimal_into_octal(decimal_1)
24. decimal_into_hexadecimal(decimal_1)
Python Program To Find ASCII value of a
character
1. print ("Please enter the String: ", end = "")
2. string = input()
3. string_length = len(string)
4. for K in string:
5. ASCII = ord(K)
6. print (K, "\t", ASCII)
Python Program to Make a Simple Calculator
1. def add(P, Q):
2. # This function is used for adding two numbers
3. return P + Q
4. def subtract(P, Q):
5. # This function is used for subtracting two numbers
6. return P - Q
7. def multiply(P, Q):
8. # This function is used for multiplying two numbers
9. return P * Q
10. def divide(P, Q):
11. # This function is used for dividing two numbers
12. return P / Q
13. # Now we will take inputs from the user
14. print ("Please select the operation.")
15. print ("a. Add")
16. print ("b. Subtract")
17. print ("c. Multiply")
18. print ("d. Divide")
19.
20. choice = input("Please enter choice (a/ b/ c/ d): ")
21.
22. num_1 = int (input ("Please enter the first number: "))
23. num_2 = int (input ("Please enter the second number: "))
24.
25. if choice == 'a':
26. print (num_1, " + ", num_2, " = ", add(num_1, num_2))
27.
28. elif choice == 'b':
29. print (num_1, " - ", num_2, " = ", subtract(num_1, num_2))
30.
31. elif choice == 'c':
32. print (num1, " * ", num2, " = ", multiply(num1, num2))
33. elif choice == 'd':
34. print (num_1, " / ", num_2, " = ", divide(num_1, num_2))
35. else:
36. print ("This is an invalid input")
Python Function to Display Calendar
1. # First import the calendar module
2. import calendar
3. # ask of month and year
4. yy = int(input("Enter year: "))
5. mm = int(input("Enter month: "))
6. # display the calendar
7. print(calendar.month(yy,mm))
Python Program to Display Fibonacci Sequence
Using Recursion
1. def recur_fibo(n):
2. if n <= 1:
3. return n
4. else:
5. return(recur_fibo(n-1) + recur_fibo(n-2))
6. # take input from the user
7. nterms = int(input("How many terms? "))
8. # check if the number of terms is valid
9. if nterms <= 0:
10. print("Plese enter a positive integer")
11. else:
12. print("Fibonacci sequence:")
13. for i in range(nterms):
14. print(recur_fibo(i))
Python Program to Find Factorial of Number
Using Recursion
1. def recur_factorial(n):
2. if n == 1:
3. return n
4. else:
5. return n*recur_factorial(n-1)
6. # take input from the user
7. num = int(input("Enter a number: "))
8. # check is the number is negative
9. if num < 0:
10. print("Sorry, factorial does not exist for negative numbers")
11. elif num == 0:
12. print("The factorial of 0 is 1")
13. else:
14. print("The factorial of",num,"is",recur_factorial(num))
Python Array Programs
Python program to copy all elements of one array
into another array
1. #Initialize array
2. arr1 = [1, 2, 3, 4, 5];
3.
4. #Create another array arr2 with size of arr1
5. arr2 = [None] * len(arr1);
6.
7. #Copying all elements of one array into another
8. for i in range(0, len(arr1)):
9. arr2[i] = arr1[i];
10.
11. #Displaying elements of array arr1
12. print("Elements of original array: ");
13. for i in range(0, len(arr1)):
14. print(arr1[i]),
15.
16. print();
17.
18. #Displaying elements of array arr2
19. print("Elements of new array: ");
20. for i in range(0, len(arr2)):
21. print(arr2[i]),
Python program to find the frequency of each
element in the array
1. #Initialize array
2. arr = [1, 2, 8, 3, 2, 2, 2, 5, 1];
3. #Array fr will store frequencies of element
4. fr = [None] * len(arr);
5. visited = -1;
6.
7. for i in range(0, len(arr)):
8. count = 1;
9. for j in range(i+1, len(arr)):
10. if(arr[i] == arr[j]):
11. count = count + 1;
12. #To avoid counting same element again
13. fr[j] = visited;
14.
15. if(fr[i] != visited):
16. fr[i] = count;
17.
18. #Displays the frequency of each element present in array
19. print("---------------------");
20. print(" Element | Frequency");
21. print("---------------------");
22. for i in range(0, len(fr)):
23. if(fr[i] != visited):
24. print(" " + str(arr[i]) + " | " + str(fr[i]));
25. print("---------------------");
Python program to left rotate the elements of an
array
1. #Initialize array
2. arr = [1, 2, 3, 4, 5];
3. #n determine the number of times an array should be rotated
4. n = 3;
5.
6. #Displays original array
7. print("Original array: ");
8. for i in range(0, len(arr)):
9. print(arr[i]),
10.
11. #Rotate the given array by n times toward left
12. for i in range(0, n):
13. #Stores the first element of the array
14. first = arr[0];
15.
16. for j in range(0, len(arr)-1):
17. #Shift element of array by one
18. arr[j] = arr[j+1];
19.
20. #First element of array will be added to the end
21. arr[len(arr)-1] = first;
22.
23. print();
24.
25. #Displays resulting array after rotation
26. print("Array after left rotation: ");
27. for i in range(0, len(arr)):
28. print(arr[i]),
Python List Programs
How to append element in the list
1. names = ["Joseph", "Peter", "Cook", "Tim"]
2.
3. print('Current names List is:', names)
4.
5. new_name = input("Please enter a name:\n")
6. names.append(new_name) # Using the append() function
7.
8. print('Updated name List is:', names)
How to compare two lists in Python
1. import collections
2.
3. list1 = [10, 20, 30, 40, 50, 60]
4. list2 = [10, 20, 30, 50, 40, 70]
5. list3 = [50, 10, 30, 20, 60, 40]
6.
7. # Sorting the list
8. list1.sort()
9. list2.sort()
10. list3.sort()
11.
12.
13. if list1 == list2:
14. print("The list1 and list2 are the same")
15. else:
16. print("The list1 and list3 are not the same")
17.
18. if list1 == list3:
19. print("The list1 and list2 are not the same")
20. else:
21. print("The list1 and list2 are not the same")
How to convert list to dictionary in Python
1. Input : ['Name', 'Abhinay', 'age', 25, 'Marks', 90]
2. Output : {'Name', 'Abhinay', 'age', 25, 'Marks', 90}
3.
4. Input : ['a', 10, 'b', 42, 'c', 86]
5. Output : {'a', 10, 'b', 42, 'c', 86}
How to Remove an Element from a List in Python
1. # Python program to remove an element from a list using the remove() function
2.
3. my_list = ['Javatpoint', 'Python', 'Tutorial', 'List',
4. 'Element', 'Removal']
5. print("Initial List is :", my_list)
6.
7. # through remove() deleting 'Python' from the my_list
8. my_list.remove('Python')
9. print( "After using the function :", my_list )
How to add two lists in Python
1. List1 = ["Rose", "Lotus", 24, "Gold", "USA" ] # define the list
2. # define the Department Dept2 list
3. Dept2 = ["Web Designing", 40, 20]
4. # define the HR_CS
5. HR_CS = [58, "Ms Wiley"]
6. List2 = [1, 2, 4, 5, 6] # integer list
7. print (" Display the List1", List1)
8. print (" Display the List2", List2)
9. print (" Display the Department List", Dept2)
10. print (" Display the CS Department ", HR_CS)
How to convert List to Set?
1. # Creating a set of eight elements
2. myset = {"Apple", "Mango", "Banana", "Orange", "Guava", "Pineapple", "Strawberry", "Gr
apes"}
3. print(myset)
How to Convert Python List to String
1. # Python program to convert a list to a string by using the join() method
2.
3. # Creating a list with elements of string data type
4. a_list = ["Python", "Convert", "List", "String", "Method"]
5.
6. # Converting to string
7. string = " ".join( a_list ) # this is read as join elements of a_list with a separator (" ")
8.
9. # Printing the string
10. print (string)
11. print (type(string))
Python Dictionary Programs
How to Create a Dictionary in Python
1. # Initializing a dictionary with some elements
2. Dictionary = {1: 'Javatpoint', 2: 'Python', 3: 'Dictionary'}
3. print("\nDictionary created using curly braces: ")
4. print(Dictionary)
5. # Creating a Dictionary with keys of different data types
6. Dictionary = {'Website': 'Javatpoint', 3: [2, 3, 5, 'Dictionary']}
7. print("\nDictionary with keys of multiple data type: ")
8. print(Dictionary)
How to convert list to dictionary in Python
1. Input : ['Name', 'Abhinay', 'age', 25, 'Marks', 90]
2. Output : {'Name', 'Abhinay', 'age', 25, 'Marks', 90}
3.
4. Input : ['a', 10, 'b', 42, 'c', 86]
5. Output : {'a', 10, 'b', 42, 'c', 86}
How to sort a dictionary in Python
1. names = {1:'Alice' ,2:'John' ,4:'Peter' ,3:'Andrew' ,6:'Ruffalo' ,5:'Chris' }
2. #print a sorted list of the keys
3. print(sorted(names.keys()))
4. #print the sorted list with items.
5. print(sorted(names.items()))
Merge two Dictionaries in Python
1. dict1 = { 'Alexandra' : 27, # given the first dictionary in key-value pairs
2. 'Shelina Gomez' : 22,
3. 'James' : 29,
4. 'Peterson' : 30
5. }
6. dict2 = {
7. 'Jasmine' : 19, # given the second dictionary in key-value pairs
8. 'Maria' : 26,
9. 'Helena' : 30
10. }
11. print("Before merging the two dictionary ")
12. print("Dictionary No. 1 is : ", dict1) # print the dict1
13. print("Dictionary No. 1 is : ", dict2) # print the dict2
14.
15. dict3 = dict1.copy() # Copy the dict1 into the dict3 using copy() method
16.
17. for key, value in dict2.items(): # use for loop to iterate dict2 into the dict3 dictionary
18. dict3[key] = value
19.
20. print("After merging of the two Dictionary ")
21. print(dict3) # print the merge dictionary