Function Program in Python :
import math
def greet():
print("Hello! Welcome to the advanced functions program.")
def quadratic_formula(a, b, c):
discriminant = b**2 - 4*a*c
if discriminant > 0:
x1 = (-b + math.sqrt(discriminant)) / (2*a)
x2 = (-b - math.sqrt(discriminant)) / (2*a)
return x1, x2
elif discriminant == 0:
x = -b / (2*a)
return x
else:
return "No real roots"
def calculate_factorial(n):
if n == 0:
return 1
else:
return n * calculate_factorial(n-1)
def fibonacci_sequence(n):
sequence = [0, 1]
for i in range(2, n):
sequence.append(sequence[i-1] + sequence[i-2])
return sequence
def main():
greet()
print("\n1. Quadratic Formula Solver")
a = float(input("Enter the value of a: "))
b = float(input("Enter the value of b: "))
c = float(input("Enter the value of c: "))
roots = quadratic_formula(a, b, c)
print("Roots:", roots)
print("\n2. Factorial Calculator")
num = int(input("Enter a number to calculate its factorial: "))
factorial = calculate_factorial(num)
print("Factorial:", factorial)
print("\n3. Fibonacci Sequence Generator")
length = int(input("Enter the length of the Fibonacci sequence: "))
fibonacci = fibonacci_sequence(length)
print("Fibonacci Sequence:", fibonacci)
if __name__ == "__main__":
main()
This program demonstrates the use of functions for different purposes:
greet(): A simple function to greet the user.quadratic_formula(a, b, c): Computes the roots of a quadratic equation given coefficientsa,b, andc.calculate_factorial(n): Calculates the factorial of a given numbern.fibonacci_sequence(n): Generates a Fibonacci sequence of lengthn.main(): The main function that orchestrates the execution of the program.
No comments:
Post a Comment