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.
01 How to Install Anaconda Software : https://youtu.be/gy7H0AsgfxY
02 What are variables in Python : https://youtu.be/Hpr-u35kz84
03 Int float Boolean Data types : https://youtu.be/H76ye6GVwZY
04 String data type : https://youtu.be/Ow9gJAlbzpk
05 Arithmetic Operators in Python : https://youtu.be/jJl50Tg070Y
06 Python Comparison Operators : https://youtu.be/psV3lnKXKUU
07 Logical and Identity Operators : https://youtu.be/oW_gTVciMrM
08 if and else : https://youtu.be/czK81ZOTyh8
What Is Functions in python and some example programs¶
def greeting():
print("Please Subcribe")
greeting()
Please Subcribe
greeting()
Please Subcribe
def greeting():
return "ramesh"
greeting()
'ramesh'
def add_2num(a,b):
sum = a+b
return sum
add_2num(2,3)
5
def add_2num(a,b):
sum = a+b
print('sum is:', sum)
add_2num(2,3)
sum is: 5
def greet(name):
# """Greets a person by name."""
print("Hello,", name + "!")
greet("Venkat") # Outputs: Hello, Alice!
Hello, Venkat!
greet("vlr training")
Hello, vlr training!
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
The area is: 50
def are_rect(le,wi):
area = le*wi
return area
are_rect(22,4)
88
totalarea=are_rect(22,4)
print("area is",totalarea)
area is 88
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)
print("The area is:", area)
elif shape == "circle":
radius = float(input("Enter radius: "))
area = calculate_circle_area(radius)
print("The area is:", area)
else:
print("Invalid shape")
Enter shape (rectangle or circle): rectangle Enter length: 44 Enter width: 3 The area is: 132.0
# student Grade with Function
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"
student_name = input("Enter student name: ")
score = int(input("Enter score: "))
grade = determine_grade(score)
print(student_name, "earned a grade of", grade)
Enter student name: kumar Enter score: 99 kumar earned a grade of A
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.")
Enter a new password: Ramsjds9 Password is strong.
No comments:
Post a Comment
Note: only a member of this blog may post a comment.