Sunday, 18 February 2024

The Amazing Technique of Returning Results in Python Functions

 


1. Single Return Value:

def add_numbers(a, b):
    result = a + b
    return result
sum_result = add_numbers(3, 4)
print(sum_result)  # Output: 7
#clcoding.com
7

2. Multiple Return Values:

def operate_numbers(a, b):
    addition = a + b
    subtraction = a - b
    multiplication = a * b
    return addition, subtraction, multiplication
result_tuple = operate_numbers(5, 3)
print(result_tuple)
# Output: (8, 2, 15)
# Unpack the tuple
add_result, sub_result, mul_result = operate_numbers(5, 3)
print(add_result, sub_result, mul_result)
# Output: 8 2 15
#clcoding.com
(8, 2, 15)
8 2 15

3. Returning a Dictionary :

def get_person_info(name, age):
    person_info = {'Name': name, 'Age': age}
    return person_info
info_dict = get_person_info('John', 30)
print(info_dict)
# Output: {'Name': 'John', 'Age': 30}
#clcoding.com
{'Name': 'John', 'Age': 30}

4. Returning None:

def simple_function():
    print("This function does something")
result = simple_function()
print(result)  # Output: None
#clcoding.com
This function does something
None

5. Returning Early:

def divide(a, b):
    if b == 0:
        print("Cannot divide by zero.")
        return  # Exit the function early
    result = a / b
    return result
result = divide(8, 2)
print(result)  # Output: 4.0
#clcoding.com
4.0

0 Comments:

Post a Comment

Popular Posts

Categories

AI (33) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (146) C (77) C# (12) C++ (82) Course (67) Coursera (198) Cybersecurity (24) data management (11) Data Science (106) Data Strucures (8) Deep Learning (13) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (21) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (46) Meta (18) MICHIGAN (5) microsoft (4) Nvidia (1) Pandas (3) PHP (20) Projects (29) Python (893) Python Coding Challenge (285) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (42) UX Research (1) web application (8)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses