0% found this document useful (0 votes)
8 views

python solution

The document contains multiple Python programming solutions for various tasks, including calculating equivalent resistances, applying Ohm's law, checking frequency types, displaying radio frequency bands, resistor color codes, calculating factorials, swapping variables, and performing operations on tuples. It also includes a simple calculator module and examples of using NumPy for creating special arrays and demonstrating broadcasting. Each solution is presented with code snippets and explanations.

Uploaded by

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

python solution

The document contains multiple Python programming solutions for various tasks, including calculating equivalent resistances, applying Ohm's law, checking frequency types, displaying radio frequency bands, resistor color codes, calculating factorials, swapping variables, and performing operations on tuples. It also includes a simple calculator module and examples of using NumPy for creating special arrays and demonstrating broadcasting. Each solution is presented with code snippets and explanations.

Uploaded by

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

SOLUTION

1.

a) Write simple Python program to calculate equivalent registers connected in series and parallel.
Accept values of R1, R2 and R3 from the user.

b) Write simple Python program to calculate value of voltage by applying Ohm’s law. Accept value of
Current(I) and Resistance(R) from the user.

 Solution: a

1. def equivalent_resistors():
2. # Accepting values of R1, R2, and R3 from the user
3. R1 = float(input("Enter the value of R1: "))
4. R2 = float(input("Enter the value of R2: "))
5. R3 = float(input("Enter the value of R3: "))
6.
7. # Calculating equivalent resistance in series
8. series_resistance = R1 + R2 + R3
9.
10. # Calculating equivalent resistance in parallel
11. parallel_resistance = 1 / ((1 / R1) + (1 / R2) + (1 / R3))
12.
13. # Printing the results
14. print(f"Equivalent resistance in series: {series_resistance} ohms")
15. print(f"Equivalent resistance in parallel: {parallel_resistance} ohms")
16.
17. # Calling the function
18. equivalent_resistors()

 Solution: b
1. def calculate_voltage(i, r): return i * r
2. def calculate_resistance(v, i): return v / i
3. def calculate_current(v, r): return v / r

4. while True:
5. option = input("1. Voltage\n2. Resistance\n3. Current\n4. Exit\n> ")
6. if option == "4": break
7. try:
8. if option == "1":
9. print(f"Voltage = {calculate_voltage(float(input('Current (A): ')), float(input('Resistance (Ω):
'))):.2f} V")
10. elif option == "2":
11. print(f"Resistance = {calculate_resistance(float(input('Voltage (V): ')), float(input('Current (A):
'))):.2f} Ω")
12. elif option == "3":
SOLUTION
13. print(f"Current = {calculate_current(float(input('Voltage (V): ')), float(input('Resistance (Ω):
'))):.2f} A")
14. else:
15. print("Invalid option.")
16. except ValueError:
17. print("Enter numerical values.")
18. except ZeroDivisionError:
19. print("Division by zero is not allowed.")

2.

Write program to check whether entered frequency is radio frequency or audio frequency.

 Solution:

1. def check_frequency():
2. frequency = float(input("Enter the frequency in Hz: "))

3. if 20 <= frequency <= 20000:


4. print("Audio frequency.")
5. elif 3000 <= frequency <= 300000000000:
6. print("Radio frequency.")
7. else:
8. print("Neither audio nor radio frequency.")

9. check_frequency()

3.

a) Write program to display various radio frequency bands using if..elseif ladder.

b) Write program to display resistor color code using switch statement.

 Solution: a

1. def radio_frequency_band():
2. frequency = float(input("Enter the frequency in Hz: "))
3. bands = [
4. (3e3, 30e3, "Very Low Frequency (VLF)"),
5. (30e3, 300e3, "Low Frequency (LF)"),
6. (300e3, 3e6, "Medium Frequency (MF)"),
7. (3e6, 30e6, "High Frequency (HF)"),
8. (30e6, 300e6, "Very High Frequency (VHF)"),
9. (300e6, 3e9, "Ultra High Frequency (UHF)"),
10. (3e9, 30e9, "Super High Frequency (SHF)"),
SOLUTION
11. (30e9, 300e9, "Extremely High Frequency (EHF)"),
12. ]
13. for low, high, name in bands:
14. if low <= frequency < high:
15. print(name)
16. return
17. print("Frequency out of radio frequency range")
18.
19. radio_frequency_band()

 Solution: b

1. def resistor_color_code():
2. colors = {
3. "black": 0,
4. "brown": 1,
5. "red": 2,
6. "orange": 3,
7. "yellow": 4,
8. "green": 5,
9. "blue": 6,
10. "violet": 7,
11. "gray": 8,
12. "white": 9
13. }

14. color = input("Enter the color: ").lower()

15. value = colors.get(color, "Invalid color")

16. if value != "Invalid color":


17. print(f"The value for {color} is: {value}")
18. else:
19. print("Invalid color entered. Please enter a valid resistor color.")

20. resistor_color_code()

4.

Write python programs to define function with arguments.


a) Calculate factorial of a number
b) Swapping of two variables

 Solution: a
SOLUTION

1. def factorial(n):
2. if n == 0 or n == 1:
3. return 1
4. else:
5. return n * factorial(n - 1)
6.
7. def swap(a, b):
8. a, b = b, a
9. return a, b
10.
11. # Main Program
12. if __name__ == "__main__":
13. # Factorial Calculation
14. number = int(input("Enter a number to calculate its factorial: "))
15. result = factorial(number)
16. print(f"The factorial of {number} is {result}")
17.
18. # Swapping Variables
19. x = input("Enter the first value: ")
20. y = input("Enter the second value: ")
21.
22. # Perform the swap
23. x, y = swap(x, y)
24. print(f"After swapping, first value is: {x}, second value is: {y}")

5. Develop Python program to perform following operations on Tuples:


a) Create
b) Access
c) Update
d) Delete Tuple elements

 Solution:

1. # a) Create
2. print("Creating tuples:")
3. tuple1 = (1, 2, 3, 4, 5)
4. tuple2 = ('a', 'b', 'c', 'd')
5. print("Tuple 1:", tuple1)
6. print("Tuple 2:", tuple2)
7.
8. # b) Access
9. print("\nAccessing elements from tuples:")
10. print("First element of tuple1:", tuple1[0])
11. print("Last element of tuple2:", tuple2[-1])
12. print("Slice of tuple1 (index 1 to 3):", tuple1[1:4])
SOLUTION
13.
14. # c) Update (indirectly)
15. print("\nUpdating tuple elements (indirectly):")
16. # Convert tuple to list, update, and convert back to tuple
17. list1 = list(tuple1)
18. list1[0] = 10
19. tuple1 = tuple(list1)
20. print("Updated tuple1:", tuple1)
21.
22. # d) Delete
23. print("\nDeleting a tuple:")
24. del tuple1
25. print("Tuple1 deleted. Attempting to print tuple1 will result in an error.")
26. try:
27. print(tuple1)
28. except NameError as e:
29. print(e)

6. Write program to create a user-defined module (e.g.: building calculator) in python.

 Solution:

1. def add(a, b):


2. return a + b

3. def subtract(a, b):


4. return a - b

5. def multiply(a, b):


6. return a * b

7. def divide(a, b):


8. return a / b if b != 0 else "Cannot divide by zero"

9. # Main program
10. if __name__ == "__main__":
11. print("Simple Calculator")

12. # Get user inputs


13. a = float(input("Enter first number: "))
14. b = float(input("Enter second number: "))

15. print("Choose an operation:")


16. print("1. Add\n2. Subtract\n3. Multiply\n4. Divide")
17. choice = input("Enter your choice (1-4): ")
SOLUTION

18. # Perform the operation


19. if choice == "1":
20. print("Result:", add(a, b))
21. elif choice == "2":
22. print("Result:", subtract(a, b))
23. elif choice == "3":
24. print("Result:", multiply(a, b))
25. elif choice == "4":
26. print("Result:", divide(a, b))
27. else:
28. print("Invalid choice")

import matplotlib.pyplot as plt

x = [1, 2, 3, 4]

y = [10, 20, 25, 30]

plt.plot(x, y)

plt.title(“Basic Line Plot”)

plt.xlabel(“X-axis”)

plt.ylabel(“Y-axis”)

plt.grid(True)

plt.show()

Special array in python

Np.zeros((2, 3)) # array of zeros

Np.ones((3, 3)) # array of ones

Np.eye(3) # identity matrix

Np.full((2, 2), 7) # array full of 7

Np.arange(0, 10, 2) # [0, 2, 4, 6, 8]

Np.linspace(0, 1, 5) # 5 evenly spaced points between 0 and 1


SOLUTION
Broadcasting in python

A = np.array([[1], [2], [3]])

B = np.array([10, 20, 30])

Print(a + b)

# Output:

# [[11 21 31]

# [12 22 32]

# [13 23 33]]

You might also like