dev
dev

Reputation: 811

How to return multiple Values from a function?

Im returning multiple values inside the fizz buzz function and I want to use a separate function to count the number of times Fizz, Buzz and FizzBuzz was returned. The counter is not finished yet but im trying to understand what the correct way is to return and insert multiple values or strings fron one single function into another.

import random
n = random.randint(1,30)

def fizzbuzz_counter(Fizz,Buzz,FizzBuzz):
    print(Fizz,Buzz,FizzBuzz)
    #Counter not finished yet

def fizzbuzz(n):
    for i in range(1,n+1):
        if i % 3 == 0 and i % 5 == 0:
            FizzBuzz = "FizzBuzz"
            print(FizzBuzz)   
            return(FizzBuzz)
        elif i % 3 == 0:
            Fizz = "Fizz"
            print(Fizz)
            return Fizz
        elif i % 5 == 0:
            Buzz = "Buzz"
            print(Buzz)
            return Buzz
        else:
            print(i)

fizzbuzz(n)
fizzbuzz_counter(fizzbuzz(FizzBuzz,Fizz,Buzz))

Upvotes: 0

Views: 139

Answers (1)

Stuart Mackintosh
Stuart Mackintosh

Reputation: 48

The first issue that you have is that once a python function returns a value it stops. So your fizzbuzz function will return only once and since you are always starting your for loop from 1 the return value will always be the same (assuming that n is equal to or greater than 3. for example fizzbuzz(10) and fizzbuzz(123) will always return 'fizz' (and print out 1,2,fizz before returning. This is because it will return once i equals 3. If you want the function to 'return' multiple values as it loops you should check out generator functions

However the simplest solution is probably to have fizzbuzz keep track of the count internally and return all 3 values at once:

def fizzbuzz(n):
    fizzbuzz=0
    fizz=0
    buzz=0
    for i in range(1,n+1):
        if i % 3 == 0 and i % 5 == 0:
            print("FizzBuzz")   
            fizzbuzz += 1
        elif i % 3 == 0:
            print("Fizz")
            fizz += 1
        elif i % 5 == 0:
            print("Buzz")
            buzz += 1
        else:
            print(i)
    return fizzbuzz, fizz, buzz

Upvotes: 1

Related Questions