Zoey
Zoey

Reputation: 47

Why does my function return the "else" of a statement and not the "while"

No matter the input, the function always prints "Enter a number".

def AddNum(n1, n2, n3, n4):
    while n1 and n2 and n3 and n4 == int:
        x = n1 + n2 + n3 + n4
        return x
    else:
        print("Enter a number.")

Upvotes: 0

Views: 30

Answers (1)

adder
adder

Reputation: 3698

It's rather unclear why do you want a loop inside that, since a simple if statement would do the trick. Besides that, that's not how you do type checking - consider using isinstance(). Also, you might want your function to work with arbitrary number of arguments:

def add_num(*args):
    if all(isinstance(arg, int) for arg in args):
        return sum(args)
    else:
        return 'Arguments must be integers.'

...which could be additionally shortened to:

def add_num(*args):
    return sum(args) if all(isinstance(arg, int) for arg in args) else 'Arguments must be integers.'

>>> add_num('spam', 1)
Arguments must be integers.
>>> add_num(1, 2)
3
>>> add_num(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
55

You may as well want to read what PEP8 says about naming conventions when it comes to functions.

Upvotes: 3

Related Questions