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 (27) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (114) C (77) C# (12) C++ (82) Course (60) Coursera (176) coursewra (1) Cybersecurity (22) data management (11) Data Science (87) Data Strucures (6) Deep Learning (9) Django (6) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (5) flutter (1) FPL (17) Google (19) Hadoop (3) HTML&CSS (46) IBM (25) IoT (1) IS (25) Java (92) Leet Code (4) Machine Learning (44) Meta (18) MICHIGAN (5) microsoft (3) Pandas (3) PHP (20) Projects (29) Python (740) Python Coding Challenge (188) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (2) Software (17) SQL (40) UX Research (1) web application (8)

Followers

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