In this article Python programs for practice we give the simple programs, Program to demonstrate slicing, Program to print current date and time, Program to display the Calendar of a given month, etc.

Python programs for practice:

1. Program to display name and address.

# Program to display name and address

# Define the name and address

name = “Pratik Patil”

address = “Kundal, Tal: Palus Dist: Sangli Maharashtra”

# Display the name and address

print(“Name:”)

print(name)

print(“\nAddress:”)

print(address)

Output:

Name:

Pratik Patil

Address:

Kundal, Tal: Palus Dist: Sangli

Maharashtra

// Here’s a Python program that takes the name and address as input from the user at runtime and then displays them:

# Program to display name and address at runtime

# Get the name and address from the user

name = input(“Enter your name: “)

address = input(“Enter your address: “)

# Display the name and address

print(“\nName:”)

print(name)

print(“\nAddress:”)

print(address)

Output:

Enter your name: Yashraj

Enter your address: Palus Tal: Palus Dist: Sangli Maharashtra

Name:

Yashraj

Address:

Palus Tal: Palus Dist: Sangli Maharashtra

2.Program to Accept two number and display addition, subtraction, multiplication, division and modules.

Here’s a Python program that accepts two numbers from the user and displays the results of addition, subtraction, multiplication, division, and modulus:

# Program to perform arithmetic operations on two numbers

# Accept two numbers from the user

num1 = float(input(“Enter the first number: “))

num2 = float(input(“Enter the second number: “))

# Perform arithmetic operations

addition = num1 + num2

subtraction = num1 – num2

multiplication = num1 * num2

division = num1 / num2 if num2 != 0 else “Undefined (division by zero)”

modulus = num1 % num2 if num2 != 0 else “Undefined (modulus by zero)”

# Display the results

print(“\nResults:”)

print(f”Addition: {addition}”)

print(f”Subtraction: {subtraction}”)

print(f”Multiplication: {multiplication}”)

print(f”Division: {division}”)

print(f”Modulus: {modulus}”)

Output:

Enter the first number: 10

Enter the second number: 3

Results:

Addition: 13.0

Subtraction: 7.0

Multiplication: 30.0

Division: 3.3333333333333335

Modulus: 1.0

3. Program to calculate factorial of given number.

# Program to calculate the factorial of a given number

# Function to calculate factorial

def factorial(num):

if num < 0:

return “Factorial is not defined for negative numbers.”

elif num == 0 or num == 1:

return 1

else:

fact = 1

for i in range(1, num + 1):

fact *= i

return fact

# Accept a number from the user

number = int(input(“Enter a number to calculate its factorial: “))

# Calculate and display the factorial

result = factorial(number)

print(f”The factorial of {number} is: {result}”)

Output:

Input:

Enter a number to calculate its factorial: 5

Output:

The factorial of 5 is: 120

4. Program to create a list of 100 numbers and separate those numbers in two different list

one includes odd number other even.

# Program to create a list of 100 numbers and separate into odd and even lists

# Create a list of 100 numbers (1 to 100)

numbers = list(range(1, 101))

# Separate numbers into odd and even lists

odd_numbers = [num for num in numbers if num % 2 != 0]

even_numbers = [num for num in numbers if num % 2 == 0]

# Display the results

print(“Original List of Numbers:”)

print(numbers)

print(“\nOdd Numbers:”)

print(odd_numbers)

print(“\nEven Numbers:”)

print(even_numbers)

Output:

Original List of Numbers:

[1, 2, 3, …, 100]

Odd Numbers:

[1, 3, 5, …, 99]

Even Numbers:

[2, 4, 6, …, 100]

5. Program to display maximum number and minimum number from given list

# Program to find the maximum and minimum numbers in a list

# Accept a list of numbers from the user

numbers = list(map(int, input(“Enter numbers separated by spaces: “).split()))

# Find the maximum and minimum numbers

max_number = max(numbers)

min_number = min(numbers)

# Display the results

print(f”The maximum number in the list is: {max_number}”)

print(f”The minimum number in the list is: {min_number}”)

Input:

Enter numbers separated by spaces: 45 12 78 34 89 23

Output:

The maximum number in the list is: 89

The minimum number in the list is: 12

6. Program to demonstrate slicing.

# Program to demonstrate slicing in Python

# Define a list

numbers = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

# Display the original list

print(“Original List:”, numbers)

# Slicing examples

print(“\nSlicing Examples:”)

print(“First 5 elements:”, numbers[:5])  # From start to the 5th element

print(“Last 5 elements:”, numbers[-5:])  # Last 5 elements

print(“Elements from index 2 to 6:”, numbers[2:7])  # From index 2 to 6

print(“Every 2nd element:”, numbers[::2])  # Every 2nd element

print(“Reversed list:”, numbers[::-1])  # Entire list in reverse order

print(“Elements from index 3 to end:”, numbers[3:])  # From index 3 to end

print(“Elements up to index 4:”, numbers[:4])  # From start to index 4

Example Output

Original List: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Slicing Examples:

First 5 elements: [10, 20, 30, 40, 50]

Last 5 elements: [60, 70, 80, 90, 100]

Elements from index 2 to 6: [30, 40, 50, 60, 70]

Every 2nd element: [10, 30, 50, 70, 90]

Reversed list: [100, 90, 80, 70, 60, 50, 40, 30, 20, 10]

Elements from index 3 to end: [40, 50, 60, 70, 80, 90, 100]

Elements up to index 4: [10, 20, 30, 40]

7. Program to demonstrate set operators (union, intersection, minus)

# Program to demonstrate set operators

# Define two sets

set1 = {1, 2, 3, 4, 5}

set2 = {4, 5, 6, 7, 8}

# Display the original sets

print(“Set 1:”, set1)

print(“Set 2:”, set2)

# Union of sets

union_set = set1 | set2  # or set1.union(set2)

print(“\nUnion of Set 1 and Set 2:”, union_set)

# Intersection of sets

intersection_set = set1 & set2  # or set1.intersection(set2)

print(“Intersection of Set 1 and Set 2:”, intersection_set)

# Difference (Set 1 – Set 2)

difference_set1 = set1 – set2  # or set1.difference(set2)

print(“Difference (Set 1 – Set 2):”, difference_set1)

# Difference (Set 2 – Set 1)

difference_set2 = set2 – set1  # or set2.difference(set1)

print(“Difference (Set 2 – Set 1):”, difference_set2)

Example Output

Set 1: {1, 2, 3, 4, 5}

Set 2: {4, 5, 6, 7, 8}

Union of Set 1 and Set 2: {1, 2, 3, 4, 5, 6, 7, 8}

Intersection of Set 1 and Set 2: {4, 5}

Difference (Set 1 – Set 2): {1, 2, 3}

Difference (Set 2 – Set 1): {6, 7, 8}

8. Program to print current date and time.

# Program to print the current date and time

from datetime import datetime

# Get the current date and time

current_datetime = datetime.now()

# Print the current date and time

print(“Current Date and Time:”, current_datetime)

# Optionally, format the date and time for better readability

formatted_datetime = current_datetime.strftime(“%Y-%m-%d %H:%M:%S”)

print(“Formatted Date and Time:”, formatted_datetime)

Output:

Current Date and Time: 2025-01-03 15:30:45.123456

Formatted Date and Time: 2025-01-03 15:30:45

9. Program to Today’s Year, Month, and Date

# Program to display today’s year, month, and date

from datetime import datetime

# Get today’s date

today = datetime.now().date()

# Extract year, month, and day

year = today.year

month = today.month

day = today.day

# Print year, month, and date

print(f”Today’s Year: {year}”)

print(f”Today’s Month: {month}”)

print(f”Today’s Date: {day}”)

Output

Today’s Year: 2025

Today’s Month: 1

Today’s Date: 3

10. Program to convert Date to String

# Program to convert date to a string

from datetime import datetime

# Example date

date = datetime(2025, 1, 3)

# Convert date to string in different formats

date_str1 = date.strftime(“%Y-%m-%d”)

date_str2 = date.strftime(“%B %d, %Y”)

date_str3 = date.strftime(“%d/%m/%Y”)

# Print formatted date strings

print(f”Date as ‘YYYY-MM-DD’: {date_str1}”)

print(f”Date as ‘Month Day, Year’: {date_str2}”)

print(f”Date as ‘DD/MM/YYYY’: {date_str3}”)

Example Output:

Date as ‘YYYY-MM-DD’: 2025-01-03

Date as ‘Month Day, Year’: January 03, 2025

Date as ‘DD/MM/YYYY’: 03/01/2025

11. Program to display the Calendar of a given month.

# Program to display the calendar of a given month

import calendar

# Input the year and month

year = int(input(“Enter the year: “))

month = int(input(“Enter the month: “))

# Display the calendar

cal = calendar.month(year, month)

print(f”\nCalendar for {calendar.month_name[month]} {year}:\n”)

print(cal)

Input:

Enter the year: 2025

Enter the month: 1

Output:

Calendar for January 2025:

January 2025

Mo Tu We Th Fr Sa Su

1

2  3  4  5  6  7  8

9 10 11 12 13 14 15

16 17 18 19 20 21 22

23 24 25 26 27 28 29

30 31

12. Program to display calendar of the given year.

# Program to display the calendar of a given year

import calendar

# Input the year

year = int(input(“Enter the year: “))

# Display the calendar for the year

cal = calendar.TextCalendar()

cal_content = cal.formatyear(year)

print(f”\nCalendar for {year}:\n”)

print(cal_content)

Example Run

Input:

Enter the year: 2025

Output:

2025

January February March    April     May      June     July      August    September October    November December

Sun Mon Tue Wed Thu Fri Sat   Sun Mon Tue Wed Thu Fri Sat   Sun Mon Tue Wed Thu Fri Sat   Sun Mon Tue Wed Thu Fri Sat   Sun Mon Tue Wed Thu Fri Sat   Sun Mon Tue Wed Thu Fri Sat

1    2    3    4    5                   1    2    3    4    5    6

6    7    8    9   10   11   12     7    8    9   10   11   12   13   14

13   14   15   16   17   18   19    14   15   16   17   18   19   20   21

20   21   22   23   24   25   26    21   22   23   24   25   26   27   28

27   28   29   30   31                          28   29   30   31

Explanation

  1. calendar.TextCalendar():
    • Creates a text-based calendar for the specified year.
  2. Formatting:
    • formatyear() generates the entire year’s calendar in a formatted string.
    • The output shows each month’s calendar with weeks and day names.

This program provides a clear representation of the calendar for the specified year.

13. Program to demonstrate File input.

# Program to demonstrate file input

# Open the file in read mode

with open(‘example.txt’, ‘r’) as file:

# Read the entire content of the file

content = file.read()

# Display the content

print(“File Content:”)

print(content)

Explanation

  1. Opening the File:
    • open(‘example.txt’, ‘r’) opens the file named example.txt in read mode.
  2. Reading the File:
    • file.read() reads the entire content of the file.
  3. Using with open():
    • Ensures the file is properly closed after reading, even if an error occurs during reading.

Example example.txt file content:

Hello, this is a simple text file.

It contains some example content.

You can modify this content as needed.

Output:

File Content:

Hello, this is a simple text file.

It contains some example content.

You can modify this content as needed.

14. Program to demonstrate file output

# Program to demonstrate file output

# Open the file in write mode

with open(‘output.txt’, ‘w’) as file:

# Write content to the file

file.write(“This is a simple text file created using Python.\n”)

file.write(“You can add multiple lines or contents as needed.”)

print(“Data has been written to ‘output.txt’.”)

Explanation

  1. Opening the File:
    • open(‘output.txt’, ‘w’) opens the file output.txt in write mode. If the file does not exist, it creates a new one.
  2. Writing to the File:
    • file.write() writes the specified string to the file.
  3. Using with open():
    • Ensures that the file is properly closed after writing.

Output

Data has been written to ‘output.txt’.

15. Program two add two numbers using GUI.

import tkinter as tk

def add_numbers():

# Get input values

num1 = float(entry1.get())

num2 = float(entry2.get())

# Perform addition

result = num1 + num2

# Display result

result_label.config(text=f”Result: {result}”)

# Create main window

root = tk.Tk()

root.title(“Add Two Numbers”)

# Create labels and entry fields for inputs

label1 = tk.Label(root, text=”Enter first number:”)

label1.pack()

entry1 = tk.Entry(root)

entry1.pack()

label2 = tk.Label(root, text=”Enter second number:”)

label2.pack()

entry2 = tk.Entry(root)

entry2.pack()

# Create a button to perform addition

add_button = tk.Button(root, text=”Add”, command=add_numbers)

add_button.pack()

# Label to display the result

result_label = tk.Label(root, text=””)

result_label.pack()

# Run the application

root.mainloop()

Explanation

  1. Tkinter Elements:
    • Label widgets display text.
    • Entry widgets allow users to input text.
    • Button widgets trigger actions.
  2. Functionality:
    • add_numbers() function retrieves inputs from Entry widgets, performs the addition, and updates the result in a label.
  3. Main Window:
    • root.mainloop() starts the GUI event loop.

Example Run

  • User inputs two numbers, clicks the “Add” button, and sees the result displayed in the Result label.

This program creates a simple GUI where users can input two numbers and get their sum as output.

Some More: 

POP- Introduction to Programming Using ‘C’

DS – Data structure Using C

OOP – Object Oriented Programming 

Java Programming

DBMS – Database Management System

RDBMS – Relational Database Management System

Join Now: Data Warehousing and Data Mining 

Leave a Reply

Your email address will not be published. Required fields are marked *