Translate

Thursday, 15 February 2024

What Is Functions in python and some example programs

 


What are Functions?

  • Code Block: A function is a reusable block of code designed to perform a specific task.

  • Organization: Functions help break down your code into modular, manageable units.

  • Inputs and Outputs: Functions can take inputs (called arguments or parameters) and may return an output.

Why Use Functions?

  • Reusability: Write a function once, and call it multiple times from different parts of your code.

  • Readability: Well-named functions make code easier to understand and maintain.

  • Abstraction: Functions hide implementation details, allowing you to focus on the overall logic of your program.

  • Testing: It's easier to test smaller, isolated functions.

Basic Syntax


Python

def function_name(parameter1, parameter2, ...):
    """
    This is the docstring (optional, but good practice)
    Describes what the function does.
    """
    # Function code here
    # ....
    return output_value  # Optional, can return a value

Example


Python

def greet(name):
    """Greets a person by name."""
    print("Hello,", name + "!")

greet("Alice"# Outputs: Hello, Alice!

Key Points

  • def keyword: Used to define a function.

  • Docstrings: Explanatory strings within triple quotes (""") below the function definition.

  • Parameters: Variables that receive values when the function is called.

  • return statement: Sends a value back from the function (optional).

Types of Functions

  • Built-in Functions: Python provides many ready-to-use functions like print(), len(), min(), etc.

  • User-defined Functions: Functions you create yourself like the greet() example above.

Example with Input and Output


Python

def calculate_area(length, width):
    """Calculates the area of a rectangle."""
    area = length * width
    return area

result = calculate_area(5, 10)
print("The area is:", result)  # Outputs: The area is: 50



Example 1: Area Calculations


Python

def calculate_rectangle_area(length, width):
    """Calculates and returns the area of a rectangle."""
    area = length * width
    return area

def calculate_circle_area(radius):
    """Calculates and returns the area of a circle."""
    pi = 3.14159
    area = pi * radius * radius
    return area

# Get user input
shape = input("Enter shape (rectangle or circle): ")

if shape == "rectangle":
    length = float(input("Enter length: "))
    width = float(input("Enter width: "))
    area = calculate_rectangle_area(length, width)
elif shape == "circle":
    radius = float(input("Enter radius: "))
    area = calculate_circle_area(radius)
else:
    print("Invalid shape")

print("The area is:", area)

Example 2: Student Grading


Python

def determine_grade(score):
    """Assigns a letter grade based on a numerical score."""
    if score >= 90:
        return "A"
    elif score >= 80:
        return "B"
    elif score >= 70:
        return "C"
    elif score >= 60:
        return "D"
    else:
        return "F"

# Get student information
student_name = input("Enter student name: ")
score = int(input("Enter score: "))

grade = determine_grade(score)
print(student_name, "earned a grade of", grade)

Example 3: Password Checker


Python

def check_password(password):
    """Checks if a password meets complexity requirements."""
    has_upper = False
    has_lower = False
    has_digit = False

    for char in password:
        if char.isupper():
            has_upper = True
        if char.islower():
            has_lower = True
        if char.isdigit():
            has_digit = True

    if len(password) >= 8 and has_upper and has_lower and has_digit:
        return True
    else:
        return False

# Get password from the user
password = input("Enter a new password: ")

if check_password(password):
    print("Password is strong.")
else:
    print("Password is weak. Please follow complexity rules.")

Key Points

  • Arguments: Values passed to functions when they are called.

  • Flexibility: Functions with arguments make our code reusable for different inputs.

  • Modularity: Breaking down problems into smaller, well-defined functions.



09 What Is Functions in python and some example programs

No comments:

Post a Comment

Note: only a member of this blog may post a comment.