Python has emerged as one of the most versatile and beginner-friendly programming languages in the world. It is widely used in various fields such as data science, engineering, web development, automation, and academic research. This collection of 49 beginner Python programs provides engineering students with practical examples and exercises to solidify their understanding of Python’s core concepts.

These programs are grouped into different categories, including basic input/output operations, conditional statements, loops, lists, functions, and utilities specific to engineering. By completing these exercises, students will not only grasp essential programming skills but also be able to apply them to engineering problems, such as solving mathematical equations, working with data structures, and performing simulations.
This resource is an excellent starting point for any engineering student eager to learn Python and gain confidence in their coding abilities.
Related articles:
- 49 Simple Python programs for beginners
- Python in machine learning
- Python project ideas (school level)
- Python project collection
- VS Code IDE
Basic Input/Output and Arithmetic
1. Hello World
Prints a welcome message.
# Display a welcome message
print("Welcome to Collegelib!")
This simple program shows how to display text on the screen.
2. Add Two Numbers
Adds two numbers and prints the result.
# Add two numbers and print the sum
a = 15
b = 25
sum = a + b
print("Total:", sum)
It adds two predefined numbers and displays the result.
3. Simple Interest Calculator
Calculates simple interest using the formula.
# Calculate simple interest
principal = 5000
rate = 5 # percent
time = 3 # years
interest = (principal * rate * time) / 100
print("Simple Interest:", interest)
This applies the basic formula for calculating interest over time.
4. Average of Three Numbers
Finds the average of three numbers.
# Calculate average of three values
x = 60
y = 75
z = 90
average = (x + y + z) / 3
print("Average:", average)
The program calculates the average by summing and dividing the values.
5. Area of a Triangle
Computes the area of a triangle.
# Calculate area of a triangle
base = 10
height = 6
area = 0.5 * base * height
print("Area of triangle:", area)
Uses the geometry formula: half of base times height.
6. Convert Celsius to Fahrenheit
Converts temperature from Celsius to Fahrenheit.
# Convert Celsius to Fahrenheit
celsius = 30
fahrenheit = (celsius * 9 / 5) + 32
print("Temperature in Fahrenheit:", fahrenheit)
Applies the temperature conversion formula for Fahrenheit.
7. Convert Kilometres to Miles
Converts distance in kilometres to miles.
# Convert kilometres to miles
km = 8
conversion_factor = 0.621371
miles = km * conversion_factor
print("Distance in miles:", miles)
This converts metric distance to the imperial system.
8. Calculate Square Root
Finds the square root of a number.
# Calculate square root
number = 81
sqrt = number ** 0.5
print("Square root:", sqrt)
Uses exponentiation to calculate the square root.
9. Power of a Number
Raises a number to a specified exponent.
# Calculate power of a number
base = 2
exponent = 5
result = base ** exponent
print("2 to the power of 5 is:", result)
This multiplies the base by itself the number of times specified.
Conditions and Comparisons
10. Check Positive, Negative or Zero
Identifies the sign of a number.
# Identify if a number is positive, negative or zero
num = -3
if num > 0:
print("Positive")
elif num < 0:
print("Negative")
else:
print("Zero")
Compares a number to zero to determine its sign.
11. Check Even or Odd
Checks if a number is even or odd.
# Determine if a number is even or odd
num = 22
if num % 2 == 0:
print("Even")
else:
print("Odd")
Uses the modulus operator to test divisibility by 2.
12. Find the Largest of Three Numbers
Determines the largest among the three values.
# Compare three numbers to find the largest
a = 40
b = 65
c = 30
if a >= b and a >= c:
print("Largest:", a)
elif b >= a and b >= c:
print("Largest:", b)
else:
print("Largest:", c)
Compares three values using conditional statements.
13. Check Leap Year
Checks if a year is a leap year.
# Determine if a year is a leap year
year = 2024
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
print("Leap year")
else:
print("Not a leap year")
Applies the Gregorian calendar rules to find leap years.
14. Check Prime Number
Verifies if a number is prime.
# Check if number is prime
num = 29
is_prime = True
if num <= 1:
is_prime = False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
is_prime = False
break
print("Prime number" if is_prime else "Not a prime number")
Checks if the number has only two factors: one and itself.
15. Armstrong Number Checker
Checks for Armstrong number.
# Check Armstrong number
num = 153
sum = 0
temp = num
while temp > 0:
digit = temp % 10
sum += digit ** 3
temp //= 10
if sum == num:
print("Armstrong number")
else:
print("Not an Armstrong number")
An Armstrong number equals the sum of the cubes of its digits.
Strings and Characters
16. Reverse a String
Prints the reverse of a string.
# Reverse a given string
text = "Collegelib"
reversed_text = text[::-1]
print("Reversed:", reversed_text)
Slices the string in reverse order.
17. Palindrome Checker
Checks if a string reads the same backwards.
# Check for palindrome
word = "madam"
if word == word[::-1]:
print("Palindrome")
else:
print("Not a palindrome")
Compares the original string with its reversed version.
18. Count Characters in a String
Counts the number of characters.
# Count characters in a string
text = "Collegelib"
count = len(text)
print("Character count:", count)
Uses the length function to count characters.
19. Count Words in a Sentence
Counts the number of words in a sentence.
# Count words in a sentence
sentence = "Python is easy at Collegelib"
words = sentence.split()
print("Word count:", len(words))
Splits the sentence into words and counts them.
20. Count Uppercase and Lowercase Letters
Differentiates character cases.
# Count uppercase and lowercase letters
text = "Collegelib FOR Engineering Students"
upper = lower = 0
for char in text:
if char.isupper():
upper += 1
elif char.islower():
lower += 1
print("Uppercase:", upper)
print("Lowercase:", lower)
Uses character functions to classify and count.
Loops
21. Print Natural Numbers from 1 to N
Prints natural numbers starting from 1 up to a specified number.
# Print natural numbers from 1 to N
n = 10
for i in range(1, n + 1):
print(i, end=' ')
This program iterates from 1 to N, printing each number.
22. Display Multiples of a Number
Displays the first 10 multiples of a given number.
# Display first 10 multiples of a number
number = 6
for i in range(1, 11):
print(number * i, end=' ')
The loop multiplies the number by values from 1 to 10.
23. Find Factorial of a Number
Calculates the factorial of a given number.
# Calculate factorial of a number
num = 5
factorial = 1
for i in range(1, num + 1):
factorial *= i
print("Factorial:", factorial)
This loop multiplies all integers up to the given number.
24. Display Fibonacci Sequence
Prints the Fibonacci sequence up to N terms.
# Display Fibonacci sequence
n_terms = 10
a, b = 0, 1
for i in range(n_terms):
print(a, end=' ')
a, b = b, a + b
The Fibonacci series is generated by iterating and updating two variables.
25. Sum of Numbers from 1 to N
Calculates the sum of numbers from 1 to a given number.
# Calculate sum of numbers from 1 to N
n = 10
total = 0
for i in range(1, n + 1):
total += i
print("Sum:", total)
The loop adds numbers from 1 to N.
Lists and Patterns
26. List Even Numbers from 1 to N
Prints all even numbers from 1 to a given upper limit.
# Print even numbers from 1 to N
n = 20
for i in range(1, n + 1):
if i % 2 == 0:
print(i, end=' ')
This loops through numbers, printing only the even ones.
27. Create a List of Squares
Creates a list containing the squares of numbers from 1 to N.
# Generate a list of squares from 1 to N
n = 10
squares = [i ** 2 for i in range(1, n + 1)]
print("Squares:", squares)
This list comprehension generates squares of numbers up to N.
28. Print a Star Pattern (Right-angled Triangle)
Displays a right-angled triangle pattern with stars.
# Print a right-angled triangle star pattern
rows = 5
for i in range(1, rows + 1):
print('* ' * i)
The loop prints stars in increasing quantities, forming a triangle.
29. Print a Star Pattern (Pyramid)
Displays a pyramid star pattern.
# Print a pyramid star pattern
rows = 5
for i in range(1, rows + 1):
print(' ' * (rows - i) + '* ' * i)
This pattern uses spaces for alignment, creating a centred pyramid.
30. Reverse a List
Reverses the order of elements in a list.
# Reverse a list
numbers = [1, 2, 3, 4, 5]
reversed_list = numbers[::-1]
print("Reversed List:", reversed_list)
This slices the list in reverse order.
Functions and Logic
31. Find the GCD of Two Numbers
Finds the greatest common divisor (GCD) of two numbers.
# Calculate the GCD of two numbers
def gcd(a, b):
while b:
a, b = b, a % b
return a
x, y = 56, 98
print("GCD:", gcd(x, y))
This uses Euclid’s algorithm to find the GCD.
32. Prime Number Checker Function
Defines a function to check whether a number is prime.
# Function to check if number is prime
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1):
if num % i == 0:
return False
return True
print(is_prime(29)) # Example output
The function checks if the number is divisible by any integer up to its square root.
33. Factorial Function
Defines a function to compute the factorial of a number.
# Function to calculate factorial
def factorial(n):
result = 1
for i in range(1, n + 1):
result *= i
return result
print(factorial(5)) # Output: 120
This function calculates the factorial by multiplying all integers from 1 to n.
34. Fibonacci Sequence Function
Generates the Fibonacci sequence up to N terms.
# Function to generate Fibonacci sequence
def fibonacci(n):
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a + b
fibonacci(10)
This function prints the Fibonacci numbers up to the specified number of terms.
Academic Utilities
35. Calculate the Average of List Elements
Calculates the average of all elements in a list.
# Calculate average of list elements
numbers = [10, 20, 30, 40, 50]
average = sum(numbers) / len(numbers)
print("Average:", average)
The program calculates the average using the sum and length of the list.
36. Convert Decimal to Binary
Converts a decimal number to binary.
# Convert decimal to binary
decimal = 14
binary = bin(decimal)[2:]
print("Binary:", binary)
The bin() function is used, and the 2:
removes the ‘0b’ prefix.
37. Grade Classification System
Classifies students based on their marks.
# Grade classification based on marks
marks = 75
if marks >= 85:
print("Grade A")
elif marks >= 70:
print("Grade B")
elif marks >= 50:
print("Grade C")
else:
print("Fail")
This uses conditional statements to assign grades based on marks.
38. Generate a Multiplication Table
Generates a multiplication table for a number.
# Generate a multiplication table
num = 6
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
This program prints the multiplication table for a given number.
39. Calculate the Area of a Circle
Computes the area of a circle given its radius.
# Calculate area of a circle
import math
radius = 7
area = math.pi * radius ** 2
print("Area of circle:", area)
This program uses the math.pi constant to calculate the area.
40. Find the Circumference of a Circle
Calculates the circumference of a circle from its radius.
# Calculate circumference of a circle
radius = 7
circumference = 2 * math.pi * radius
print("Circumference:", circumference)
The circumference is computed using the formula 2πr2 \pi r.
41. Calculate the Volume of a Cylinder
Finds the volume of a cylinder given its radius and height.
# Calculate volume of a cylinder
radius = 3
height = 5
volume = math.pi * radius ** 2 * height
print("Volume of cylinder:", volume)
This formula calculates the volume based on the radius and height.
42. Find the Roots of a Quadratic Equation
Solves the quadratic equation ax2+bx+c=0ax^2 + bx + c = 0.
# Solve quadratic equation
import cmath
a, b, c = 1, -3, 2
d = b ** 2 - 4 * a * c
root1 = (-b + cmath.sqrt(d)) / (2 * a)
root2 = (-b - cmath.sqrt(d)) / (2 * a)
print("Roots:", root1, root2)
Uses the quadratic formula to find the roots, considering both real and complex roots.
Academic Utilities (continued)
43. Find Distance Between Two Points
Calculates the Euclidean distance between two points in a 2D space.
# Calculate the distance between two points
import math
x1, y1 = 2, 3
x2, y2 = 5, 7
distance = math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2)
print("Distance between points:", distance)
The Euclidean distance formula is applied to calculate the distance between the points.
44. Convert Binary to Decimal
Converts a binary number to its decimal equivalent.
# Convert binary to decimal
binary = "1011"
decimal = int(binary, 2)
print("Decimal:", decimal)
The int() function is used to convert the binary string to a decimal integer.
45. Check for Armstrong Number (with N digits)
Verifies if a number is an Armstrong number for N digits.
# Check if number is Armstrong (N digits)
num = 1634
num_str = str(num)
n = len(num_str)
sum = sum(int(digit) ** n for digit in num_str)
if sum == num:
print("Armstrong number")
else:
print("Not an Armstrong number")
The program raises each digit to the power of the number of digits and checks for equality.
46. Calculate the Compound Interest
Calculates compound interest using the formula.
# Calculate compound interest
principal = 1000
rate = 5 # percent
time = 2 # years
compound_interest = principal * (1 + rate / 100) ** time - principal
print("Compound Interest:", compound_interest)
This uses the compound interest formula for periodic interest calculation.
47. Matrix Addition
Adds two matrices.
# Add two matrices
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
result = [[A[i][j] + B[i][j] for j in range(len(A[0]))] for i in range(len(A))]
print("Matrix Addition Result:", result)
This uses nested list comprehensions to add corresponding elements of two matrices.
48. Find the Determinant of a Matrix
Calculates the determinant of a 2×2 matrix.
# Calculate the determinant of a matrix
matrix = [[3, 4], [2, 5]]
determinant = matrix[0][0] * matrix[1][1] - matrix[0][1] * matrix[1][0]
print("Determinant:", determinant)
The determinant formula for a 2×2 matrix is applied directly.
49. Plot a Graph of a Function
Plots a mathematical function using matplotlib.
# Plot a graph of a function
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(-10, 10, 100)
y = x ** 2 # y = x^2 (parabola)
plt.plot(x, y)
plt.title("Graph of y = x^2")
plt.xlabel("x-axis")
plt.ylabel("y-axis")
plt.grid(True)
plt.show()
The library is used to plot the function y = x² over a range of values for x.2 over a range of values for x.
This curated list of Python programs will provide students with a hands-on experience in fundamental programming concepts such as variables, control structures, data types, and mathematical operations. By incorporating engineering-specific problems, the curriculum ensures that these concepts are not just theoretical but also practical. This approach equips students with the tools to tackle real-world challenges in their academic pursuits and future careers.
These programs familiarise students with key Python libraries and tools commonly used in engineering, including math for mathematical operations, NumPy for scientific computations, and Matplotlib for graphing and data visualisation.
Through these exercises, students will learn Python and enhance their logical thinking, problem-solving skills, and confidence to tackle more complex projects in the future.