Home > Net >  How to access a specific variable created inside a function outside a function. Even when there are
How to access a specific variable created inside a function outside a function. Even when there are

Time:10-25

I am new to programming and I am trying to teach myself. I am starting with python and I am struggling to figure out if I am going about this the right way. I am trying to figure out how to access a specific variable from inside a function outside of that function.

weight = input('Enter Amount: ')

def quantity():
  p_total = weight / 454
  print(f'Amount: {p_total}')
  
  hp_total = weight / 227
  print(f'Amount HP: {hp_total}')
  
  qp_total = weight / 114
  print(f'Amount QP: {qp_total}')

  return p_total, hp_total, qp_total

print(qp_total)

I want to then be able to access the individual variables created in there as needed. Such as being able to call just qp_total or p_total. Or would this not be a good use of a function? Again I am still extremely new to coding.

CodePudding user response:

As your result is a tuple, you can provide an index to retrieve the item you want from that tuple:

def quantity(weight):
    p_total = weight / 454
    hp_total = weight / 227
    qp_total = weight / 114
    return p_total, hp_total, qp_total

print(quantity(50)[2]) # 0.43859649122807015

If you want to have multiple items, but not the whole result, then you may use _ for the "empty" output (although technically not really "empty"):

p_total, _, qp_total = quantity(50)
print(p_total, qp_total) # 0.11013215859030837 0.43859649122807015

A concept like "accessing internal variables from outside" sounds more like pertaining to "class":

class Quantity():
    def __init__(self, weight):
        self.p_total = weight / 454
        self.hp_total = weight / 227
        self.qp_total = weight / 114

q = Quantity(50)
print(q.qp_total) # 0.43859649122807015

But in my opinion, it is an overcomplication in this case.

CodePudding user response:

You never actually call your quantity function. Plus you should really pass the weight variable in:

def quantity(weight):
  p_total = weight / 454
  print(f'Amount: {p_total}')
  
  hp_total = weight / 227
  print(f'Amount HP: {hp_total}')
  
  qp_total = weight / 114
  print(f'Amount QP: {qp_total}')

  return p_total, hp_total, qp_total

weight = input('Enter Amount: ')
p_total, hp_total, qp_total = quantity(weight)
print(qp_total)

CodePudding user response:

def quantity(weight):
  p_total = weight / 454
  hp_total = weight / 227
  qp_total = weight / 114
  return p_total, hp_total, qp_total

weight = int(input('Enter Amount: '))
p_total = quantity(weight)[0]
hp_total = quantity(weight)[1]
qp_total = quantity(weight)[2]
print(qp_total)

The weight input must be converted to an integer because in python the input is passed as a string.

  • Related