01. Program to demonstrate different number data types in Python
Python Code
''' Program to demonstrate different number data types '''
# Integers
x = 5
print("x = ", x)
print("The type of x", type(x))
# Floating-Point Numbers
y = 40.5
print("y = ", y)
print("The type of y", type(y))
# Complex Numbers
z = 1+5j
print("z = ", z)
print("The type of z", type(z))
Output
x = 5
The type of x <class 'int'>
y = 40.5
The type of y <class 'float'>
z = (1+5j)
The type of z <class 'complex'>
02. Program to perform different Arithmentic Operations on numbers
Python Code
''' Program to perform different Arithmentic Operations '''
# Taking Input
x = float(input("Enter First Number : "))
y = float(input("Enter Second Number : "))
print("x = ", x)
print("y = ", y)
# Addition (+)
print("1. Addition : ", x + y)
# Substraction (-)
print("2. Substraction : ", x - y)
# Multiplication (*)
print("3. Multiplication : ", x * y)
# Division (/)
print("4. Divide : ", x / y)
# Remainder (%)
print("5. Remainder : ", x % y)
# Exponent (**)
print("6. Exponent : ", x ** y)
# Floor Division (//)
print("7. Floor Division : ", x // y)
Output
Enter First Number : 5
Enter Second Number : 2
x = 5.0
y = 2.0
1. Addition : 7.0
2. Substraction : 3.0
3. Multiplication : 10.0
4. Divide : 2.5
5. Remainder : 1.0
6. Exponent : 25.0
7. Floor Division : 2.0
03. Program to create, concatenate and print a string and accessing
sub-string from a given string
Python Code
''' Program to Create, Concatenate and Print a String
And Accessing Sub-String from given String '''
# Create Strings
str1 = input("Enter the First Name : ")
str2 = input("Enter the Last Name : ")
# Concatenate Strings
concatenated_str = str1 + str2
# Print String
print("Concatenated String : ", concatenated_str)
# Finding String
index1 = concatenated_str.find(str1)
print("First Name found at : ", index1)
index2 = concatenated_str.find(str2)
print("Last Name found at : ", index2)
# Accessing a substring
subStr1 = concatenated_str[index1:index2]
subStr2 = concatenated_str[index2:]
# Print substrings
print("Extracted Substring 1 :", subStr1)
print("Extracted Substring 2 :", subStr2)
Output
Enter the First Name : Yash
Enter the Last Name : Choudhary
Concatenated String : YashChoudhary
First Name found at : 0
Last Name found at : 4
Extracted Substring 1 : Yash
Extracted Substring 2 : Choudhary
04. Program to print the current date in the format “Sun May 29 02:26:23
IST 2025”
Python Code
''' Program to print current date '''
from datetime import datetime
# Current Time
curr_time = datetime.now()
# Printing in the given format
time = curr_time.strftime('%a %b %d %H:%M:%S'+' IST '+ '%Y')
print(time)
Output
Sat Jan 11 22:48:30 IST 2025
05. Program to create, append, and remove lists
Python Code
''' Program to create, append and remove list '''
# Creating Lists
List1 = [1, 'a', 'apple', 1.4, 1+4j]
List2 = [5, 6, 'grapes']
List3 = List1 + List2
print("List1 : ", List1)
print("List2 : ", List2)
print("List3 : ", List3)
# Initialize an empty list
List = []
while True:
choice = int(
input(
"\nEnter Choice: \n1. Create a New List\n"
"2. Append an Element\n"
"3. Remove an Element by Value\n"
"4. Remove an Element by Index\n"
"5. Display the List\n"
"0. Exit\n=>"
)
)
if choice == 1:
# Create a new list
elements = input("Enter elements separated by space: ").split()
List = list(map(int, elements))
print("New List: ", List)
elif choice == 2:
# Append an Element
element = int(input("Enter an Element: "))
List.append(element)
print(f"{element} appended to the list.")
elif choice == 3:
# Remove an Element by Value
try:
value = int(input("Enter the value: "))
List.remove(value)
print(f"{value} removed from the list.")
except ValueError:
print("Value not found...")
elif choice == 4:
# Remove an Element by Index
try:
index = int(input("Enter the index: "))
removed_ele = List.pop(index)
print(f"Element {removed_ele} removed from index {index}.")
except IndexError:
print("Invalid Index!!")
elif choice == 5:
# Display the List
print("List: ", List)
elif choice == 0:
# Exit
print("Exiting...")
break
else:
print("Invalid Choice!!!")
Output
List1 : [1, 'a', 'apple', 1.4, (1+4j)]
List2 : [5, 6, 'grapes']
List3 : [1, 'a', 'apple', 1.4, (1+4j), 5, 6, 'grapes']
Enter Choice:
1. Create a New List
2. Append an Element
3. Remove an Element by Value
4. Remove an Element by Index
5. Display the List
0. Exit
=>1
Enter elements separated by space: 1 2 3 4
New List: [1, 2, 3, 4]
Enter Choice:
1. Create a New List
2. Append an Element
3. Remove an Element by Value
4. Remove an Element by Index
5. Display the List
0. Exit
=>2
Enter an Element: 5
5 appended to the list.
Enter Choice:
1. Create a New List
2. Append an Element
3. Remove an Element by Value
4. Remove an Element by Index
5. Display the List
0. Exit
=>3
Enter the value: 3
3 removed from the list.
Enter Choice:
1. Create a New List
2. Append an Element
3. Remove an Element by Value
4. Remove an Element by Index
5. Display the List
0. Exit
=>4
Enter the index: 1
Element 2 removed from index 1.
Enter Choice:
1. Create a New List
2. Append an Element
3. Remove an Element by Value
4. Remove an Element by Index
5. Display the List
0. Exit
=>5
List: [1, 4, 5]
Enter Choice:
1. Create a New List
2. Append an Element
3. Remove an Element by Value
4. Remove an Element by Index
5. Display the List
0. Exit
=>0
Exiting...
06. Program to demonstrate working with tuples
Python Code
''' Working with tuples '''
# 1. Creating a Tuple
Tuple = (1, 2, 3, 4, 5, 6)
print("Tuple: ", Tuple)
# with the use of Strings
Tuple = ('Vijay', 'Vivek', 'Vikas')
print("Tuple with the use of Strings: ", Tuple)
# with the use of List
List = [1, 2, 3, 4, 5, 6]
Tuple = tuple(List)
print("Tuple using List: ", Tuple)
# 2. Iterating Through a Tuple
print("Iterating through the Tuple: ")
for i in Tuple:
print(i, end =" ")
print()
# 3. Accessing Elements
print("First Element: ", Tuple[0])
print("Last Element: ", Tuple[-1])
# 4. Slicing a Tuple
print("Slice Tuple (index 1 to 3): ", Tuple[1:4])
# 5. Checking Membership
print("Is 3 in the tuple? ", 3 in Tuple)
print("Is 10 in the tuple? ", 10 in Tuple)
# 6. Tuple Length
print("Length of the Tuple: ", len(Tuple))
# 7. Tuple Index
print("Index of element 3: ", Tuple.index(3))
# 8. Unpacking Tuples
a, b, c, d, e, f = Tuple
print("Unpacked Values: ", a, b, c, d, e, f)
# 9. Immutable Nature
try:
Tuple[0] = 10
except TypeError:
print("Error: Tuples are immutable!")
# 10. Concatenating Tuples
new_Tuple = Tuple + (6, 7, 8)
print("Concatenated Tuple: ", new_Tuple)
print("Count of element 6: ", new_Tuple.count(6)) # counts the repeatation of 6
# 11. Repeating Tuples
rep_Tuple = Tuple * 2
print("Repeated Tuple: ", rep_Tuple)
# 12. Nested Tuples
nested_tuple = (1, (2, 3), (4, 5, 6))
print("Nested Tuple: ", nested_tuple)
print("Access Nested Element (4):", nested_tuple[2][0])
# 13. Tuple with Different Types
mix_Tuple = (10, "Python", 3.14, True)
print("Mixed Tuple: ", mix_Tuple)
Output
Tuple: (1, 2, 3, 4, 5, 6)
Tuple with the use of Strings: ('Vijay', 'Vivek', 'Vikas')
Tuple using List: (1, 2, 3, 4, 5, 6)
Iterating through the Tuple:
1 2 3 4 5 6
First Element: 1
Last Element: 6
Slice Tuple (index 1 to 3): (2, 3, 4)
Is 3 in the tuple? True
Is 10 in the tuple? False
Length of the Tuple: 6
Index of element 3: 2
Unpacked Values: 1 2 3 4 5 6
Error: Tuples are immutable!
Concatenated Tuple: (1, 2, 3, 4, 5, 6, 6, 7, 8)
Count of element 6: 2
Repeated Tuple: (1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6)
Nested Tuple: (1, (2, 3), (4, 5, 6))
Access Nested Element (4): 4
Mixed Tuple: (10, 'Python', 3.14, True)
07. Program to demonstrate working with dictionaries in python.
Python Code
''' Working with Dictionaries '''
# 1. Creating a Dictionary
Dict = {
"name": "Vijay",
"age": 20,
"city": "Pune"
}
print("Dictionary: ", Dict)
# 2. Accessing Values
print("Name: ", Dict["name"]) # Using Key
print("Age: ", Dict.get("age")) # Using get() method
# 3. Adding a New Key-Value Pair
Dict["profession"] = "Developer"
print("After Adding 'profession': \n", Dict)
# 4. Updating Values
Dict["age"] = 21
Dict.update({"city" : "Delhi"}) # Using update() method
print("After updating 'age' & 'city': \n", Dict)
# 5. Removing a Key-Value Pair
rem_value = Dict.pop("city")
print("After Removing 'city':\n", Dict)
print("Removed : ", rem_value)
# 6. Remove Last Item
l_item = Dict.popitem() # Using popitem() method
print("After popitem() :\n", Dict)
print("Last Item Removed : ", l_item)
# 7. Iterating over a dictionary
print("Keys: ")
for key in Dict:
print(key, end=" ")
print("\nValues: ")
for value in Dict.values():
print(value, end=" ")
print("\nKey-Value Pairs:")
for key, value in Dict.items():
print(f"{key} : {value}")
# 8. Dictionary Length
print("Length of Dictionary: ", len(Dict))
# 9. Checking if a key Exists
print("Is 'name' in dictionary? ", "name" in Dict)
print("Is 'city' in dictionary? ", "city" in Dict)
# 10. Copy a Dictionary
Dict1 = Dict.copy()
print("New Copied Dictionary: \n", Dict1)
# 11. Clearing a Dictionary
Dict.clear()
print("After Clearing: \n", Dict)
# 12. Creating a Dictionary using dict() Constructor
new_dict = dict(country="India", state="M.P.", city="Indore", pin=452001)
print("Dictionary using dict():\n", new_dict)
# 13. Nested Dictionary
nested_dict = {
"person1" : {"name": "Sneh", "age": 20},
"person2" : {"name": "Sunny", "age": 25}
}
print("Nested Dictionary:\n", nested_dict)
print("Accessing Nested Value (person1's name): ", nested_dict["person1"]["name"])
# Dictionary with Comprehension
Dict2 = {x : x**2 for x in [1, 2, 3, 4, 5]}
print("Dictionary with Comprehension:\n", Dict2)
Output
Dictionary: {'name': 'Vijay', 'age': 20, 'city': 'Pune'}
Name: Vijay
Age: 20
After Adding 'profession':
{'name': 'Vijay', 'age': 20, 'city': 'Pune', 'profession': 'Developer'}
After updating 'age' & 'city':
{'name': 'Vijay', 'age': 21, 'city': 'Delhi', 'profession': 'Developer'}
After Removing 'city':
{'name': 'Vijay', 'age': 21, 'profession': 'Developer'}
Removed : Delhi
After popitem() :
{'name': 'Vijay', 'age': 21}
Last Item Removed : ('profession', 'Developer')
Keys:
name age
Values:
Vijay 21
Key-Value Pairs:
name : Vijay
age : 21
Length of Dictionary: 2
Is 'name' in dictionary? True
Is 'city' in dictionary? False
New Copied Dictionary:
{'name': 'Vijay', 'age': 21}
After Clearing:
{}
Dictionary using dict():
{'country': 'India', 'state': 'M.P.', 'city': 'Indore', 'pin': 452001}
Nested Dictionary:
{'person1': {'name': 'Sneh', 'age': 20}, 'person2': {'name': 'Sunny', 'age': 25}}
Accessing Nested Value (person1's name): Sneh
Dictionary with Comprehension:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
08. Program to find Largest of three numbers.
Python Code
''' Program to find Largest of three numbers '''
# Input 3 No's
num1 = float(input("Enter First Number: "))
num2 = float(input("Enter Second Number: "))
num3 = float(input("Enter Third Number: "))
# Largest Number
if num1 >= num2 and num1 >= num3:
largest = num1
elif num2 >= num1 and num2 >= num3:
largest = num2
else:
largest = num3
# Display the largest number
print("The largest number is: ", largest)
Output
Enter First Number: 55
Enter Second Number: 31
Enter Third Number: 70
The largest number is: 70.0
09. Python program to construct the following pattern, using a nested for
loop
#
# #
# # #
# # # #
Python Code
''' Pattern of # '''
# No. of rows for the pattern
n = 4
# Using Nested for-loop
for i in range(1, n + 1): # Outer loop for changing the line
for j in range(i): # Inner loop for printing # in a line
print("#", end = " ")
print()
Output
#
# #
# # #
# # # #
10. Program to print prime numbers less than 20
Python Code
''' Program to print prime numbers less than 20 '''
# Function to check if a number is prime
def is_prime(num):
if num < 2:
return False
for i in range(2, num):
if num % i == 0:
return False
return True
# Printing prime no's less than 20
print("Prime numbers less than 20:")
for n in range(2, 20):
if is_prime(n):
print(n, end = " ")
Output
Prime numbers less than 20:
2 3 5 7 11 13 17 19
11. Program to define a module to find Fibonacci Numbers and import the
module to another program.
Python Code : fibonacci.py
''' Fibonacci module fibonacci.py '''
def generate_fibo(n):
if n <= 0:
return []
elif n == 1:
return [0]
elif n == 2:
return [0, 1]
fib_series = [0, 1]
for i in range(2, n):
next_num = fib_series[-1] + fib_series[-2]
fib_series.append(next_num)
return fib_series
Python Code : main.py
''' import fibonacci module in main.py '''
import fibonacci
# input no. of terms
num = int(input("Enter no. of terms: "))
# Using the module function generate_fibo
fibo_sequence = fibonacci.generate_fibo(num)
# Display the Fibonacci Series
print("Fibonacci Sequence: \n", fibo_sequence)
Output
Enter no. of terms: 10
Fibonacci Sequence:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]
12. Program to define a module and import a specific function in that
module to another program
Python Code : math_operations.py
''' math_operations.py '''
def add(a, b):
# Return the sum of two no's
return a + b
def subtract(a, b):
# Return the difference of two no's
return a - b
def multiply(a, b):
# Return the product of two no's
return a * b
def divide(a, b):
# Return the quotient of two no's
if b != 0:
return a / b
else:
return "Division by zero is not allowed!!!"
Python Code : main.py
# main.py
''' import the multiply function from the module math_operations.py '''
from math_operations import multiply
# Input two no's
num1 = int(input("Enter First No.: "))
num2 = int(input("Enter Second No.: "))
# Use the imported function
result = multiply(num1, num2)
# Display the result
print(f"The product of {num1} and {num2} is : {result}")
# print("And Addition : ", add(num1, num2))
# Gives NameError: name 'add' is not defined
Output
Enter First No.: 5
Enter Second No.: 6
The product of 5 and 6 is : 30
13. Program that inputs a text file and prints all of the unique words in
the file in alphabetical order
Python Code
''' Program to input a text file and print all of the unique words alphabetically '''
# Input the file name
file_name = input("Enter File Name (with extension): ")
lst = list() # list for the unique sorted words
try:
# Open and read the file
with open(file_name, 'r') as file:
# Read all the text and split into words
text = file.read()
words = text.split()
# lower words
lower_words = [word.lower() for word in words]
lower_words.sort()
# display the sorted words
print("The unique words in alphabetical order are:")
for word in lower_words:
if word in lst: # if element is repeated
continue # do nothing
else: # else if element is not in the list
lst.append(word)
print(word)
except FileNotFoundError:
print("File not found!!")
Text File : sample.txt
Hello World
Welcome to the world of python
Python is great for programming
Programming is fun
Output
Enter File Name (with extension): sample.txt
The unique words in alphabetical order are:
for
fun
great
hello
is
of
programming
python
the
to
welcome
world
14. Write a Python class to convert an integer to a roman numeral
Python Code
''' Python Class to convert an integer to a roman '''
class RomanConverter:
def int_to_roman(self, num):
if not 1 <= num <= 3999:
return "Number Out of Range(1-3999)!"
roman_numerals = [
(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'),
(100, 'C'), (90, 'XC'), (50, 'L'), (40, 'XL'), (10, 'X'),
(9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')
]
result = ""
for value, symbol in roman_numerals:
while num >= value:
result += symbol
num -= value
return result
# Input from the user
try:
print(":::Integer to Roman Conversion:::")
number = int(input("Enter an Integer: "))
print("Roman : ", RomanConverter().int_to_roman(number))
except ValueError:
print("Invalid Input!!!")
Output
:::Integer to Roman Conversion:::
Enter an Integer: 1234
Roman : MCCXXXIV
:::Integer to Roman Conversion:::
Enter an Integer: 123
Roman : CXXIII
15. Write a Python class to reverse a string word by word
Python Code
''' Class to reverse a string word by word '''
class StringReverser:
def reverse_words(self, str):
return ' '.join(reversed(str.split()))
# Input from the User
input_str = input("Enter a string: ")
# Reverse the string using the class
reversed_str = StringReverser().reverse_words(input_str)
# Printing the reversed string
print(f"Reversed String: {reversed_str}")
Output
Enter a string: Welcome to the world of Python
Reversed String: Python of world the to Welcome
Computer Graphics with C Examples 01. Program for drawing line using DDA line drawing method. C Code /* DDA - Digital Differential Analyzer (DDA) algorithm is an incremental scan conversion method of line drawing. DDA is used for linear interpolation of variables ovar an interval between start and end point. It is used for rasterization of lines, triangles and polygons. */ // Drawing a line using DDA Algorithm #include<stdio.h> #include<conio.h> #include<graphics.h> #include<math.h> int main(){ int x1, y1, x2, y2, i; float x, y, dx, dy, length; int gd = DETECT, gm; // Initialise Graphics mode detectgraph(&gd, &gm); initgraph(&gd, &gm, "C:\\TURBOC3\\BGI"); // Step 1 : Read two end points P1(x1, y1) and P2(x2, y2) printf(" Enter First Point : "); scanf("%d%d", &x1, &y1); printf(" Enter Second Point : "); scanf("%d%d", &x2, ...
Data Communication and Computer Networks (Major-I) : BCAII DAVV - Devi Ahilya Vishwavidyalaya Indore (M.P.) July - August 2023 B.C.A. II Year (4 Y. D. C.) Examination DATA COMMUNICATION AND COMPUTER NETWORKS Major - I Time : 3 Hours] Max. Marks : 70 Min. Marks : 25] Section A : Objective Questions [6 x 1 = 6] 1. Network Topology, जो सभी Nodes को एक रेखीय तरीके से जोड़ती है : Which network topology connects all nodes in a linear fashion : Bus Star Ring Mesh 2. किस संचार माध्यम की Bandwidth सबसे अधिक है : Which transmission media has the highest bandwidth : Twisted Pair Coaxial Cable Fiber Optics Radio Waves 3. LAN और WAN के बीच मुख्य अंतर है : What is the main difference between LAN and WAN : Physical Size Speed of Transmission Cost Security 4. Ph...
Python Programming Examples 01. Program to demonstrate different number data types in Python Python Code ''' Program to demonstrate different number data types ''' # Integers x = 5 print("x = ", x) print("The type of x", type(x)) # Floating-Point Numbers y = 40.5 print("y = ", y) print("The type of y", type(y)) # Complex Numbers z = 1+5j print("z = ", z) print("The type of z", type(z)) Copy Output x = 5 The type of x <class 'int'> y = 40.5 The type of y <class 'float'> z = (1+5j) The type of z <class 'complex'> 02. Program to perform different Arithmentic Operations on numbers Python Code ''' Program to perform different Arithmentic Operations ''' # Taking Input x = float(input("Enter First Number : ...
Comments
Post a Comment