Python – Functions Examples

Example 1 :

# Define a function
def greet():
    print("Hello, World!")

# Call the function
greet()

Output :

Hello, World!

Example 2 :

# Define a function with parameters
def greet(name):
    print(f"Hello, {name}!")

# Call the function with an argument
greet("Alice")

Output :

Hello, Alice!

Example 3 :

# Define a function with two parameters
def add(a, b):
    return a + b

# Call the function with arguments
result = add(3, 4)
print(result)

Output :

7

Example 4 :

# Define a function that returns a value
def square(x):
    return x * x

# Call the function and store the result
result = square(5)
print(result)

Output :

25

Example 5 :

# Define a function that returns multiple values
def get_name_and_age():
    name = "Alice"
    age = 30
    return name, age

# Call the function and unpack the result
name, age = get_name_and_age()
print(name, age)

Output :

Alice 30

Example 6 : (Area of Circle using Functions)

def areaofcircle(r):
    answer=3.14*r
    return answer

radius=int(input("Enter Radius Value"))
ans=areaofcircle(radius)
print ("Answer",ans)

Output :

Enter Radius Value 1
Answer 3.14

Example 7 :

def welcome(myname):
    msg="Hi " +myname + " Welcome to My Centre"
    return msg;

    
m=input("Enter Your Name : ")
print(welcome(m))

Output :

Enter Your Name : Raj
Hi Raj Welcome to My Centre

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *