How to get one variable from multiple return variables

Question:

Hi All I have a function that returns multiple variables. Based on a specific value of x, I want to get one variable from the function. I have tried using "_" to assign the variables I do not need like a, _, _ = func() but its not working. Below is my sample code for demonstration. Thanks in advance.

x1 = 1
x2 = 3
x3 = 4

def func():
    if x1 == 1:
       a = x1 + 2
    if x2 == 2:
       b = 6
    if x3 == 3:
       c = x3 + 8

  return a, b, c

def get():
   if x1 == 1:
      a, _, _ = func()

get()
Asked By: daniel

||

Answers:

When the second if condition is false, you never assign b, so you get an error when you try to use it in return a, b, c.

You can solve this problem by giving all the variables default values first.

def func():
    a = b = c = None
    if x1 == 1:
       a = x1 + 2
    if x2 == 2:
       b = 6
    if x3 == 3:
       c = x3 + 8

    return a, b, c
Answered By: Barmar
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.