15 simple programs that demonstrate basic programming concepts:
Hello World
print("Hello, World!")
Add Two Numbers
a = 5
b = 3
sum = a + b
print("Sum:", sum)
Find Square of a Number
number = 4
square = number ** 2
print("Square:", square)
Swap Two Variables
a = 5
b = 3
a, b = b, a
print("a:", a, "b:", b)
Check if Number is Even or Odd
number = 7
if number % 2 == 0:
print("Even")
else:
print("Odd")
Find Factorial of a Number
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print("Factorial:", factorial(5))
Generate Fibonacci Sequence
def fibonacci(n):
a, b = 0, 1
for n in range(n):
print(a, end=' ')
a, b = b, a + b
fibonacci(10)
Check if a Number is Prime
def is_prime(n):
if n <= 1:
return False
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
print("Prime:", is_prime(17))
Find Largest of Three Numbers
a, b, c = 10, 14, 12
largest = max(a, b, c)
print("Largest:", largest)
Calculate Sum of Digits
number = 1234
sum_of_digits = sum(int(digit) for digit in str(number))
print("Sum of digits:", sum_of_digits)
Reverse a String
string = " "
reversed_string = string[::-1]
print("Reversed string:", reversed_string)
Check if a String is a Palindrome
string = "madam"
is_palindrome = string == string[::-1]
print("Is palindrome:", is_palindrome)
Generate Random Number
import random
random_number = [Link](1, 100)
print("Random number:", random_number)
Convert Celsius to Fahrenheit
celsius = 25
fahrenheit = (celsius * 9/5) + 32
print("Fahrenheit:", fahrenheit)
Find Length of a List
my_list = [1, 2, 3, 4, 5]
length = len(my_list)
print("Length:", length)
Here are 15 basic programs that take input from the user:
1. Add Two Numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
sum = num1 + num2
print("Sum:", sum)
2. Multiply Two Numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
product = num1 * num2
print("Product:", product)
3. Check if a Number is Even or Odd
number = int(input("Enter a number: "))
if number % 2 == 0:
print("Even")
else:
print("Odd")
4. Calculate the Area of a Circle
import math
radius = float(input("Enter the radius of the circle: "))
area = [Link] * radius ** 2
print("Area of the circle:", area)
5. Check if a Year is 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")
6. Generate Fibonacci Sequence Up to N Terms
n = int(input("Enter the number of terms: "))
a, b = 0, 1
print("Fibonacci sequence:")
for _ in range(n):
print(a, end=' ')
a, b = b, a + b
7. Check if a Number is Prime
num = int(input("Enter a number: "))
if num > 1:
for i in range(2, int(num**0.5) + 1):
if (num % i) == 0:
print(num, "is not a prime number")
break
else:
print(num, "is a prime number")
else:
print(num, "is not a prime number")
8. Calculate Factorial of a Number
num = int(input("Enter a number: "))
factorial = 1
if num < 0:
print("Factorial does not exist for negative numbers")
elif num == 0:
print("Factorial of 0 is 1")
else:
for i in range(1, num + 1):
factorial *= i
print("Factorial of", num, ":", factorial)
9. Reverse a String
string = input("Enter a string: ")
reversed_string = string[::-1]
print("Reversed string:", reversed_string)
10. Check if a String is Palindrome
string = input("Enter a string: ")
if string == string[::-1]:
print("Palindrome")
else:
print("Not a Palindrome")
11. Calculate Simple Interest
principal = float(input("Enter principal amount: "))
rate = float(input("Enter annual interest rate (%): "))
time = float(input("Enter time period in years: "))
simple_interest = (principal * rate * time) / 100
print("Simple Interest:", simple_interest)
12. Convert Celsius to Fahrenheit
celsius = float(input("Enter temperature in Celsius: "))
fahrenheit = (celsius * 9/5) + 32
print("Temperature in Fahrenheit:", fahrenheit)
13. Find the Largest Among Three Numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
largest = max(num1, num2, num3)
print("Largest number:", largest)
14. Check if a Character is Vowel or Consonant
char = input("Enter a character: ")[0].lower()
if char in 'aeiou':
print("Vowel")
else:
print("Consonant")
15. Print Multiplication Table of a Number
num = int(input("Enter a number: "))
print(f"Multiplication Table of {num}:")
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
10 programs that demonstrate the use of control structures, including if-else
statements, if-elif-else conditions, and nested if statements, with input
taken from the user:
1. Check if a Number is Positive, Negative, or Zero
num = float(input("Enter a number: "))
if num > 0:
print("Positive")
elif num == 0:
print("Zero")
else:
print("Negative")
2. Find the Largest of Three Numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
if num1 >= num2 and num1 >= num3:
largest = num1
elif num2 >= num1 and num2 >= num3:
largest = num2
else:
largest = num3
print("Largest number:", largest)
3. Check if a Year is 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")
4. Determine the Grade Based on Marks
marks = float(input("Enter marks: "))
if marks >= 90:
grade = 'A'
elif marks >= 80:
grade = 'B'
elif marks >= 70:
grade = 'C'
elif marks >= 60:
grade = 'D'
else:
grade = 'F'
print("Grade:", grade)
5. Check if a Number is Even or Odd
num = int(input("Enter a number: "))
if num % 2 == 0:
print("Even")
else:
print("Odd")
6. Determine Age Category
age = int(input("Enter age: "))
if age < 13:
category = "Child"
elif age < 20:
category = "Teenager"
elif age < 65:
category = "Adult"
else:
category = "Senior"
print("Age category:", category)
7. Nested if Statements to Find the Largest of Three Numbers
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
num3 = float(input("Enter third number: "))
if num1 >= num2:
if num1 >= num3:
largest = num1
else:
largest = num3
else:
if num2 >= num3:
largest = num2
else:
largest = num3
print("Largest number:", largest)
8. Check if a Number is Divisible by Both 3 and 5
num = int(input("Enter a number: "))
if num % 3 == 0 and num % 5 == 0:
print(f"{num} is divisible by both 3 and 5")
else:
print(f"{num} is not divisible by both 3 and 5")
9. Determine the Type of Triangle Based on Sides
a = float(input("Enter length of side a: "))
b = float(input("Enter length of side b: "))
c = float(input("Enter length of side c: "))
if a == b == c:
triangle_type = "Equilateral"
elif a == b or b == c or a == c:
triangle_type = "Isosceles"
else:
triangle_type = "Scalene"
print("Triangle type:", triangle_type)
10. Check if a Character is a Vowel or Consonant
char = input("Enter a character: ").lower()
if char in 'aeiou':
print(f"{char} is a vowel")
else:
print(f"{char} is a consonant")
5 programs that use for loops and take input from the user:
1. Print Numbers from 1 to N
n = int(input("Enter a number: "))
for i in range(1, n + 1):
print(i)
2. Calculate the Sum of N Numbers
n = int(input("How many numbers do you want to sum? "))
total_sum = 0
for i in range(n):
num = float(input(f"Enter number {i+1}: "))
total_sum += num
print("Sum:", total_sum)
3. Print Multiplication Table of a Number
num = int(input("Enter a number: "))
print(f"Multiplication Table of {num}:")
for i in range(1, 11):
print(f"{num} x {i} = {num * i}")
4. Check if a Number is Prime
num = int(input("Enter a number: "))
is_prime = True
if num > 1:
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
is_prime = False
break
else:
is_prime = False
if is_prime:
print(f"{num} is a prime number")
else:
print(f"{num} is not a prime number")
5. Calculate Factorial of a Number
num = int(input("Enter a number: "))
factorial = 1
if num < 0:
print("Factorial does not exist for negative numbers")
elif num == 0:
print("Factorial of 0 is 1")
else:
for i in range(1, num + 1):
factorial *= i
print(f"Factorial of {num}: {factorial}")
5 programs that use while loops and take input from the user:
1. Print Numbers from 1 to N
n = int(input("Enter a number: "))
i = 1
while i <= n:
print(i)
i += 1
2. Calculate the Sum of N Numbers
n = int(input("How many numbers do you want to sum? "))
total_sum = 0
count = 1
while count <= n:
num = float(input(f"Enter number {count}: "))
total_sum += num
count += 1
print("Sum:", total_sum)
3. Reverse a Number
number = int(input("Enter a number: "))
reversed_number = 0
while number > 0:
digit = number % 10
reversed_number = reversed_number * 10 + digit
number //= 10
print("Reversed Number:", reversed_number)
4. Find Factorial of a Number
num = int(input("Enter a number: "))
factorial = 1
i = 1
while i <= num:
factorial *= i
i += 1
print(f"Factorial of {num}: {factorial}")
5. Check if a Number is Prime
num = int(input("Enter a number: "))
is_prime = True
if num > 1:
i = 2
while i <= num**0.5:
if num % i == 0:
is_prime = False
break
i += 1
else:
is_prime = False
if is_prime:
print(f"{num} is a prime number")
else:
print(f"{num} is not a prime number")
Here's a simple calculator program in that takes input
from the user:
# Function to add two numbers
def add(x, y):
return x + y
# Function to subtract two numbers
def subtract(x, y):
return x - y
# Function to multiply two numbers
def multiply(x, y):
return x * y
# Function to divide two numbers
def divide(x, y):
return x / y
# Display calculator operations
print("Select operation:")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
# Take input from the user
choice = input("Enter choice (1/2/3/4): ")
# Check if choice is one of the four options
if choice in ('1', '2', '3', '4'):
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
if choice == '1':
print(num1, "+", num2, "=", add(num1, num2))
elif choice == '2':
print(num1, "-", num2, "=", subtract(num1, num2))
elif choice == '3':
print(num1, "*", num2, "=", multiply(num1, num2))
elif choice == '4':
if num2 == 0:
print("Error! Division by zero is not allowed.")
else:
print(num1, "/", num2, "=", divide(num1, num2))
else:
print("Invalid input")
To create a graphical calculator in that takes input from the user and displays
the output using graphics, we can use the tkinter library, which is a standard GUI
toolkit in . Here's a basic example of a calculator using tkinter:
import tkinter as tk
from tkinter import messagebox
# Function to evaluate the expression
def evaluate_expression():
try:
result = eval([Link]()) # Evaluate the expression entered by the user
[Link](0, [Link]) # Clear the input field
[Link]([Link], str(result)) # Display the result
except Exception as e:
[Link]("Error", f"Invalid input: {e}")
# Function to add characters to the input field
def add_to_input(char):
[Link]([Link], char)
# Create the main window
root = [Link]()
[Link]("Simple Calculator")
# Create a text entry field
entry = [Link](root, width=30, font=('Arial', 14))
[Link](row=0, column=0, columnspan=4, padx=10, pady=10)
# Define buttons for numbers and operations
buttons = [
('7', 1, 0), ('8', 1, 1), ('9', 1, 2), ('/', 1, 3),
('4', 2, 0), ('5', 2, 1), ('6', 2, 2), ('*', 2, 3),
('1', 3, 0), ('2', 3, 1), ('3', 3, 2), ('-', 3, 3),
('0', 4, 0), ('.', 4, 1), ('=', 4, 2), ('+', 4, 3),
]
# Create buttons and place them in the grid
for button_text, row, col in buttons:
button = [Link](root, text=button_text, width=5, height=2,
font=('Arial', 12),
command=lambda char=button_text: add_to_input(char))
[Link](row=row, column=col, padx=5, pady=5)
# Bind the Enter key to evaluate the expression
[Link]('<Return>', lambda event: evaluate_expression())
# Run the main loop
[Link]()
Here are two example programs in Python that perform operations on strings.
Program 1: Count the Occurrences of Each Character in a String
This program defines a function to count the occurrences of each character in a given string and then
prints the counts.
python
Copy code
def count_characters(s):
"""Count the occurrences of each character in the string s."""
counts = {}
for char in s:
if char in counts:
counts[char] += 1
else:
counts[char] = 1
return counts
# Get user input
string = input("Enter a string: ")
# Count and print the occurrences of each character
character_counts = count_characters(string)
print("Character counts:")
for char, count in character_counts.items():
print(f"{char}: {count}")
Program 2: Reverse Each Word in a String
This program defines a function to reverse each word in a given string while keeping the words in the
same order, and then prints the modified string.
python
Copy code
def reverse_words(s):
"""Reverse each word in the string s while keeping the words in the same
order."""
words = [Link]()
reversed_words = [word[::-1] for word in words]
return " ".join(reversed_words)
# Get user input
string = input("Enter a string: ")
# Reverse each word and print the result
reversed_string = reverse_words(string)
print("String with reversed words:")
print(reversed_string)
Explanation
Program 1: Count the Occurrences of Each Character in a String
1. Function Definition:
• count_characters(s) counts the occurrences of each character in the string s.
• It initializes an empty dictionary counts.
• It iterates through each character in the string. If the character is already in the
dictionary, it increments its count. If not, it adds the character to the dictionary with a
count of 1.
• The function returns the dictionary containing the character counts.
2. Main Program:
• The user is prompted to enter a string.
• The program calls the count_characters function with the user-provided string
and prints the character counts.
Program 2: Reverse Each Word in a String
1. Function Definition:
• reverse_words(s) reverses each word in the string s while keeping the words in
the same order.
• It splits the string into a list of words using split().
• It uses a list comprehension to reverse each word in the list.
• It joins the reversed words back into a single string with spaces in between and returns
the resulting string.
2. Main Program:
• The user is prompted to enter a string.
• The program calls the reverse_words function with the user-provided string and
prints the modified string with each word reversed.