fb pixel

Introduction to Python

  • Profound Academy

    • Status
      • 1
        Input and Output
      • 2
        Variables and Integer Arithmetic
      • 3
        Conditional Operators
      • 4
        Advanced Conditions - Nesting
      • 5
        Types and Variables
      • 6
        Strings
      • 7
        Lists
      • 8
        For Loops
      • 9
        While Loops
      • 10
        continue, break, while...else
      • 11
        String and List methods
      • 12
        Nested Loops
      • 13
        List Comprehension
      • 14
        Tuples and Sets
      • 15
        dict
      • 16
        Functions
      • 17
        Functions 2
      • 18
        Lambda and higher-order functions
      • 19
        Files

  • Multiple return values

    Python is very flexible when dealing with functions and it’s possible to return several values from a function:
    def f():
    	return 107, 'hello', [8, 9, 10]
    
    print(f())        # (107, 'hello', [8, 9, 10])
    a, b, c = f()
    print(a)          # 107
    print(b)          # hello
    print(c)          # [8, 9, 10]
    In this example, f() function returns 3 values (107, 'hello', and [8, 9, 10]). We can assign each returned value to a variable with a, b, c = f().
    The most interesting part is that there is no magic in returning several values. What the function f() does is actually return a single value - a tuple that has 3 elements (107, 'hello', and [8, 9, 10]). When printing the whole returned value with print(f()), we can see that the returned value is actually a tuple (note the parentheses). When a function returns a tuple, we just unpack the values into a, b, and c.
    So, in reality, the functions always return a single value - but we can interpret returning a tuple as returning multiple values.

    Challenge

    Write a function that would return the whole part and the remainder after dividing a by b.
    The input contains two integers - a and b.
    The program should print 3 lines. Each line should contain the whole part after and the remainder after the division of two numbers:
    • The first line should contain the result for a and b.
    • The second line should contain the result for a + 1 and b + 1.
    • The third line should contain the result for a - 1 and b - 1.
    Input
    Output
    7 4
    1 3 1 3 2 0
     
    To check your solution you need to sign in
    Sign in to continue