user12386893
user12386893

Reputation: 9

why do i get a none in my code at the end even whilst using return

I originally had this code and it would be fine for 1-99 but for the 100th it would say "None":

def f(n):
    for i in range(1, n):
        if i % 3 == 0 and i % 5 == 0:
            print("bacon and egg")
        elif i % 5 == 0:
            print("egg")
        elif i % 3 == 0:
            print("bacon")
        else:
            print("neither")

print(f(100)) 

So I tried to correct it and for this part of my code it comes up with a "NameError: name 'neither' is not defined" as I tried to include return to no longer get the none:

def f(n):
    for i in range(1, n):
        if i % 3 == 0 and i % 5 == 0:
            return bacon and egg
        elif i % 5 == 0:
            return egg
        elif i % 3 == 0:
            return bacon
        else:
            return neither

print(f(100)) 

How would I fix this to no longer get the none?

Upvotes: 0

Views: 48

Answers (2)

David Silveiro
David Silveiro

Reputation: 1602

Focusing on your 2nd example, it seems like the NameError is due to the fact neither isn't actually a populated variable, in which case, you could wrap it up as a string and return it :)

Example

def f(n):
    for i in range(1, n):
        if i % 3 == 0 and i % 5 == 0:
            return 'bacon and egg'
        elif i % 5 == 0:
            return 'egg'
        elif i % 3 == 0:
            return 'bacon'
        else:
            return 'neither'

print(f(100)) 

Upvotes: 1

Harish Vutukuri
Harish Vutukuri

Reputation: 1150

Replace print(f(100)) with f(100) to remove None.

def f(n):
    for i in range(1, n):
        if i % 3 == 0 and i % 5 == 0:
            print("bacon and egg")
        elif i % 5 == 0:
            print("egg")
        elif i % 3 == 0:
            print("bacon")
        else:
            print("neither")

f(100)

Upvotes: 0

Related Questions