A Function is a Block Understanding the Fundamentals of Programming

 

A Function is a Block Understanding the Fundamentals of Programming


A Function is a Block Understanding the Fundamentals of Programming
A Function is a Block Understanding the Fundamentals of Programming


A Function is a Block Understanding the Fundamentals of Programming


  • Functions help in organizing code, making it more modular and easier to understand. Here's a basic overview of creating and using functions in Python:

Defining a Function:

  • You can define a function using the `def` keyword, followed by the function name and a pair of parentheses. 
  • If the function takes parameters, they are listed inside the parentheses.

 def greet(name):  
   print("Hello, " + name + "!")  


Calling a Function:


  • To execute a function and make it perform its task, you need to call it. 
  • Call a function by using its name followed by parentheses. 
  • If the function takes parameters, provide them inside the parentheses.

 greet("John")  


Return Statement:


  • A function can return a value using the `return` statement. 
  • The returned value can be assigned to a variable or used in any other way.

 def add(a, b):  
   return a + b  
 result = add(3, 5)  
 print(result)   
 Output: 8  

Default Parameters:


  • You can provide default values for function parameters. 
  • If a value is not provided during the function call, the default value is used.


 def power(base, exponent=2):  
   return base ** exponent  
 print(power(3))      
 Output: 9 (default exponent is 2)  
 print(power(3, 3))    
 Output: 27  


Variable Number of Arguments:


  • A function can accept a variable number of arguments using the `*args` (for positional arguments) and `**kwargs` (for keyword arguments) syntax.


 def print_arguments(*args, **nvr):  
   for arg in args:  
     print(arg)  
   for key, value in nvr.items():  
     print(f"{key}: {value}")  
 print_arguments(1, 2, 3, name="N.V.Ramana", age=25)  


Lambda Functions:


  • You can create small anonymous functions using the `lambda` keyword. These functions can have any number of input parameters but can only have one expression.

 square = lambda x: x**2  
 print(square(5))   
 Output: 25  


  • These are some of the fundamental concepts related to functions in Python. Functions are crucial for writing clean, modular, and reusable code.


Exercise 1: Simple Greeting Function


  • Write a function called `greet_person` that takes a person's name as a parameter and prints a personalized greeting message.


 def greet_person(name):  
   print("Hello, " + name + "!")  
 Test the function  
 greet_person("NVR")  
 greet_person("How are you")  


Exercise 2: Calculate the Area of a Rectangle


  • Write a function called `calculate_rectangle_area` that takes the length and width of a rectangle as parameters and returns the area.


 def calculate_rectangle_area(length, width):  
   return length * width  
 # Test the function  
 area = calculate_rectangle_area(5, 8)  
 print("The area of the rectangle is:", area)  


Exercise 3: Check Even or Odd


  • Write a function called `is_even` that takes an integer as a parameter and returns `True` if the number is even and `False` otherwise.

 def is_even(number):  
   return number % 2 == 0  
 # Test the function  
 print(is_even(4))    
 Output: True  
 print(is_even(7))    
  Output: False  


Exercise 4: Sum of Numbers


  • Write a function called `sum_numbers` that takes a variable number of arguments and returns the sum of those numbers.

 def sum_numbers(*args):  
   return sum(args)  
 # Test the function  
 result = sum_numbers(1, 2, 3, 4, 5)  
 print("Sum of numbers:", result)  


Exercise 5: Celsius to Fahrenheit Converter


  • Write a function called `celsius_to_fahrenheit` that takes a temperature in Celsius as a parameter and returns the equivalent temperature in Fahrenheit.

 def celsius_to_fahrenheit(celsius):  
   return (celsius * 9/5) + 32  
 # Test the function  
 temperature_celsius = 20  
 temperature_fahrenheit = celsius_to_fahrenheit(temperature_celsius)  
 print(f"{temperature_celsius} degrees Celsius is equal to {temperature_fahrenheit:.2f} degrees Fahrenheit.")  



Exercise 6: Factorial Function


  • Write a function called `factorial` that calculates the factorial of a given non-negative integer. 
  • The factorial of a number \(n\) is the product of all positive integers up to \(n\).


 def factorial(n):  
   if n == 0 or n == 1:  
     return 1  
   else:  
     return n * factorial(n - 1)  
 # Test the function  
 print("Factorial of 5:", factorial(5))  


Exercise 7: String Reversal


  • Write a function called `reverse_string` that takes a string as a parameter and returns the reversed version of that string.


 def reverse_string(input_str):  
   return input_str[::-1]  
 # Test the function  
 original_str = "Hello, World!"  
 reversed_str = reverse_string(original_str)  
 print("Original String:", original_str)  
 print("Reversed String:", reversed_str)  


Exercise 8: Palindrome Checker


  • Write a function called `is_palindrome` that takes a string as a parameter and returns `True` if the string is a palindrome like reads the same backward as forward, and `False` otherwise.


 def is_palindrome(input_str):  
   return input_str == input_str[::-1]  
 # Test the function  
 print(is_palindrome("radar"))   # Output: True  
 print(is_palindrome("python"))   # Output: False  
 print(is_palindrome("level"))   # Output: True  


Exercise 9: Prime Number Checker


  • Write a function called `is_prime` that takes an integer as a parameter and returns `True` if the number is prime like has no divisors other than 1 and itself, and `False` otherwise.


 def is_prime(number):  
   if number < 2:  
     return False  
   for i in range(2, int(number**0.5) + 1):  
     if number % i == 0:  
       return False  
   return True  
 # Test the function  
 print(is_prime(7))     
 Output: True  
 print(is_prime(12))     
  Output: False  
 print(is_prime(23))     
 Output: True  


  • Feel free to run these examples and experiment with the functions. 
  • If you have any questions or if there's a specific topic you'd like to explore further, let me know!


Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.