Simple Python Programs for Beginners
Print Hello World – Program 1 #
Program:
# This is a simple Python program to print text on the screen
# The print() function is used to display output
print("Hello, World!")
Output:
Hello, World!
Add Two Numbers – Program 2 #
Program:
# This program adds two numbers provided by the user
# Input from user (input() returns a string, so we convert it to float or int)
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
# Add the two numbers
sum = num1 + num2
# Display the result
print("The sum of", num1, "and", num2, "is:", sum)
Output:
Enter first number: 10
Enter second number: 20
The sum of 10.0 and 20.0 is: 30.0
Find the Fibonacci Series – Program 3 #
Explanation :
The Fibonacci Series is a sequence of numbers where each number is the sum of the two preceding ones, starting from 0 and 1. The sequence looks like this:
Example :
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …
The first two numbers are fixed: 0 and 1.
Every subsequent number is calculated by adding the two numbers before it.
For example:
- 0 + 1 = 1
- 1 + 1 = 2
- 1 + 2 = 3
- 2 + 3 = 5
- And so on.
This series is widely used in mathematics, computer science, and even nature (e.g., patterns in flower petals, pinecones, etc.).
Program:
import java.util.Scanner;nnpublic class FibonacciSeries {nn public static void main(String[] args) {nn Scanner scanner = new Scanner(System.in);nn System.out.print(u0022Enter the number of terms: u0022);nn int n = scanner.nextInt();nn int firstTerm = 0, secondTerm = 1;nn System.out.println(u0022Fibonacci Series:u0022);nn for (int i = 1; i u003c= n; i++) {nn System.out.print(firstTerm + u0022 u0022);nn int nextTerm = firstTerm + secondTerm;nn firstTerm = secondTerm;nn secondTerm = nextTerm;nn }nn scanner.close();nn }nn}nn// Output:nnEnter the number of terms: 5nnFibonacci Series:nn0 1 1 2 3 nnEnter the number of terms: 10nnFibonacci Series:nn0 1 1 2 3 5 8 13 21 34
Check if a Number is Prime – Program 4 #
Explanation:
A prime number is a number greater than 1 that has no positive divisors other than 1 and itself. In other words, it cannot be formed by multiplying two smaller natural numbers.
Key Points:
- Prime Numbers: 2, 3, 5, 7, 11, 13, etc.
- Non-Prime Numbers (Composite): 4, 6, 8, 9, 10, etc.
- Special Case: The number 1 is neither prime nor composite.
How to Check:
A number is prime if it is not divisible by any number other than 1 and itself.
For example:
- 7 is prime because it is only divisible by 1 and 7.
- 9 is not prime because it is divisible by 1, 3, and 9.
Program:
import java.util.Scanner;nnpublic class PrimeNumberChecker {nn public static void main(String[] args) {nn Scanner scanner = new Scanner(System.in);nn System.out.print(u0022Enter a number: u0022);nn int number = scanner.nextInt();nn boolean isPrime = true;nn if (number u003c= 1) {nn isPrime = false;nn } else {nn for (int i = 2; i u003c= Math.sqrt(number); i++) {nn if (number % i == 0) {nn isPrime = false;nn break;nn }nn }nn }nn if (isPrime) {nn System.out.println(number + u0022 is a prime number.u0022);nn } else {nn System.out.println(number + u0022 is not a prime number.u0022);nn }nn scanner.close();nn }nn}nn// OutputnnEnter a number: 7nn7 is a prime number.nnEnter a number: 10nn10 is not a prime number.nnEnter a number: 1nn1 is not a prime number.
This series is widely used in mathematics, computer science, and even nature (e.g., patterns in flower petals, pinecones, etc.).
Reverse a Number – Program 5 #
Explanation:
Reversing a number means rearranging its digits in the opposite order.
For example:
- Original number: 1234
- Reversed number: 4321
Program:
import java.util.Scanner;nnpublic class ReverseNumber {nn public static void main(String[] args) {nn Scanner scanner = new Scanner(System.in);nn System.out.print(u0022Enter a number: u0022);nn int number = scanner.nextInt();nn int reversedNumber = 0;nn while (number != 0) {nn int digit = number % 10; // Extract the last digitnn reversedNumber = reversedNumber * 10 + digit; // Append the digit to the reversed numbernn number = number / 10; // Remove the last digitnn }nn System.out.println(u0022Reversed number: u0022 + reversedNumber);nn scanner.close();nn }nn}nn// OutputnnEnter a number: 1234nnReversed number: 4321nnEnter a number: 56789nnReversed number: 98765
Check if a Number is Palindrome – Program 6 #
Explanation:
A palindrome number is a number that remains the same when its digits are reversed. For example:
- 121 is a palindrome because reversing it gives 121.
- 123 is not a palindrome because reversing it gives 321.
Program:
import java.util.Scanner;nnpublic class PalindromeChecker {nn public static void main(String[] args) {nn Scanner scanner = new Scanner(System.in);nn System.out.print(u0022Enter a number: u0022);nn int number = scanner.nextInt();nn int originalNumber = number;nn int reversedNumber = 0;nn while (number != 0) {nn int digit = number % 10; // Extract the last digitnn reversedNumber = reversedNumber * 10 + digit; // Append the digit to the reversed numbernn number = number / 10; // Remove the last digitnn }nn if (originalNumber == reversedNumber) {nn System.out.println(originalNumber + u0022 is a palindrome.u0022);nn } else {nn System.out.println(originalNumber + u0022 is not a palindrome.u0022);nn }nn scanner.close();nn }nn}nn// OutputnnEnter a number: 121nn121 is a palindrome.nnEnter a number: 123nn123 is not a palindrome.nnEnter a number: 1221nn1221 is a palindrome.
Check if a Number is Armstrong – Program 7 #
Explanation:
An Armstrong number (also known as a narcissistic number) is a number that is equal to the sum of its own digits each raised to the power of the number of digits. For example:
Program:
import java.util.Scanner;nnpublic class ArmstrongNumberChecker {nn public static void main(String[] args) {nn Scanner scanner = new Scanner(System.in);nn System.out.print(u0022Enter a number: u0022);nn int number = scanner.nextInt();nn int originalNumber = number;nn int sum = 0;nn int digits = String.valueOf(number).length(); // Count the number of digitsnn while (number != 0) {nn int digit = number % 10; // Extract the last digitnn sum += Math.pow(digit, digits); // Add the digit raised to the power of digitsnn number = number / 10; // Remove the last digitnn }nn if (originalNumber == sum) {nn System.out.println(originalNumber + u0022 is an Armstrong number.u0022);nn } else {nn System.out.println(originalNumber + u0022 is not an Armstrong number.u0022);nn }nn scanner.close();nn }nn}nn// OutputnnEnter a number: 153nn153 is an Armstrong number.nnEnter a number: 370nn370 is an Armstrong number.nnEnter a number: 123nn123 is not an Armstrong number.
Calculate GCD and LCM of Two Numbers – Program 8 #
Explanation:
1. GCD (Greatest Common Divisor):
- The largest positive integer that divides both numbers without leaving a remainder.
- Example: GCD of 12 and 18 is 6.
2. LCM (Least Common Multiple):
- The smallest positive integer that is a multiple of both numbers.
- Example: LCM of 12 and 18 is 36.
Program:
import java.util.Scanner;nnpublic class GCDandLCM {nn public static void main(String[] args) {nn Scanner scanner = new Scanner(System.in);nn System.out.print(u0022Enter the first number: u0022);nn int num1 = scanner.nextInt();nn System.out.print(u0022Enter the second number: u0022);nn int num2 = scanner.nextInt();nn int gcd = calculateGCD(num1, num2);nn int lcm = (num1 * num2) / gcd; // Using the relationship between GCD and LCMnn System.out.println(u0022GCD of u0022 + num1 + u0022 and u0022 + num2 + u0022 is: u0022 + gcd);nn System.out.println(u0022LCM of u0022 + num1 + u0022 and u0022 + num2 + u0022 is: u0022 + lcm);nn scanner.close();nn }nn // Function to calculate GCD using Euclidean Algorithmnn public static int calculateGCD(int a, int b) {nn while (b != 0) {nn int temp = b;nn b = a % b;nn a = temp;nn }nn return a;nn }nn}nn// Output:nnEnter the first number: 12nnEnter the second number: 18nnGCD of 12 and 18 is: 6nnLCM of 12 and 18 is: 36nnEnter the first number: 20nnEnter the second number: 25nnGCD of 20 and 25 is: 5nnLCM of 20 and 25 is: 100
Swap two numbers using a temporary variable – Program 9 #
Explanation:
Swapping two numbers means exchanging their values.
For example:
- Before swapping: a = 5, b = 10
- After swapping: a = 10, b = 5
Program:
public class SwapNumbers {nn public static void main(String[] args) {nn int a = 5;nn int b = 10;nn System.out.println(u0022Before swapping: a = u0022 + a + u0022, b = u0022 + b);nn // Swapping using a temporary variablenn int temp = a; // Store the value of a in tempnn a = b; // Assign the value of b to ann b = temp; // Assign the original value of a (stored in temp) to bnn System.out.println(u0022After swapping: a = u0022 + a + u0022, b = u0022 + b);nn }nn}
Swapping Two Numbers without a Third Variable – Program 10 #
Program:
import java.util.Scanner;nnpublic class SwapNumbers {nn public static void main(String[] args) {nn Scanner scanner = new Scanner(System.in);nn System.out.print(u0022Enter the first number (a): u0022);nn int a = scanner.nextInt();nn System.out.print(u0022Enter the second number (b): u0022);nn int b = scanner.nextInt();nn System.out.println(u0022Before swapping: a = u0022 + a + u0022, b = u0022 + b);nn // Swapping logic without a third variablenn a = a + b; // Step 1: a now holds the sum of a and bnn b = a - b; // Step 2: b now holds the original value of ann a = a - b; // Step 3: a now holds the original value of bnn System.out.println(u0022After swapping: a = u0022 + a + u0022, b = u0022 + b);nn scanner.close();nn }nn}nn// Output:nnEnter the first number (a): 5nnEnter the second number (b): 10nnBefore swapping: a = 5, b = 10nnAfter swapping: a = 10, b = 5
Alternative Way
a = a ^ b; // Step 1: a now holds the XOR of a and b
b = a ^ b; // Step 2: b now holds the original value of a
a = a ^ b; // Step 3: a now holds the original value of b
Note: This method is also efficient and avoids arithmetic overflow issue
Find the sum of digits of a number – Program 11 #
Explanation:
The sum of digits of a number refers to the total obtained by adding up each individual digit in the number. It is a basic mathematical operation that breaks down a number into its constituent digits and sums them together.
Example:
Consider the number 1234.
- The digits are: 1, 2, 3, and 4.
- The sum of the digits is: 1 + 2 + 3 + 4 = 10.
Program:
import java.util.Scanner;nnpublic class SumOfDigits {nn public static void main(String[] args) {nn Scanner scanner = new Scanner(System.in);nn // Input: Get the number from the usernn System.out.print(u0022Enter a number: u0022);nn int number = scanner.nextInt();nn // Initialize sum to 0nn int sum = 0;nn // Process: Calculate the sum of digitsnn int temp = number; // Temporary variable to hold the numbernn while (temp != 0) {nn int digit = temp % 10; // Extract the last digitnn sum += digit; // Add the digit to the sumnn temp = temp / 10; // Remove the last digitnn }nn // Output: Display the sum of digitsnn System.out.println(u0022Sum of digits of u0022 + number + u0022 is: u0022 + sum);nn scanner.close();nn }nn}nn// outputnnEnter a number: 1234nnSum of digits of 1234 is: 10
Find the largest of three numbers – Program 12 #
Explanation:
The largest of three numbers refers to the greatest value among three given numbers.
Example:
Consider the numbers 12, 25, and 8. Here the largest number is 25.
Program:
import java.util.Scanner;nnpublic class LargestOfThree {nn public static void main(String[] args) {nn Scanner scanner = new Scanner(System.in);nn // Input: Get three numbers from the usernn System.out.print(u0022Enter the first number: u0022);nn int num1 = scanner.nextInt();nn System.out.print(u0022Enter the second number: u0022);nn int num2 = scanner.nextInt();nn System.out.print(u0022Enter the third number: u0022);nn int num3 = scanner.nextInt();nn // Logic: Find the largest numbernn int largest;nn if (num1 u003e= num2 u0026u0026 num1 u003e= num3) {nn largest = num1; // num1 is the largestnn } else if (num2 u003e= num1 u0026u0026 num2 u003e= num3) {nn largest = num2; // num2 is the largestnn } else {nn largest = num3; // num3 is the largestnn }nn // Output: Display the largest numbernn System.out.println(u0022The largest number is: u0022 + largest);nn scanner.close();nn }nn}nn// OutputnnEnter the first number: 12nnEnter the second number: 25nnEnter the third number: 8nnThe largest number is: 25
Find the smallest of three numbers – Program 13 #
Explanation:
The smallest of three numbers refers to the smallest value among three given numbers.
Example:
Consider the numbers 12, 25, and 8. Here the smallest number is 8.
Program:
import java.util.Scanner;nnpublic class SmallestOfThree {nn public static void main(String[] args) {nn Scanner scanner = new Scanner(System.in);nn // Input: Get three numbers from the usernn System.out.print(u0022Enter the first number: u0022);nn int num1 = scanner.nextInt();nn System.out.print(u0022Enter the second number: u0022);nn int num2 = scanner.nextInt();nn System.out.print(u0022Enter the third number: u0022);nn int num3 = scanner.nextInt();nn // Logic: Find the smallest numbernn int smallest;nn if (num1 u003c= num2 u0026u0026 num1 u003c= num3) {nn smallest = num1; // num1 is the smallestnn } else if (num2 u003c= num1 u0026u0026 num2 u003c= num3) {nn smallest = num2; // num2 is the smallestnn } else {nn smallest = num3; // num3 is the smallestnn }nn // Output: Display the smallest numbernn System.out.println(u0022The smallest number is: u0022 + smallest);nn scanner.close();nn }nn}n// OutputnnEnter the first number: 12nnEnter the second number: 25nnEnter the third number: 8nnThe smallest number is: 8
Check if a number is a perfect number – Program 14 #
Explanation:
A perfect number is a positive integer that is equal to the sum of its proper divisors (excluding itself). In other words, if you add up all the numbers that divide the number evenly (except the number itself), the sum should be equal to the number.
Example:
- 6 is a perfect number because its proper divisors are 1, 2, and 3, and 1 + 2 + 3 = 6.
- 28 is also a perfect number because its proper divisors are 1, 2, 4, 7, and 14, and 1 + 2 + 4 + 7 + 14 = 28.
Program:
import java.util.Scanner;nnpublic class PerfectNumber {nn public static void main(String[] args) {nn Scanner scanner = new Scanner(System.in);nn // Input: Get the number from the usernn System.out.print(u0022Enter a number: u0022);nn int number = scanner.nextInt();nn // Logic: Check if the number is perfectnn int sum = 0;nn for (int i = 1; i u003c number; i++) {nn if (number % i == 0) {nn sum += i; // Add proper divisors to the sumnn }nn }nn // Output: Display the resultnn if (sum == number) {nn System.out.println(number + u0022 is a perfect number.u0022);nn } else {nn System.out.println(number + u0022 is not a perfect number.u0022);nn }nn scanner.close();nn }nn}nn// OutputnnEnter a number: 28nn28 is a perfect number.nnEnter a number: 12nn12 is not a perfect number.
Find the square root of a number – Program 15 #
Explanation:
Square Root of a Number
The square root of a number is a value that, when multiplied by itself, gives the original number. It is denoted by the symbol √.
Example:
- The square root of 25 is 5 because 5 × 5 = 25.
- The square root of 9 is 3 because 3 × 3 = 9.
Program:
import java.util.Scanner;nnpublic class SquareRoot {nn public static void main(String[] args) {nn Scanner scanner = new Scanner(System.in);nn // Input: Get the number from the usernn System.out.print(u0022Enter a number: u0022);nn double number = scanner.nextDouble();nn // Logic: Calculate the square rootnn double squareRoot = Math.sqrt(number);nn // Output: Display the square rootnn System.out.println(u0022The square root of u0022 + number + u0022 is: u0022 + squareRoot);nn scanner.close();nn }nn}nn// OutputnnEnter a number: 25nnThe square root of 25.0 is: 5.0
Find whether leap year or not – Program 16 #
Explanation:
Leap Year
A leap year is a year that has 366 days instead of the usual 365 days. The extra day is added to the month of February, making it 29 days long instead of 28. Leap years are introduced to keep the calendar year synchronized with the astronomical year (the time it takes Earth to orbit the Sun).
Program:
import java.util.Scanner;nnpublic class LeapYear {nn public static void main(String[] args) {nn Scanner scanner = new Scanner(System.in);nn // Input: Get the year from the usernn System.out.print(u0022Enter a year: u0022);nn int year = scanner.nextInt();nn // Logic: Check if the year is a leap yearnn boolean isLeapYear = false;nn if (year % 4 == 0) {nn if (year % 100 == 0) {nn if (year % 400 == 0) {nn isLeapYear = true; // Divisible by 400nn }nn } else {nn isLeapYear = true; // Divisible by 4 but not by 100nn }nn }nn // Output: Display the resultnn if (isLeapYear) {nn System.out.println(year + u0022 is a leap year.u0022);nn } else {nn System.out.println(year + u0022 is not a leap year.u0022);nn }nn scanner.close();nn }nn}nn// Output:nnEnter a year: 2024nn2024 is a leap year.nnEnter a year: 1900nn1900 is not a leap year.
Convert a decimal number to binary – Program 17 #
Explanation:
Converting a decimal number to binary involves representing the number in base 2 (using only 0s and 1s). The process works as follows:
- Divide the decimal number by 2.
- Record the remainder (either 0 or 1).
- Update the number to be the quotient of the division.
- Repeat the process until the number becomes 0.
- The binary number is the sequence of remainders read in reverse order.
Example:
Convert 13 to binary:
- 13 ÷ 2 = 6, remainder 1
- 6 ÷ 2 = 3, remainder 0
- 3 ÷ 2 = 1, remainder 1
- 1 ÷ 2 = 0, remainder 1
- Binary: 1101 (read remainders in reverse order).
Program:
import java.util.Scanner;nnpublic class DecimalToBinary {nn public static void main(String[] args) {nn Scanner scanner = new Scanner(System.in);nn System.out.print(u0022Enter a decimal number: u0022);nn int decimal = scanner.nextInt();nn StringBuilder binary = new StringBuilder();nn if (decimal == 0) {nn binary.append(u00220u0022); // Handle the special case for 0nn } else {nn while (decimal u003e 0) {nn int remainder = decimal % 2; // Get the remaindernn binary.insert(0, remainder); // Insert the remainder at the beginningnn decimal = decimal / 2; // Update the numbernn }nn }nn System.out.println(u0022Binary representation: u0022 + binary.toString());nn scanner.close();nn }nn}nn// OutputnnEnter a decimal number: 13nnBinary representation: 1101nnEnter a decimal number: 25nnBinary representation: 11001nnEnter a decimal number: 0nnBinary representation: 0
Convert a binary number to decimal – Program 18 #
Explanation:
Converting a binary number to decimal involves calculating the decimal equivalent of a number represented in base 2 (using 0s and 1s).
- Start from the rightmost digit (least significant bit).
- Multiply each binary digit by 2 power n, where n is its position (starting from 0).
- Sum all the results to get the decimal number.
Example:
Program:
import java.util.Scanner;nnpublic class BinaryToDecimal {nn public static void main(String[] args) {nn Scanner scanner = new Scanner(System.in);nn System.out.print(u0022Enter a binary number: u0022);nn String binary = scanner.nextLine();nn int decimal = 0;nn int power = 0;nn // Start from the end of the string (rightmost digit)nn for (int i = binary.length() - 1; i u003e= 0; iu002du002d) {nn char ch = binary.charAt(i);nn if (ch == '1') {nn decimal += Math.pow(2, power); // Add 2^power to the resultnn }nn power++; // Increment the power for the next digitnn }nn System.out.println(u0022Decimal representation: u0022 + decimal);nn scanner.close();nn }nn}nn// OutputnnEnter a binary number: 1101nnDecimal representation: 13nnEnter a binary number: 1010nnDecimal representation: 10nnEnter a binary number: 1111nnDecimal representation: 15
Find the Sum of multiples of 3 – Program 19 #
Explanation:
The sum of multiples of 3 involves adding all numbers within a given range that are divisible by 3.
For example:
- Range: 1 to 10
- Multiples of 3: 3, 6, 9
- Sum: 3+6+9=18
Program:
import java.util.Scanner;nnpublic class SumOfMultiplesOf3 {nn public static void main(String[] args) {nn Scanner scanner = new Scanner(System.in);nn System.out.print(u0022Enter the upper limit (n): u0022);nn int n = scanner.nextInt();nn int sum = 0;nn for (int i = 1; i u003c= n; i++) {nn if (i % 3 == 0) { // Check if the number is divisible by 3nn sum += i; // Add the number to the sumnn }nn }nn System.out.println(u0022Sum of multiples of 3 from 1 to u0022 + n + u0022 is: u0022 + sum);nn scanner.close();nn }nn}nn// OutputnnEnter the upper limit (n): 10nnSum of multiples of 3 from 1 to 10 is: 18nnEnter the upper limit (n): 20nnSum of multiples of 3 from 1 to 20 is: 63
Find the Sum of prime digits – Program 20 #
Explanation:
The sum of prime digits involves identifying the prime digits in a number and calculating their sum. Prime digits are digits that are prime numbers. The prime digits are 2, 3, 5, and 7.
Program:
import java.util.Scanner;nnpublic class SumOfPrimeDigits {nn public static void main(String[] args) {nn Scanner scanner = new Scanner(System.in);nn System.out.print(u0022Enter a number: u0022);nn int number = scanner.nextInt();nn int sum = 0;nn while (number u003e 0) {nn int digit = number % 10; // Extract the last digitnn if (isPrimeDigit(digit)) { // Check if the digit is primenn sum += digit; // Add the prime digit to the sumnn }nn number = number / 10; // Remove the last digitnn }nn System.out.println(u0022Sum of prime digits: u0022 + sum);nn scanner.close();nn }nn // Function to check if a digit is primenn public static boolean isPrimeDigit(int digit) {nn return digit == 2 || digit == 3 || digit == 5 || digit == 7;nn }nn}nn// OutputnnEnter a number: 12345nnSum of prime digits: 10nnEnter a number: 7352nnSum of prime digits: 17
Find the sum of the series 1 + 2 + 3 + … + n – Program 21 #
Explanation:
The sum of the series 1+2+3+⋯+n is the total of all integers from 1 to n.
This is a simple arithmetic series where each term increases by 1.
Program:
import java.util.Scanner;nnpublic class SumOfSeries {nn public static void main(String[] args) {nn Scanner scanner = new Scanner(System.in);nn System.out.print(u0022Enter the value of n: u0022);nn int n = scanner.nextInt();nn int sum = n * (n + 1) / 2; // Using the formulann System.out.println(u0022Sum of the series 1 + 2 + 3 + ... + u0022 + n + u0022 is: u0022 + sum);nn scanner.close();nn }nn}nn// output:nnEnter the value of n: 5nnSum of the series 1 + 2 + 3 + ... + 5 is: 15nnEnter the value of n: 10nnSum of the series 1 + 2 + 3 + ... + 10 is: 55