50 best Python programs for beginners | Python Program for beginners for practice | Python Programing | Python Hacks | Python Programmer







50 Basic Python Programs: A Comprehensive Guide

Welcome to the ultimate guide on Python programming! Whether you're a beginner or just looking to refresh your skills, this blog covers 50 essential Python programs that will help you grasp the key concepts of coding, such as loops, conditionals, functions, and data structures.

In this guide, we will go through various types of programs, starting from simple ones like printing patterns to complex ones involving data structures like linked lists and queues.

Table of Contents

  1. Hello World Program
  2. Basic Calculator
  3. Even or Odd Number
  4. Prime Number
  5. Factorial
  6. Fibonacci Series
  7. Reverse a String
  8. Palindrome Check
  9. Sum of Digits
  10. Multiplication Table
  11. Count Vowels
  12. Count Consonants
  13. Find Largest of Three Numbers
  14. Sum of Natural Numbers
  15. Armstrong Number
  16. Matrix Addition
  17. Matrix Multiplication
  18. Count Vowels and Consonants
  19. Count Words in a String
  20. Find Largest Element in Array
  21. Find Smallest Element in Array
  22. Bubble Sort
  23. Insertion Sort
  24. Selection Sort
  25. Linear Search
  26. Binary Search
  27. Find GCD
  28. Find LCM
  29. Power of a Number
  30. Reverse a String
  31. Count Occurrences of a Character
  32. Sum of First N Natural Numbers
  33. ASCII Value of a Character
  34. Sum of Array Elements
  35. Check Leap Year
  36. Sum of Digits of a Number
  37. Sum of Elements in a 2D Array
  38. Reverse an Array
  39. Print Pascal’s Triangle
  40. Find Fibonacci Series Using Recursion
  41. Count Digits in a Number
  42. Check Perfect Number
  43. Sum of Elements in a Linked List
  44. Linked List Reversal
  45. Implement Stack
  46. Implement Queue
  47. Basic Calculator
  48. Convert Decimal to Binary
  49. Find Roots of a Quadratic Equation
  50. Print Diamond Shape

1. Hello World Program

The simplest Python program that prints Hello, World! on the screen.

python
print("Hello, World!")

2. Basic Calculator

This program adds two numbers and performs other basic arithmetic operations.

python
num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) operation = input("Enter operation (+, -, *, /): ") if operation == "+": print(f"The result is: {num1 + num2}") elif operation == "-": print(f"The result is: {num1 - num2}") elif operation == "*": print(f"The result is: {num1 * num2}") elif operation == "/": print(f"The result is: {num1 / num2}") else: print("Invalid operation")

3. Even or Odd Number

This program checks if a given number is even or odd.

python
num = int(input("Enter a number: ")) if num % 2 == 0: print("Even number") else: print("Odd number")

4. Prime Number

This program checks if a number is prime or not.

python
num = int(input("Enter a number: ")) if num > 1: for i in range(2, num): if num % i == 0: print(f"{num} is not a prime number") break else: print(f"{num} is a prime number") else: print(f"{num} is not a prime number")

5. Factorial

This program calculates the factorial of a number.

python
num = int(input("Enter a number: ")) factorial = 1 for i in range(1, num + 1): factorial *= i print(f"Factorial of {num} is {factorial}")

6. Fibonacci Series

This program generates the Fibonacci series up to a given number.

python
n = int(input("Enter the number of terms: ")) a, b = 0, 1 for _ in range(n): print(a, end=" ") a, b = b, a + b

7. Reverse a String

This program reverses the given string.

python
string = input("Enter a string: ") print(f"Reversed string: {string[::-1]}")

8. Palindrome Check

This program checks if the given string is a palindrome.

python
string = input("Enter a string: ") if string == string[::-1]: print("The string is a palindrome") else: print("The string is not a palindrome")

9. Sum of Digits

This program calculates the sum of digits of a given number.

python
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}")

10. Multiplication Table

This program prints the multiplication table of a number.

python
num = int(input("Enter a number: ")) for i in range(1, 11): print(f"{num} x {i} = {num * i}")

11. Count Vowels

This program counts the number of vowels in a string.

python
string = input("Enter a string: ") vowels = "aeiou" count = sum(1 for char in string if char.lower() in vowels) print(f"Number of vowels: {count}")

12. Count Consonants

This program counts the number of consonants in a string.

python
string = input("Enter a string: ") consonants = "bcdfghjklmnpqrstvwxyz" count = sum(1 for char in string if char.lower() in consonants) print(f"Number of consonants: {count}")

13. Find Largest of Three Numbers

This program finds the largest of three numbers.

python
num1 = int(input("Enter first number: ")) num2 = int(input("Enter second number: ")) num3 = int(input("Enter third number: ")) largest = max(num1, num2, num3) print(f"The largest number is {largest}")

14. Sum of Natural Numbers

This program calculates the sum of first N natural numbers.

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

15. Armstrong Number

This program checks if a number is an Armstrong number (also known as narcissistic number).

python
num = int(input("Enter a number: ")) sum = 0 temp = num while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 if sum == num: print(f"{num} is an Armstrong number") else: print(f"{num} is not an Armstrong number")

16. Matrix Addition

This program adds two matrices.

python
A = [[1, 2], [3, 4]] B = [[5, 6], [7, 8]] result = [[0, 0], [0, 0]] for i in range(len(A)): for j in range(len(A[0])): result[i][j] = A[i][j] + B[i][j] print(f"Matrix A + B is: {result}")

17. Matrix Multiplication

This program multiplies two matrices.

python
A = [[1, 2], [3, 4]] B = [[5, 6], [7, 8]] 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] print(f"Matrix A * B is: {result}")

18. Count Vowels and Consonants

This program counts both vowels and consonants in a string.

python
string = input("Enter a string: ") vowels = "aeiou" consonants = "bcdfghjklmnpqrstvwxyz" vowel_count = sum(1 for char in string if char.lower() in vowels) consonant_count = sum(1 for char in string if char.lower() in consonants) print(f"Vowels: {vowel_count}, Consonants: {consonant_count}")

19. Count Words in a String

This program counts the number of words in a string.

python
string = input("Enter a string: ") words = string.split() print(f"Number of words: {len(words)}")

20. Find Largest Element in Array

This program finds the largest element in an array.

python
arr = [3, 1, 4, 1, 5, 9] largest = max(arr) print(f"The largest element is {largest}")










21. Find Smallest Element in Array

This program finds the smallest element in an array.

python
arr = [3, 1, 4, 1, 5, 9] smallest = min(arr) print(f"The smallest element is {smallest}")

22. Bubble Sort

This program sorts an array using the bubble sort algorithm.

python
arr = [64, 34, 25, 12, 22, 11, 90] n = len(arr) for i in range(n): for j in range(0, n-i-1): if arr[j] > arr[j+1]: arr[j], arr[j+1] = arr[j+1], arr[j] print("Sorted array:", arr)

23. Insertion Sort

This program sorts an array using the insertion sort algorithm.

python
arr = [12, 11, 13, 5, 6] 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 print("Sorted array:", arr)

24. Selection Sort

This program sorts an array using the selection sort algorithm.

python
arr = [64, 25, 12, 22, 11] for i in range(len(arr)): min_idx = i for j in range(i+1, len(arr)): if arr[j] < arr[min_idx]: min_idx = j arr[i], arr[min_idx] = arr[min_idx], arr[i] print("Sorted array:", arr)

25. Linear Search

This program searches for an element in an array using the linear search algorithm.

python
arr = [12, 34, 54, 2, 3] x = int(input("Enter the element to search: ")) found = False for i in range(len(arr)): if arr[i] == x: found = True break if found: print(f"{x} is found at index {i}") else: print(f"{x} not found in the array")

26. Binary Search

This program searches for an element in a sorted array using the binary search algorithm.

python
arr = [2, 3, 12, 34, 54] x = int(input("Enter the element to search: ")) low, high = 0, len(arr) - 1 found = False while low <= high: mid = (low + high) // 2 if arr[mid] == x: found = True break elif arr[mid] < x: low = mid + 1 else: high = mid - 1 if found: print(f"{x} is found at index {mid}") else: print(f"{x} not found in the array")

27. Find GCD

This program calculates the greatest common divisor (GCD) of two numbers.

python
import math a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) gcd = math.gcd(a, b) print(f"The GCD of {a} and {b} is {gcd}")

28. Find LCM

This program calculates the least common multiple (LCM) of two numbers.

python
import math a = int(input("Enter first number: ")) b = int(input("Enter second number: ")) lcm = abs(a * b) // math.gcd(a, b) print(f"The LCM of {a} and {b} is {lcm}")

29. Power of a Number

This program calculates the power of a number.

python
base = int(input("Enter base: ")) exponent = int(input("Enter exponent: ")) result = base ** exponent print(f"{base} raised to the power of {exponent} is {result}")

30. Reverse a String

This program reverses the given string.

python
string = input("Enter a string: ") reversed_string = ''.join(reversed(string)) print(f"Reversed string: {reversed_string}")

31. Count Occurrences of a Character

This program counts the occurrences of a character in a string.

python
string = input("Enter a string: ") char = input("Enter character to count: ") count = string.count(char) print(f"The character '{char}' appears {count} times in the string.")

32. Sum of First N Natural Numbers

This program calculates the sum of the first N natural numbers.

python
n = int(input("Enter a number: ")) sum_n = n * (n + 1) // 2 print(f"Sum of first {n} natural numbers is {sum_n}")

33. ASCII Value of a Character

This program prints the ASCII value of a character.

python
char = input("Enter a character: ") print(f"The ASCII value of '{char}' is {ord(char)}")

34. Sum of Array Elements

This program calculates the sum of all elements in an array.

python
arr = [3, 1, 4, 1, 5, 9] sum_arr = sum(arr) print(f"Sum of array elements: {sum_arr}")

35. Check Leap Year

This program checks if a given year is a leap year.

python
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.")

36. Sum of Digits of a Number

This program calculates the sum of the digits of a given number.

python
num = int(input("Enter a number: ")) sum_digits = sum(int(digit) for digit in str(num)) print(f"Sum of digits: {sum_digits}")

37. Sum of Elements in a 2D Array

This program calculates the sum of all elements in a 2D array.

python
arr = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] sum_arr = sum(sum(row) for row in arr) print(f"Sum of all elements in 2D array: {sum_arr}")

38. Reverse an Array

This program reverses an array.

python
arr = [1, 2, 3, 4, 5] reversed_arr = arr[::-1] print(f"Reversed array: {reversed_arr}")

39. Print Pascal’s Triangle

This program prints Pascal’s Triangle up to a given number of rows.

python
n = int(input("Enter number of rows: ")) for i in range(n): for j in range(n - i - 1): print(" ", end="") num = 1 for j in range(i + 1): print(num, end=" ") num = num * (i - j) // (j + 1) print()

40. Find Fibonacci Series Using Recursion

This program finds the Fibonacci series using recursion.

python
def fibonacci(n): if n <= 1: return n else: return fibonacci(n-1) + fibonacci(n-2) n = int(input("Enter the number of terms: ")) for i in range(n): print(fibonacci(i), end=" ")

41. Count Digits in a Number

This program counts the number of digits in a number.

python
num = int(input("Enter a number: ")) count = len(str(abs(num))) print(f"Number of digits: {count}")

42. Check Perfect Number

This program checks if a number is a perfect number.

python
num = int(input("Enter a number: ")) divisors = [i for i in range(1, num) if num % i == 0] if sum(divisors) == num: print(f"{num} is a perfect number") else: print(f"{num} is not a perfect number")

43. Sum of Elements in a Linked List

This program calculates the sum of elements in a linked list.

python
class Node: def __init__(self, data): self.data = data self.next = None def sum_linked_list(head): total = 0 current = head while current: total += current.data current = current.next return total head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) print(f"Sum of linked list elements: {sum_linked_list(head)}")

44. Linked List Reversal

This program reverses a linked list.

python
class Node: def __init__(self, data): self.data = data self.next = None def44. Linked List Reversal

This program reverses a linked list.

python
class Node: def __init__(self, data): self.data = data self.next = None def reverse_linked_list(head): prev = None current = head while current: next_node = current.next current.next = prev prev = current current = next_node return prev # Example linked list: 1 -> 2 -> 3 -> 4 head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) reversed_head = reverse_linked_list(head) while reversed_head: print(reversed_head.data, end=" -> ") reversed_head = reversed_head.next

45. Implement Stack

This program implements a basic stack using a list.

python
class Stack: def __init__(self): self.stack = [] def push(self, item): self.stack.append(item) def pop(self): if not self.is_empty(): return self.stack.pop() return None def is_empty(self): return len(self.stack) == 0 # Example of using the Stack stack = Stack() stack.push(10) stack.push(20) stack.push(30) print("Popped element:", stack.pop())

46. Implement Queue

This program implements a basic queue using a list.

python
class Queue: def __init__(self): self.queue = [] def enqueue(self, item): self.queue.append(item) def dequeue(self): if not self.is_empty(): return self.queue.pop(0) return None def is_empty(self): return len(self.queue) == 0 # Example of using the Queue queue = Queue() queue.enqueue(10) queue.enqueue(20) queue.enqueue(30) print("Dequeued element:", queue.dequeue())

47. Basic Calculator

This program performs basic arithmetic operations such as addition, subtraction, multiplication, and division.

python
num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) operation = input("Enter operation (+, -, *, /): ") if operation == "+": print(f"The result is: {num1 + num2}") elif operation == "-": print(f"The result is: {num1 - num2}") elif operation == "*": print(f"The result is: {num1 * num2}") elif operation == "/": if num2 != 0: print(f"The result is: {num1 / num2}") else: print("Error! Division by zero.") else: print("Invalid operation")

48. Convert Decimal to Binary

This program converts a decimal number to binary.

python
decimal = int(input("Enter a decimal number: ")) binary = bin(decimal)[2:] print(f"The binary representation of {decimal} is {binary}")

49. Find Roots of a Quadratic Equation

This program calculates the roots of a quadratic equation using the quadratic formula.

python
import math a = float(input("Enter coefficient a: ")) b = float(input("Enter coefficient b: ")) c = float(input("Enter coefficient c: ")) discriminant = b**2 - 4*a*c if discriminant > 0: root1 = (-b + math.sqrt(discriminant)) / (2*a) root2 = (-b - math.sqrt(discriminant)) / (2*a) print(f"Roots are {root1} and {root2}") elif discriminant == 0: root = -b / (2*a) print(f"One root: {root}") else: real_part = -b / (2*a) imaginary_part = math.sqrt(-discriminant) / (2*a) print(f"Complex roots: {real_part} + {imaginary_part}i and {real_part} - {imaginary_part}i")

50. Print Diamond Shape

This program prints a diamond pattern using asterisks.

python
n = int(input("Enter the number of rows for the diamond: ")) # Upper half of the diamond for i in range(n): print(" " * (n - i - 1) + "*" * (2 * i + 1)) # Lower half of the diamond for i in range(n - 2, -1, -1): print(" " * (n - i - 1) + "*" * (2 * i + 1))

Conclusion

These 50 basic Python programs cover a wide range of essential topics that every beginner programmer should understand. From simple mathematical operations to working with data structures like linked lists, stacks, and queues, these programs are a great way to start mastering Python programming. Whether you are just getting started or looking for a quick reference, these programs will help you practice and enhance your coding skills!

 

Post a Comment

0 Comments