ADVERTISEMENT

ADVERTISEMENT

Top 50 Python Programs

hello_world.py

                        # Python program to print "Hello, World!"
print("Hello, World!")                    

Last Modified: January 11, 2025 23:35:26

swap_two_numbers.py

                        # Program to swap two numbers

a = 5
b = 10

# Before swapping
print("Before swapping:")
print("a =", a)
print("b =", b)

# Swapping
a, b = b, a

# After swapping
print("\nAfter swapping:")
print("a =", a)
print("b =", b)                    

Last Modified: January 12, 2025 00:06:45

check_prime.py

                        # Program to check if a number is prime

def is_prime(num):
    if num < 2:
        return False
    for i in range(2, num):
        if num % i == 0:
            return False
    return True

num = int(input("Enter a number: "))
if is_prime(num):
    print(f"{num} is a prime number.")
else:
    print(f"{num} is not a prime number.")                    

Last Modified: January 12, 2025 00:07:17

largest_of_three.py

                        # Program to find the largest of three numbers

a = float(input("Enter first number: "))
b = float(input("Enter second number: "))
c = float(input("Enter third number: "))

if a >= b and a >= c:
    largest = a
elif b >= a and b >= c:
    largest = b
else:
    largest = c

print(f"The largest number is {largest}")                    

Last Modified: January 12, 2025 00:07:39

odd_or_even.py

                        # Program to check if a number is odd or even

num = int(input("Enter a number: "))

if num % 2 == 0:
    print(f"{num} is an even number.")
else:
    print(f"{num} is an odd number.")                    

Last Modified: January 12, 2025 00:07:57

armstrong_number.py

                        # Program to check if a number is an Armstrong number
num = int(input("Enter a number: "))
sum = 0
temp = num
order = len(str(num))

while temp > 0:
    digit = temp % 10
    sum += digit ** order
    temp //= 10

if num == sum:
    print(f"{num} is an Armstrong number.")
else:
    print(f"{num} is not an Armstrong number.")                    

Last Modified: January 12, 2025 07:09:13

factorial.py

                        # Program to find the factorial of a number
num = int(input("Enter a number: "))
factorial = 1

for i in range(1, num + 1):
    factorial *= i

print(f"The factorial of {num} is {factorial}.")                    

Last Modified: January 12, 2025 07:09:25

fibonacci_sequence.py

                        # Program to generate Fibonacci sequence
n_terms = int(input("Enter the number of terms: "))
a, b = 0, 1
count = 0

if n_terms <= 0:
    print("Please enter a positive integer.")
elif n_terms == 1:
    print("Fibonacci sequence upto 1 term:")
    print(a)
else:
    print("Fibonacci sequence:")
    while count < n_terms:
        print(a)
        nth = a + b
        a = b
        b = nth
        count += 1                    

Last Modified: January 12, 2025 07:09:39

palindrome.py

                        # Program to check if a number is a palindrome
num = int(input("Enter a number: "))
reverse = 0
temp = num

while temp > 0:
    digit = temp % 10
    reverse = reverse * 10 + digit
    temp //= 10

if num == reverse:
    print(f"{num} is a palindrome.")
else:
    print(f"{num} is not a palindrome.")                    

Last Modified: January 12, 2025 07:09:56

count_vowels.py

                        # Program to count vowels in a string
string = input("Enter a string: ")
vowels = "aeiouAEIOU"
count = 0

for char in string:
    if char in vowels:
        count += 1

print(f"Number of vowels in the string: {count}")                    

Last Modified: January 12, 2025 07:10:09

sum_of_digits.py

                        # Program to find the sum of digits of a number
num = int(input("Enter a number: "))
sum_digits = 0

while num > 0:
    sum_digits += num % 10
    num //= 10

print(f"Sum of digits: {sum_digits}")                    

Last Modified: January 12, 2025 07:10:27

count_words.py

                        # Program to count words in a string
string = input("Enter a string: ")
words = string.split()
print(f"Number of words: {len(words)}")                    

Last Modified: January 12, 2025 07:10:41

factorial_recursive.py

                        # Program to find the factorial of a number using recursion
def factorial(n):
    if n == 0 or n == 1:
        return 1
    else:
        return n * factorial(n - 1)

num = int(input("Enter a number: "))
print(f"The factorial of {num} is {factorial(num)}.")                    

Last Modified: January 12, 2025 07:10:58

reverse_string.py

                        # Program to reverse a string
string = input("Enter a string: ")
reversed_string = string[::-1]
print(f"Reversed string: {reversed_string}")                    

Last Modified: January 12, 2025 07:11:14

leap_year.py

                        # Program to check if a year is a leap year
year = int(input("Enter a year: "))

if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
    print(f"{year} is a leap year.")
else:
    print(f"{year} is not a leap year.")                    

Last Modified: January 12, 2025 07:11:26

gcd.py

                        # Program to find the greatest common divisor (GCD) of two numbers
def gcd(a, b):
    while b:
        a, b = b, a % b
    return a

num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print(f"The GCD of {num1} and {num2} is {gcd(num1, num2)}.")                    

Last Modified: January 12, 2025 07:11:38

lcm.py

                        # Program to find the least common multiple (LCM) of two numbers
def lcm(a, b):
    return abs(a * b) // gcd(a, b)

num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print(f"The LCM of {num1} and {num2} is {lcm(num1, num2)}.")                    

Last Modified: January 12, 2025 07:11:52

bubble_sort.py

                        # Program to implement bubble sort
def bubble_sort(arr):
    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]

arr = list(map(int, input("Enter the elements separated by space: ").split()))
bubble_sort(arr)
print("Sorted array:", arr)                    

Last Modified: January 12, 2025 07:12:08

insertion_sort.py

                        # Program to implement insertion sort
def insertion_sort(arr):
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1
        while j >= 0 and key < arr[j]:
            arr[j + 1] = arr[j]
            j -= 1
        arr[j + 1] = key

arr = list(map(int, input("Enter the elements separated by space: ").split()))
insertion_sort(arr)
print("Sorted array:", arr)                    

Last Modified: January 12, 2025 07:12:20

merge_sort.py

                        # Program to implement merge sort
def merge_sort(arr):
    if len(arr) > 1:
        mid = len(arr) // 2
        left = arr[:mid]
        right = arr[mid:]

        merge_sort(left)
        merge_sort(right)

        i = j = k = 0

        while i < len(left) and j < len(right):
            if left[i] < right[j]:
                arr[k] = left[i]
                i += 1
            else:
                arr[k] = right[j]
                j += 1
            k += 1

        while i < len(left):
            arr[k] = left[i]
            i += 1
            k += 1

        while j < len(right):
            arr[k] = right[j]
            j += 1
            k += 1

arr = list(map(int, input("Enter the elements separated by space: ").split()))
merge_sort(arr)
print("Sorted array:", arr)                    

Last Modified: January 12, 2025 07:12:32

quick_sort.py

                        # Program to implement quick sort
def quick_sort(arr):
    if len(arr) <= 1:
        return arr
    pivot = arr[len(arr) // 2]
    left = [x for x in arr if x < pivot]
    middle = [x for x in arr if x == pivot]
    right = [x for x in arr if x > pivot]
    return quick_sort(left) + middle + quick_sort(right)

arr = list(map(int, input("Enter the elements separated by space: ").split()))
print("Sorted array:", quick_sort(arr))                    

Last Modified: January 12, 2025 07:12:58

binary_search.py

                        # Program to implement binary search
def binary_search(arr, target):
    left, right = 0, len(arr) - 1
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target:
            return mid
        elif arr[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return -1

arr = list(map(int, input("Enter the sorted elements separated by space: ").split()))
target = int(input("Enter the number to search: "))
result = binary_search(arr, target)

if result != -1:
    print(f"Element found at index {result}")
else:
    print("Element not found")                    

Last Modified: January 12, 2025 07:13:18

count_characters.py

                        # Program to count characters in a string
string = input("Enter a string: ")
print(f"Number of characters: {len(string)}")                    

Last Modified: January 12, 2025 07:13:34

remove_duplicates.py

                        # Program to remove duplicate elements from a list
arr = list(map(int, input("Enter the elements separated by space: ").split()))
unique_arr = list(set(arr))
print(f"List without duplicates: {unique_arr}")                    

Last Modified: January 12, 2025 07:14:08

decimal_to_binary.py

                        # Program to convert decimal to binary
num = int(input("Enter a decimal number: "))
binary = bin(num).replace("0b", "")
print(f"Binary representation of {num} is {binary}")                    

Last Modified: January 12, 2025 07:14:18

binary_to_decimal.py

                        # Program to convert binary to decimal
binary = input("Enter a binary number: ")
decimal = int(binary, 2)
print(f"Decimal representation of {binary} is {decimal}")                    

Last Modified: January 12, 2025 07:14:31

ascii_value.py

                        # Program to find the ASCII value of a character
char = input("Enter a character: ")
print(f"The ASCII value of '{char}' is {ord(char)}")                    

Last Modified: January 12, 2025 07:14:44

sum_of_n_numbers.py

                        # Program to calculate sum of first n numbers
n = int(input("Enter a number: "))
sum_numbers = sum(range(1, n + 1))
print(f"Sum of first {n} numbers is {sum_numbers}")                    

Last Modified: January 12, 2025 07:15:00

matrix_multiplication.py

                        # Program to multiply two matrices
def multiply_matrices(A, B):
    result = [[0, 0], [0, 0]]
    for i in range(len(A)):
        for j in range(len(B[0])):
            for k in range(len(B)):
                result[i][j] += A[i][k] * B[k][j]
    return result

A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
result = multiply_matrices(A, B)

for row in result:
    print(row)                    

Last Modified: January 12, 2025 07:15:13

count_occurrences.py

                        # Program to count occurrences of an element in a list
arr = list(map(int, input("Enter the elements separated by space: ").split()))
target = int(input("Enter the element to count: "))
print(f"The element {target} appears {arr.count(target)} times.")                    

Last Modified: January 12, 2025 07:15:35

simple_interest.py

                        # Program to calculate simple interest
P = float(input("Enter principal amount: "))
R = float(input("Enter rate of interest: "))
T = float(input("Enter time in years: "))

SI = (P * R * T) / 100
print(f"Simple interest is {SI}")                    

Last Modified: January 12, 2025 07:15:46

compound_interest.py

                        # Program to calculate compound interest
P = float(input("Enter principal amount: "))
R = float(input("Enter rate of interest: "))
T = float(input("Enter time in years: "))
N = float(input("Enter the number of times interest is compounded: "))

A = P * (1 + R / (N * 100)) ** (N * T)
CI = A - P
print(f"Compound interest is {CI}")                    

Last Modified: January 12, 2025 07:16:22

pattern1.py

                        # Program to print a pattern of stars
n = int(input("Enter the number of rows: "))
for i in range(1, n + 1):
    print('*' * i)                    

Last Modified: January 12, 2025 07:16:34

pattern2.py

                        # Program to print a reverse pattern of stars
n = int(input("Enter the number of rows: "))
for i in range(n, 0, -1):
    print('*' * i)                    

Last Modified: January 12, 2025 07:16:46

sum_of_even_numbers.py

                        # Program to find the sum of even numbers up to n
n = int(input("Enter a number: "))
sum_even = sum([i for i in range(2, n + 1, 2)])
print(f"Sum of even numbers up to {n} is {sum_even}")                    

Last Modified: January 12, 2025 07:17:00

sum_of_odd_numbers.py

                        # Program to find the sum of odd numbers up to n
n = int(input("Enter a number: "))
sum_odd = sum([i for i in range(1, n + 1, 2)])
print(f"Sum of odd numbers up to {n} is {sum_odd}")                    

Last Modified: January 12, 2025 07:17:11

reverse_number.py

                        # Program to reverse a number
num = int(input("Enter a number: "))
reverse = 0
while num > 0:
    reverse = reverse * 10 + num % 10
    num //= 10
print(f"Reversed number is {reverse}")                    

Last Modified: January 12, 2025 07:17:21

hcf.py

                        # Program to find the highest common factor (HCF) of two numbers
def hcf(a, b):
    while b:
        a, b = b, a % b
    return a

num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
print(f"The HCF of {num1} and {num2} is {hcf(num1, num2)}.")                    

Last Modified: January 12, 2025 07:17:32

factors.py

                        # Program to find all factors of a number
num = int(input("Enter a number: "))
factors = []
for i in range(1, num + 1):
    if num % i == 0:
        factors.append(i)

print(f"Factors of {num} are: {factors}")                    

Last Modified: January 12, 2025 07:17:43

count_digits.py

                        # Program to count digits in a number
num = int(input("Enter a number: "))
count = len(str(num))
print(f"Number of digits in {num} is {count}")                    

Last Modified: January 12, 2025 07:17:58

temp_conversion.py

                        # Program to convert Celsius to Fahrenheit
C = float(input("Enter temperature in Celsius: "))
F = (C * 9/5) + 32
print(f"{C}°C is equal to {F}°F")                    

Last Modified: January 12, 2025 07:18:10

sum_of_natural_numbers.py

                        # Program to calculate sum of natural numbers
n = int(input("Enter a number: "))
sum_natural = n * (n + 1) // 2
print(f"Sum of first {n} natural numbers is {sum_natural}")                    

Last Modified: January 12, 2025 07:18:22

even_odd.py

                        # Program to check if a number is even or odd
num = int(input("Enter a number: "))
if num % 2 == 0:
    print(f"{num} is even")
else:
    print(f"{num} is odd")                    

Last Modified: January 12, 2025 07:18:31

sum_of_squares.py

                        # Program to find the sum of squares of first n numbers
n = int(input("Enter a number: "))
sum_squares = sum([i ** 2 for i in range(1, n + 1)])
print(f"Sum of squares of first {n} numbers is {sum_squares}")                    

Last Modified: January 12, 2025 07:18:43

string_length.py

                        # Program to find the length of a string
string = input("Enter a string: ")
print(f"Length of the string is {len(string)}")                    

Last Modified: January 12, 2025 07:18:56

string_reverse.py

                        # Program to reverse a string
string = input("Enter a string: ")
print(f"Reversed string: {string[::-1]}")                    

Last Modified: January 12, 2025 07:19:24

string_palindrome.py

                        # Program to check if a string is palindrome
string = input("Enter a string: ")
if string == string[::-1]:
    print(f"{string} is a palindrome")
else:
    print(f"{string} is not a palindrome")                    

Last Modified: January 12, 2025 07:19:36

gcd_recursive.py

                        # Program to find GCD using recursion
def gcd(a, b):
    if b == 0:
        return a
    return gcd(b, a % b)

a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
print(f"GCD of {a} and {b} is {gcd(a, b)}")                    

Last Modified: January 12, 2025 07:19:47

lcm_recursive.py

                        # Program to find LCM using recursion
def lcm(a, b):
    return abs(a * b) // gcd(a, b)

a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
print(f"LCM of {a} and {b} is {lcm(a, b)}")                    

Last Modified: January 12, 2025 07:20:00

multiply_list.py

                        # Program to multiply all elements in a list
arr = list(map(int, input("Enter the elements separated by space: ").split()))
result = 1
for num in arr:
    result *= num
print(f"Multiplication of all elements is {result}")                    

Last Modified: January 12, 2025 07:20:13

ADVERTISEMENT