In the last session, we discussed the Set Operations. Now, we will look at Python's function Operations. The sets are the most important topic in Python.
Let’s start,
Definition of Function in Python
A function is a block of code that performs a specific task. Functions help in organizing code, reusing code, and improving readability.
Function Simple Syntax
def function_name(parameters):
# Function body
return expression
Why do we need to use functions
#input
#this code using with if else statement
num=24
if num%2==0:
print("the number is even")
else:
print("the number is odd")
#output
the number is even
#The same code using function
#input
def even_or_odd(num):
"""This function finds even or odd"""
if num%2==0:
print("the number is even")
else:
print("the number is odd")
even_or_odd(24)
#Output
the number is even
function with multiple parameters
#input
def add(a,b):
return a+b
result=add(2,4)
print(result)
#output
6
Default Parameters
#input
def greet(name):
print(f"Hello {name} Welcome To the Python Course")
greet("Babu")
#output
Hello Babu Welcome To the Python Course
Direct assigned Parameters
#input
def greet(name="babu"):
print(f"Hello {name} Welcome To the Python Course")
greet()
#output
Hello babu Welcome To the Python Course
Variable Length Arguments
#input
def print_numbers(*Peter):
for number in Peter:
print(number)
print_numbers(1,2,3,4,5,6,7,8,"Peter")
#output
1
2
3
4
5
6
7
8
Peter
Positional arguments
#input
def print_numbers(*args):
for number in args:
print(number)
print_numbers(1,2,3,4,5,6,7,8,"Peter")
#output
1
2
3
4
5
6
7
8
Peter
8.Keywords Arguments
#input
def print_details(**kwargs):
for key,value in kwargs.items():
print(f"{key}:{value}")
print_details(name="Peter",age="32",country="India")
#output
name:Peter
age:32
country:India
Combine Positional and Keywords Arguments
#input
def print_details(*args,**kwargs):
for val in args:
print(f" Positional arument :{val}")
for key,value in kwargs.items():
print(f"{key}:{value}")
print_details(1,2,3,4,"peter",name="jorge",age="32",country="India")
#output
Positional arument :1
Positional arument :2
Positional arument :3
Positional arument :4
Positional arument :peter
name:jorge
age:32
country:India
Return statements
#input
def multiply(a,b):
return a*b
multiply(2,3)
#output
6
Return multiple parameters
#input
def multiply(a,b):
return a*b,a
multiply(2,3)
#output
(6, 2)
Temperature Conversion
#input
def convert_temperature(temp,unit):
"""This function converts temperature between Celsius and Fahrenheit"""
if unit=='C':
return temp * 9/5 + 32 ## Celsius To Fahrenheit
elif unit=="F":
return (temp-32)*5/9 ## Fahrenheit to celsius
else:
return None
print(convert_temperature(25,'C'))
print(convert_temperature(77,'F'))
#output
77.0
25.0
Password Strength Checker with a function
#input
def is_strong_password(password):
"""This function checks if the password is strong or not"""
if len(password)<8:
return False
if not any(char.isdigit() for char in password):
return False
if not any(char.islower() for char in password):
return False
if not any(char.isupper() for char in password):
return False
if not any(char in '!@#$%^&*()_+' for char in password):
return False
return True
## calling the function
print(is_strong_password("WeakPwdd"))
print(is_strong_password("Str0ngPwd!@#"))
#output
False
True
Check IF a String Is a Palindrome
#input
def is_palindrome(s):
s=s.lower().replace(" ","")
return s==s[::-1]
print(is_palindrome("A man a plan a canal Panama"))
print(is_palindrome("Welcome to python"))
#output
True
False
Calculate the factorials of a number using function
#input
def factorial(n):
if n==0:
return 1
else:
return n * factorial(n-1)
print(factorial(5))
#output
120
Validate Email Address using a function
#input
import re
def is_valid_email(email):
"""This function checks if the email is valid."""
pattern = r'^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$'
return re.match(pattern, email) is not None
print(is_valid_email("[email protected]"))
print(is_valid_email("marcus.com"))
#output
True
False
Now, We have covered function operations with various examples and methods. In the next article, we will dive into advanced functions in Python.