0% found this document useful (0 votes)
2 views2 pages

Program 2

The document contains two Python programs: the first calculates Fibonacci numbers based on user input, ensuring N is greater than 0, and the second converts binary numbers to decimal and octal numbers to hexadecimal using defined functions. Error handling is included for invalid inputs in both programs. The source code for each program is provided with appropriate function definitions and user prompts.
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)
2 views2 pages

Program 2

The document contains two Python programs: the first calculates Fibonacci numbers based on user input, ensuring N is greater than 0, and the second converts binary numbers to decimal and octal numbers to hexadecimal using defined functions. Error handling is included for invalid inputs in both programs. The source code for each program is provided with appropriate function definitions and user prompts.
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

2a) Defined as a function F as fib = fib-1 + fib-2.

Write a Python
program that accepts a value for N (where N >0) as input and pass
this value to the function. Display a suitable error message if the
condition for input value is not followed.
Source Code
def fib(n):
if n == 1:
return 0
elif n == 2:
return 1
else:
return fib(n-1) + fib(n-2)
num = int(input("Enter a number: "))
if num > 0:
print("fib(", num, ")=", fib(num), sep="")
else:
print("Error in input")
2b)Develop a python program to convert binary to decimal, octal
to hexadecimal using functions. Function to convert binary to
decimal.

Source Code
def binary_to_decimal(binary_str):
decimal = int(binary_str, 2)
return decimal
def octal_to_hexadecimal(octal_str):
decimal = int(octal_str, 8
hexadecimal = hex(decimal)[2:].upper
return hexadecimal
def main() :
try:
choice = input("Choose a conversion (1 for Binary to Decimal,2 for Octal to
Hexadecimal):\n")
if choice == '1':
binary_str = input ("Enter a Binary Number: ")
decimal_value = binary_to_decimal (binary_str)
print (f"Decima1 equivalent: {decimal_value}")
elif choice == '2':
octal_str = input("Enter an Octal Number:")
hexadecimal_value = octal_to_hexadecimal (octal_str)
print (f"Hexadecimal equivalent: {hexadecimal_value} ")
else:
print ("Invalid choice. Please enter")
except ValueError:
print ("lnvalid input. Please enter a valid nunber. ")

if __name__ == "__main__":
main()

You might also like