Friday, January 26, 2024

Programs of Function in Python


Function to Calculate Factorial:


def factorial(n): if n == 0: return 1 else: return n * factorial(n-1) num = 5 print("Factorial of", num, "is", factorial(num))


Function to Check if a Number is Prime:


def is_prime(n): if n <= 1: return False for i in range(2, int(n**0.5) + 1): if n % i == 0: return False return True num = 17 if is_prime(num): print(num, "is prime") else: print(num, "is not prime")

Function to Find Fibonacci Series:


def fibonacci(n): fib_series = [0, 1] for i in range(2, n): fib_series.append(fib_series[-1] + fib_series[-2]) return fib_series terms = 10 print("Fibonacci series up to", terms, "terms:", fibonacci(terms))


Function to Reverse a String:


def reverse_string(s): return s[::-1] string = "hello" print("Reversed string:", reverse_string(string))


Function to Convert Celsius to Fahrenheit:


def celsius_to_fahrenheit(celsius): return (celsius * 9/5) + 32 temp_celsius = 30 print(temp_celsius, "Celsius is equal to", celsius_to_fahrenheit(temp_celsius), "Fahrenheit")

No comments:

Post a Comment

Input Text and Display in tkinter

  import tkinter as tk def display_text():     text = entry.get()     label.config(text="You entered: " + text) root = tk.Tk() roo...