Home > Back-end >  How can I use a syntax for set of numbers in a single line
How can I use a syntax for set of numbers in a single line

Time:10-02

def punch_your_three_brothers_in_order_of_age(a, b, c):
    list = [a, b, c]
    if type(a) == str:
        return "Please use numbers for each brother's age."
    elif type(b) == str:
        return "Please use numbers for each brother's age."
    elif type(c) == str:
        return "Please use numbers for each brother's age."
    else:
        list.sort(reverse=True)
        A = list
        return "Start with the "   str(A[0])   " year old, then continue with your "   str(A[1])   " year old brother."

I want the program to return "Please use numbers for each brother's age." when a, b or c is not numeric. I want to code that in a single line, I tried something like this:

if type(a, b, c) != int or float:
    print("Please use numbers for each brother's age.")

But that code doesn't work. How can I do it within a single line?

CodePudding user response:

You have the right idea to use the boolean or operator. However, it doesn't quite work the way you want. Instead, you need to take the type() of each variable one at a time and compare with each type separately:

if type(a) != float and type(a) != int:
    print("Please use numbers for each brother's age.")

Alternatively, you can use the not in operator:

if type(a) not in (int, float):
    print("Please use numbers for each brother's age.")

Alternatively, you can put the variables in a list:

brothers = [a, b, c]

if any(type(bro) not in (float, int) for bro in brothers):
    print("Please use numbers for each brother's age.")

CodePudding user response:

Assuming the inputs are strings that may or may not have numeric values (e.g. returned by the input()) function, what you want to do is convert them into numbers, and catch any resulting ValueError:

def punch_your_three_brothers_in_order_of_age(a, b, c):
    try:
        ages = sorted(int(i) for i in [a, b, c])
    except ValueError:
        print("Please use numbers for each brother's age.")
    print(f"Start with the {ages[0]} year old...")

If the inputs already have the int or float type, converting them to int won't raise a ValueError so this same approach will work fine.

CodePudding user response:

this function checks if all it`s arguments have number type:

def is_num(*args):
res = True
for i in args:
    if type(i) not in [float, int]:
        res = False
return res

print(is_num(255, 25235, 213.4))
print(is_num("sdad", 12, 12.5))

outputs to console:

True
False

CodePudding user response:

The easiest solution is to use or to create one big line of if checking.

if not ((type(a) in (int, float)) or (type(b) in (int, float)) or (type(c) in (int, float))):

But thats a little cumbersome and convoluted, so maybe some checking with any?

if any((not type(v) in (int, float) for v in [a, b, c])):
  • Related