0% found this document useful (0 votes)
18 views39 pages

C& Python Lab Manual

Uploaded by

farooq9345
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views39 pages

C& Python Lab Manual

Uploaded by

farooq9345
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 39

ER.

PERUMAL MANIMEKALAI POLYTECHNIC


COLLEGE, HOSUR – 637117
(An ISO 9001: 2015 Certified Institutions)

C AND PYTHON PROGRAMMING


(For Electronics (Robotics) Engineering)

2023 Regulation

II YEAR /III SEMESTER

Prepared by

SUGASHINI.P .M.E,
Safety Rules
1. 💻 Handle Equipment with Care
o Do not bang on the keyboard or mouse.
o Avoid moving or tilting monitors or CPU units.
o Use gentle touches when handling devices.
2. ⚡ Electrical Safety
o Do not touch power cables, sockets, or wires with wet hands.
o Avoid overloading power outlets with multiple devices.
o Report any exposed wires or faulty equipment immediately.
3. 🛡️ Data and Privacy Protection
o Do not share your passwords or personal information.
o Log out from your account after use.
o Avoid downloading unauthorized or unknown files.
4. 🚫 Food and Drinks Prohibited
o Do not bring food or beverages near the computers.
o Spills can damage hardware and cause electric shocks.
5. ️ Proper Posture and Ergonomics
o Sit with a straight back and adjust the chair height properly.
o Keep a comfortable distance from the monitor (about 20 inches).
o Take regular breaks to prevent eye strain.
6. 🔥 Fire Safety
o Know the location of fire extinguishers.
o Do not attempt to repair electrical issues yourself—report them.
o In case of fire, leave the lab immediately and call for help.
7. 📚 Follow Lab Rules and Instructions
o Always listen to the lab instructor or technician.
o Do not install or uninstall software without permission.
o Use the equipment for educational purposes only.
8. 🌐 Internet Safety
o Avoid visiting suspicious or inappropriate websites.
o Do not download unknown software or open suspicious emails.
o Use only authorized and legal resources.
9. 🚷 No Unauthorized Access
o Do not access or modify other users' files.
o Only authorized personnel should access the server room.
10. ️ Maintain Cleanliness
 Keep the area around the workstation tidy.
 Dispose of waste properly and keep the lab clutter-free.
ER. PERUMAL MANIMEKALAI POLYTECHNIC
COLLEGE, HOSUR
VISION OF THE COLLEGE

PMC Tech Polytechnic College shall emerge as a premier Institute for valued added
technical education coupled with Innovation, Incubation, Ethics and Professional values

MISSION OF THE COLLEGE

1. To foster the professional competence through excellence in teaching and learning.


2. To nurture overall development of students by providing Quality Education &
Training.
3. To provide innovative environment to learn, innovate and create new ideas for the
betterment of oneself and society.

C AND PYTHON PROGRAMMING


(For Electronics (Robotics) Engineering)

2023 Regulation

II YEAR /III SEMESTER

Prepared by
P.SUGASHINI M.E. Lecturer
Department of E-Robotics
Er. Perumal Manimekalai Polytechnic College.
Hosur- 635117
DO'S AND DON'TS IN THE LAB
Do’s

1. Use the lab for its intended purpose: Only work on educational or
authorized activities.
2. Handle equipment carefully: Use the mouse, keyboard, and other
peripherals gently.
3. Keep food and drinks away: To prevent spills and damage.
4. Maintain cleanliness: Keep the workstation tidy and dispose of waste
properly.
5. Save your work frequently: To avoid losing progress due to unexpected
issues.
6. Log out properly: Ensure you sign out of your account when done.
7. Follow the lab rules: Adhere to all lab-specific regulations or guidelines.
8. Ask for help when needed: If you experience issues, inform the lab
supervisor or IT staff.
9. Use authorized software: Only use programs that are approved and installed
by the institution.
10. Respect others: Keep noise levels low and avoid disturbing others.

Don’ts

1. Don’t bring food or drinks: They can cause damage if spilled.


2. Don’t run or play rough: To avoid accidents or equipment damage.
3. Don’t tamper with hardware or software: Avoid unplugging cables,
modifying system settings, or installing unauthorized software.
4. Don’t share your login credentials: Keep your username and password
confidential.
5. Don’t access inappropriate content: Stay away from non-educational or
prohibited websites.
6. Don’t hog resources: Be mindful of time limits if others are waiting.
7. Don’t remove lab equipment: Headphones, keyboards, or other accessories
should stay in the lab.
8. Don’t print excessively: Conserve paper and only print when necessary.
9. Don’t download unknown files: This may introduce viruses or malware.
10. Don’t engage in gaming or social media (if not allowed): Respect the lab’s
rules on usage.

4
Vision of the Department
To develop Electronics Robotics Engineering diploma holders to meet the growing needs
of industry and society.

Mission of the Department

Provide goal-oriented, quality-based and value-added education through state of


M1
art teaching & training method.
To provide Environment to promote practical knowledge on Robotics to meet the
M2
needs of the Industry and society
To provide a platform to learn leadership, ethics and entrepreneurship experience
M3
among students for their sustained growth.

M4 Prepare students to go for lifelong learning for betterment of oneself.

Program Educational Objectives (PEO’s)

Core Competence: Our students will exhibit the knowledge in Mathematics,


PEO 1 fundamentals of Mechanical, Electrical, Electronics and Computer Engineering
to solve Engineering problems in robotics

Breadth: Our students will be able to design and create novel products and
PEO 2 solutions for real life problems using the knowledge of Scientific, Mechanical,
Electronics and Computer Engineering.

Professionalism: Our students exhibit professional and ethical attitude,


PEO 3 effective communication skills and exhibit teamwork over multidisciplinary
areas.

Higher studies and Employability: Our students succeed in industry /


PEO 4 technical profession by creating an environment excellence and a high order of
ethics and a zeal for lifelong learning.

5
PROGRAMME OUTCOMES

Basic and Discipline specific knowledge: Apply knowledge of basic


PO1 mathematics, science and engineering fundamentals and engineering
Specialization to solve the engineering problems.
Problem analysis: Identify and analyse well-defined engineering problems
PO2
Using codified standard methods.
Deign/ development of solutions: Design solutions for well-defined technical
PO3 Problems and assist with the design of systems components or processes to meet
specified needs.
Engineering Tools, Experimentation and Testing: Apply modern
PO4 Engineering tools and appropriate technique to conduct standard tests and
measurements.
Engineering practices for society, sustainability and environment: Apply
PO5 appropriate technology in context of society, sustainability, environment and
ethical practices
Project Management: Use engineering management principles
PO6 Individually, as a team member or a leader to manage projects and
effectively communicate about well-defined engineering activities.
Life-long learning: Ability to analyse individual needs and engage in updating
PO7
in the context of technological changes

PROGRAMME SPECIFIC OUTCOMES

Ability to understand the integration of engineering applications such as electronic,


PSO1 Mechanical, electromechanical, control and computer systems that contain
software and hardware components including sensors, actuators and controllers.

An ability to exhibit the knowledge of electrical and electronic circuits, Hydraulic


PSO2
& Pneumatic control system, logic design and image processing using hardware
and Soft programming for automation

6
Contents
PartA
1. Write a simple C Program
a) Print your Name and Address

b) Find Simple interest and Compound interest.


2. Write a C program to swap two variable’s using (i) third variable and (ii) without using third variable.
3. Write a program to find the largest number between given three numbers.
4. Write a program to print all prime numbers from 1 to N.
i) Write a Python Program to print prime numbers in the given range
ii) Write a Python Program to convert decimal to binary and octal
5. i) Write a Python Program to check the given year is leap year or not.
ii) Write a Python Program to print Armstrong numbers between given range. 6
Write a Python program function for display calendar
7. (i) Write a Python Program using recursion to print ‘n’ terms in Fibonacci series.
(ii) Write a Python Program using without recursion to print ‘n’ terms in Fibonacci series
PART - B
8. Write a program to prepare the total marks for N students by reading the Reg. No, Name,
and Mark1 to Mark6 by using array of structures.
9. Write a program using the function power (a,b) to calculate the value of a raised to b
10. Write a program to find the length of the given string using pointers
11. Write a program to find factorial of a number using recursion.
12. Write a Python Program to make a simple calculator
13. Write a Python Program to take a list of words and return the length of the longest one
using string.
14. Write a Python Program to copy file contents from one file to another and display number
of words copied
15. Write a Python Program to demonstrate to use Dictionary and related
Functions.

Content Beyond the syllabus:


16. Write a C program to perform logic gates
17. Write a python program to calculate Ohm’s law.

7
Write a simple c program print your Name and address
Ex No 1a
Date:

Aim:
To write a simple c program print your Name and address.

Program:
#include <stdio.h>
#include<conio.h>
int main ()
{
clrscr();
printf("Name: ROBO\n");
print("Address: 123 AI Street, OpenAI City, CodeLand\n");
getch();
return 0;
}

Output

Name: ROBO
Address: Address: 123 AI Street, OpenAI City, CodeLand

Result:
Thus the C program is executed and the output is verified successfully.

8
Program to calculate simple and compound interest
Ex No 1b
Date:

Aim:
To write and execute a C program to calculate simple and compound interest.

Program:
#include <stdio.h>
#include<conio.h>
#include <math.h>
float calculateSimpleInterest(float principal, float rate, float time)
{
float simpleInterest;
simpleInterest = (principal * rate * time) / 100.0; return
simpleInterest;
}
float calculateCompoundInterest(float principal, float rate, float time) { float
compoundInterest;
compoundInterest = principal * (pow((1 + rate / 100.0), time)) - principal; return
compoundInterest;
}
int main()
{
clrscr();
float principal, rate, time, simpleInterest, compoundInterest;
printf("Enter principal amount: ");
scanf("%f", &principal);
printf("Enter rate of interest (per annum): ");
scanf("%f", &rate);
printf("Enter time period (in years): "); scanf("%f",
&time);
simpleInterest = calculateSimpleInterest(principal, rate, time);
compoundInterest = calculateCompoundInterest(principal, rate, time);
printf("\nSimple Interest: %.2f\n", simpleInterest);
printf("Compound Interest: %.2f\n", compoundInterest); clrscr();
return 0;
}
9
Flow Chart:

Output
Enter principal amount: 1000
Enter rate of interest (per annum): 5
Enter time period (in years): 3
Simple Interest: 150.00
Compound Interest: 157.63

Result:
Thus the C program is executed and the output is verified successfully.

10
Program to swap two variable’s using
(i) Third variable and (ii) Without using a third variable.
Ex No 2
Date:

Aim:
To Write a C program to swap two variable’s using (i) Third variable and (ii) Without using a
third variable.

Program for Using a Third Variable


#include <stdio.h>
#include<conio.h>
int main()
{
clrscr();
int a, b, temp;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
printf("Before swapping: a = %d, b = %d\n", a, b);
temp = a;
a = b;
b = temp;
printf("After swapping: a = %d, b = %d\n", a,
b); getch();
return 0;
}
Program for Without Using a Third Variable (Using Arithmetic Operations)
#include <stdio.h>
#include<conio.h>
int main()
{
clrscr();
int a, b;
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
printf("Before swapping: a = %d, b = %d\n", a, b);
a = a + b;
b = a - b;
a = a - b;
printf("After swapping: a = %d, b = %d\n", a,
b); getch();
return 0;
}

11
Flow Chart

Output for program 1

Enter two integers: 10 20


Before swapping: a = 10, b = 20
After swapping: a = 20, b = 10

Output for program 2


Enter two integers: 10 20
Before swapping: a = 10, b = 20
After swapping: a = 20, b = 10

Result:
Thus the C program is executed and the output is verified successfully.

12
Program to find the largest number between given three numbers.
Ex No 3
Date:

Aim:
To write a program to find the largest number between given three numbers.

Program:
#include <stdio.h>
#include<conio.h>
int main()
{
clrscr();
int num1, num2, num3;
printf("Enter three integers: ");
scanf("%d %d %d", &num1, &num2, &num3);
int largest = num1;
if (num2 > largest)
{
largest = num2;
}
if (num3 > largest)
{
largest = num3;
}
printf("The largest number is: %d\n", largest);
getch();
return 0;
}

Output :
Enter three integers: 25 10 45
The largest number is: 45

13
Flow Chart

Result:
Thus the C program is executed and the output is verified successfully.

14
Write a Python Program to print prime numbers in the given
range Ex No 4a
Date:
Aim:
To write a Python Program to print prime numbers in the given range.
Program:
# Function to check if a number is prime
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num ** 0.5) + 1): # Check divisibility up to the square root of num
if num % i == 0:
return False
return True

# Function to print prime numbers in a given range


def print_prime_numbers(start, end):
print(f"Prime numbers between {start} and {end} are:")
for num in range(start, end + 1):
if is_prime(num):
print(num, end=" ")

Output :

15
Flow Chart

Result:
Thus the Python program is executed and the output is verified successfully.

16
Write a Python Program to convert decimal to binary and octal
Ex No 4b
Date:
Aim:
To Write a Python Program to convert decimal to binary and octal
Program:
def decimal_to_octal(num):
return oct(num)[2:] # oct() returns a string with a '0o' prefix, so we slice off the '0o'

# Input: Take decimal number from the user


decimal number = int(input("Enter a decimal number: "))

# Conversion and output


binary = decimal_to_binary(decimal_number)
octal = decimal_to_octal(decimal_number)

print(f"Decimal: {decimal_number}")
print(f"Binary: {binary}")
print(f"Octal: {octal}")
Output :

Enter a decimal number: 25


Decimal: 25
Binary: 11001
Octal: 31

Result:
Thus the Python program is executed and the output is verified successfully.

17
Write a Python Program to check the given year is leap year or not.
Ex No 5a
Date:

Aim:
To Write a Python Program to check the given year is leap year or not.

Program:
def is_leap_year(year):
"""
Function to check if a given year is a leap year or not.
"""
if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
return True
else:
return False
year = int(input("Enter a year: "))
if is_leap_year(year):
print(f"{year} is a leap year.")
else:
print(f"{year} is not a leap year.")

Output:

Result:
Thus the Python program is executed and the output is verified successfully.

18
Write a Python Program to print Armstrong numbers between given range.
Ex No 5b
Date:

Aim:
To Write a Python Program to print Armstrong numbers between given range.

Program:
def is_armstrong(num):
"""Check if a number is an Armstrong number."""
digits = [int(d) for d in str(num)]
num_digits = len(digits)
sum_of_powers = sum(d ** num_digits for d in digits)
return sum_of_powers == num

def print_armstrong_in_range(start, end):


"""Print all Armstrong numbers in a given range."""
print(f"Armstrong numbers between {start} and {end} are:")
for num in range(start, end + 1):
if is_armstrong(num):
print(num, end=' ')
print() # For a new line after printing all Armstrong numbers

# Input range
start = int(input("Enter the start of the range: "))
end = int(input("Enter the end of the range: "))

# Print Armstrong numbers in the given range


print_armstrong_in_range(start, end)

Output:

Result:
Thus the Python program is executed and the output is verified successfully.

19
Write a Python program function for display calendar
Ex No 6
Date:
Aim:
To Write a Python program function for display calendar.
Program:
import calendar

def display_calendar(year, month):


"""Display the calendar for a specific month and year."""
# Create a TextCalendar instance
cal = calendar.TextCalendar(calendar.SUNDAY)
# Generate the calendar for the specified month and year
month_calendar = cal.formatmonth(year, month)
print(month_calendar)

# Main function to get user input and display the calendar


def main():
# Get the year and month from the user
year = int(input("Enter the year (e.g., 2024): "))
month = int(input("Enter the month (1-12): "))

# Validate month input


if 1 <= month <= 12:
display_calendar(year, month)
else:
print("Invalid month. Please enter a value between 1 and 12.")

if name == " main ":


main()

Output:

Result:
Thus the Python program is executed and the output is verified successfully.

20
Write a Python Program using recursion to print ‘n’ terms in Fibonacci series.
Ex No 7a
Date:

Aim:
To Write a Python Program using recursion to print ‘n’ terms in Fibonacci series.

Program:
def fibonacci(n):
"""Recursive function to return the nth Fibonacci number."""
if n <= 0:
return 0
elif n ==
1:
return 1
else:
return fibonacci(n - 1) + fibonacci(n - 2)

def print_fibonacci_series(n):
"""Print the first n terms of the Fibonacci series."""
for i in range(n):
print(fibonacci(i), end=' ')
print() # For a new line after printing all terms

def main():
# Get the number of terms from the user
n = int(input("Enter the number of terms in the Fibonacci series: "))
if n > 0:
print_fibonacci_series(n)
else:
print("Please enter a positive integer.")

if name == " main ":


main()

Output:

Result:
Thus the Python program is executed and the output is verified successfully.

21
Write a Python Program using without recursion to print ‘n’ terms in Fibonacci
series Ex No 7b
Date:
Aim:
To Write a Python Program using without recursion to print ‘n’ terms in Fibonacci series
Program:
def print_fibonacci_series(n):
"""Print the first n terms of the Fibonacci series."""
if n <= 0:
print("Please enter a positive integer.")
return
elif n == 1:
print("0")
return
elif n == 2:
print("0 1")
return

# Initialize the first two terms


a, b = 0, 1
print(a, end=' ')
print(b, end=' ')

# Generate and print the remaining terms


for _ in range(2, n):
a, b = b, a + b
print(b, end=' ')
print() # For a new line after printing all terms

def main():
# Get the number of terms from the user
n = int(input("Enter the number of terms in the Fibonacci series: "))
print_fibonacci_series(n)

if name == " main ":


main()

Output:

Result:
Thus the Python program is executed and the output is verified successfully.

22
Write a program to prepare the total marks for N students by reading
the Reg. No, Name, and Mark1 to Mark6 by using array of structures.
Ex No 8
Date:

Aim:
To write a program to prepare the total marks for N students by reading the Reg. No, Name, and
Mark1 to Mark6 by using array of structures.

Program:
def calculate_total_marks(students):
for student in students:
total_marks = sum(student['marks'])
student['total_marks'] = total_marks
def display_student_details(students):
print("Student details with total marks:")
for student in students:
print(f"Registration Number: {student['reg_no']}, Name: {student['name']}, Total Marks:
{student['total_marks']}")
if name == " main ":
# Number of students
N=3
students = []
for i in range(N):
reg_no = input(f"Enter Registration Number for student {i+1}: ")
name = input(f"Enter Name for student {i+1}: ")
marks = []
for j in range(6):
mark = float(input(f"Enter Mark{j+1} for {name}: "))
marks.append(mark)
student_details = {
'reg_no': reg_no,
'name': name,
'marks': marks,
'total_marks': 0 # Placeholder for total marks
}
students.append(student_details)
calculate_total_marks(students)
display_student_details(students)

23
Output:

Result:
Thus the Python program is executed and the output is verified successfully.

24
Write a program using the function power (a,b) to calculate the value of a raised to
b Ex No 9
Date:

Aim:
To Write a program using the function power (a,b) to calculate the value of a raised to b.

Program:
def power(a, b):
"""Calculate and return a raised to the power of b."""
return a ** b

def main():
# Input base and exponent from the user
a = float(input("Enter the base (a): "))
b = int(input("Enter the exponent (b): "))

# Calculate the power using the power function


result = power(a, b)

# Print the result


print(f"{a} raised to the power of {b} is: {result}")

if name == " main ":


main()

Output:

Result:
Thus the Python program is executed and the output is verified successfully.

25
Write a program to find the length of the given string using
pointers

Ex No 10
Date:

Aim:
To write a program to find the length of the given string using pointers

Program:
def find_string_length(s):
length = 0
while s[length:]:
length += 1
return length
if name == " main ":
string = input("Enter a string: ")
length = find_string_length(string)
print(f"Length of the string '{string}' is:
{length}")

Output:

Result:
Thus the Python program is executed and the output is verified successfully.

26
Write a program to find factorial of a number using recursion.
Ex No 11
Date:
Aim:
To write a program to find factorial of a number using recursion.
Program:
def. factorial(n):
"""Calculate the factorial of a number using recursion."""
# Base case: factorial of 0 or 1 is 1
if n == 0 or n == 1:
return 1
# Recursive case: n! = n * (n-1)!
else:
return n * factorial(n - 1)

def main():
# Input a number from the user
number = int(input("Enter a non-negative integer: "))

# Validate the input


if number < 0:
print("Factorial is not defined for negative numbers.")
else:
# Calculate the factorial using the factorial function
result = factorial(number)
# Print the result
print(f"The factorial of {number} is: {result}")

if name == " main ":


main()

Output:

Result:
Thus the Python program is executed and the output is verified successfully.

27
Write a Python Program to make a simple calculator
Ex No 12
Date:

Aim:
To Write a Python Program to make a simple calculator.

Program:
def add(x, y):
"""Return the sum of x and y."""
return x + y

def subtract(x, y):


"""Return the difference between x and y."""
return x - y

def multiply(x, y):


"""Return the product of x and y."""
return x * y

def divide(x, y):


"""Return the quotient of x divided by y."""
if y == 0:
return "Error: Division by zero is not allowed."
else:
return x / y

def main():
while True:
# Display the menu
print("\nSimple Calculator")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")

# Take user input for operation


choice = input("Enter your choice (1/2/3/4/5): ")

# Exit the program

28
if choice == '5':
print("Exiting...")
break

# Check if the choice is


valid if choice in ['1', '2', '3',
'4']:
# Get user input for numbers
try:
num1 = float(input("Enter the first number: "))
num2 = float(input("Enter the second number: "))
except ValueError:
print("Invalid input. Please enter numeric values.")
continue

# Perform the chosen operation if


choice == '1':
print(f"The result of {num1} + {num2} is: {add(num1, num2)}")
elif choice == '2':
print(f"The result of {num1} - {num2} is: {subtract(num1,
num2)}") elif choice == '3':
print(f"The result of {num1} * {num2} is: {multiply(num1,
num2)}") elif choice == '4':
print(f"The result of {num1} / {num2} is: {divide(num1,
num2)}") else:
print("Invalid choice. Please enter a number between 1 and 5.")

if name == " main ":


main()

Output:

Result:
Thus the Python program is executed and the output is verified successfully.

29
Write a Python Program to take a list of words and return the length of
the longest one using string.
Ex No 13
Date:
Aim:
To Write a Python Program to take a list of words and return the length of the longest one using
string.
Program:
def longest_word_length(words):
"""Return the length of the longest word in the list.""" #
Check if the list is empty
if not words:
return 0

# Find the longest word using the max function with key=len
longest_word = max(words, key=len)

# Return the length of the longest word


return len(longest_word)

def main():
# Input a list of words from the user
words = input("Enter a list of words separated by spaces: ").split()

# Calculate the length of the longest word length


= longest_word_length(words)

# Print the result


print(f"The length of the longest word is: {length}")

if name == " main ":


main()

Output:

Result:
Thus the Python program is executed and the output is verified successfully.

30
Write a Python Program to copy file contents from one file to another
and display number of words copied
Ex No 14
Date:
Aim:
To Write a Python Program to copy file contents from one file to another and display number of words
copied
Program:
def copy_file_contents(source_file, destination_file):
"""Copy contents from source_file to destination_file and return the number of words
copied."""
try:
# Open the source file in read mode
with open(source_file, 'r') as src:
content = src.read()

# Count the number of words in the content


word_count = len(content.split())

# Open the destination file in write mode with


open(destination_file, 'w') as dest:
dest.write(content)

return word_count
except
FileNotFoundError:
print(f"Error: The file {source_file} was not found.")
return 0
except IOError as e:
print(f"Error: An IOError occurred.
{e}") return 0

def main():
# Get the names of the source and destination files from the user
source_file = input("Enter the source file name: ")
destination_file = input("Enter the destination file name: ")

# Copy file contents and get the number of words copied


words_copied = copy_file_contents(source_file, destination_file)

if words_copied > 0:
print(f"Contents copied successfully. Number of words copied: {words_copied}")
else:
print("Failed to copy contents.")

if name == " main ":


main()

31
Output:
Successfully copied 6 words from 'source.txt' to 'destination.txt'.

Result:
Thus the Python program is executed and the output is verified successfully.

32
Write a Python Program to demonstrate to use Dictionary and related
Functions. Ex No 15
Date:

Aim:
To Write a Python Program to demonstrate to use Dictionary and related Functions.

Program:
def demo_dictionary_operations():
# Create a dictionary
my_dict = {
'name': 'Alice',
'age': 25,
'city': 'New York'
}

# Display the dictionary


print("Initial
Dictionary:")
print(my_dict)

# Add a new key-value pair


my_dict['email'] = '[email protected]'
print("\nDictionary after adding 'email':")
print(my_dict)

# Update an existing key-value pair


my_dict['age'] = 26
print("\nDictionary after updating 'age':")
print(my_dict)

# Remove a key-value pair


del my_dict['city']
print("\nDictionary after removing 'city':")
print(my_dict)

# Access a value using a key


name = my_dict.get('name', 'Not Found')
print(f"\nValue for 'name': {name}")

# Check if a key exists in the dictionary


if 'email' in my_dict:
print("\n'email' exists in the dictionary.")

# Get all keys and values


keys = my_dict.keys()
values = my_dict.values()

33
items = my_dict.items()
print("\nKeys:", list(keys))
print("Values:",
list(values)) print("Items:",
list(items))

# Iterate over the dictionary


print("\nIterating over dictionary items:")
for key, value in my_dict.items():
print(f"{key}: {value}")

def main():
demo_dictionary_operations()

if name == " main ":


main()

Output:

Result:
Thus the Python program is executed and the output is verified successfully.

34
Write a C program to perform logic gates
Ex No 16
Date:

Aim:
To Write a C program to perform logic gates

Program:
#include <stdio.h>
#include<conio.h>
int and_gate(int a, int b);
int or_gate(int a, int b);
int not_gate(int a);
int xor_gate(int a, int b);
int main()
{
clrscr();
int input1, input2;
printf("Enter first input (0 or 1): ");
scanf("%d", &input1);
printf("Enter second input (0 or 1): ");
scanf("%d", &input2);
printf("\nAND Gate: %d AND %d = %d\n", input1, input2, and_gate(input1, input2));
printf("OR Gate: %d OR %d = %d\n", input1, input2, or_gate(input1, input2));
printf("NOT Gate for %d = %d\n", input1, not_gate(input1));
printf("XOR Gate: %d XOR %d = %d\n", input1, input2, xor_gate(input1, input2));
getch();
return 0;
}
int and_gate(int a, int b) {
return a && b;
}
int or_gate(int a, int b) {
return a || b;
}
int not_gate(int a) {
return !a;
}
int xor_gate(int a, int b) {
return a ^ b;
}

35
Output:
Enter first input (0 or 1): 1

Enter second input (0 or 1): 0

AND Gate: 1 AND 0 = 0

OR Gate: 1 OR 0 = 1

NOT Gate for 1 = 0

XOR Gate: 1 XOR 0 = 1

Result:
Thus the C program is executed and the output is verified successfully.

36
Write a python program to calculate Ohm’s Law
Ex No 17
Date:

Aim:
To write a python program to calculate Ohm’s law

Program:
def calculate_voltage(current, resistance): """
Calculate voltage using Ohm's law """
return current * resistance
def calculate_current(voltage, resistance): """
Calculate current using Ohm's law """
return voltage / resistance
def calculate_resistance(voltage, current):
""" Calculate resistance using Ohm's law """
return voltage / current
if name == " main ":
print("Ohm's Law
Calculator")
print("Choose what you want to calculate:")
print("1. Voltage (V)")
print("2. Current (I)")
print("3. Resistance (R)")
choice = int(input("Enter your choice (1/2/3): "))
if choice == 1:
current = float(input("Enter current (I) in amperes: "))
resistance = float(input("Enter resistance (R) in ohms: "))
voltage = calculate_voltage(current, resistance)
print(f"The voltage (V) across the circuit is: {voltage} volts")
elif choice == 2:
voltage = float(input("Enter voltage (V) in volts: "))
resistance = float(input("Enter resistance (R) in ohms: "))
current = calculate_current(voltage, resistance)
print(f"The current (I) flowing through the circuit is: {current} amperes")
elif choice == 3:
voltage = float(input("Enter voltage (V) in volts: "))
current = float(input("Enter current (I) in amperes: "))
resistance = calculate_resistance(voltage, current)
print(f"The resistance (R) of the circuit is: {resistance} ohms")
else:
print("Invalid choice. Please enter a valid option (1/2/3).")

37
Output:
Ohm's Law Calculator

Choose what you want to calculate:

1. Voltage (V)

2. Current (I)

3. Resistance (R)

Enter your choice (1/2/3): 1

Enter current (I) in amperes: 2.5

Enter resistance (R) in ohms: 10

The voltage (V) across the circuit is: 25.0 volts

Result:
Thus the Python program is executed and the output is verified successfully.

38

You might also like