-3

The line of code just prints out 'null' what am I doing wrong? I want to give the function the price and I want to pull out the price value that it produces. Also if anyone has a better code to turn the string $3,200.00 into a float I would be happy to use that.

price = 'null'

def ConvertPrice(currentprice):
    findcomma = currentprice.find(",")
    finddollar = currentprice.find("$")
    offer = currentprice.find('offer')
    if offer == -1:
        offer = currentprice.find('Offer')
    right = (currentprice[findcomma+1:])
    left = (currentprice[finddollar+1:findcomma])
    findinsideparenthsis = currentprice.find('(')
    if offer >= 0:
        if findcomma == -1:
            left = (currentprice[finddollar+1:findinsideparenthsis-1])
            price = float(left)
            return price   
        else:
            right = (currentprice[findcomma+1:findinsideparenthsis-1])
            left = (currentprice[finddollar+1:findcomma])
            price = float(left + right)
            return price
    elif findcomma == -1:
        right = (currentprice[findcomma+1:])
        left = (currentprice[finddollar+1:])
        price = float(left)
        return price
    else:
        right = (currentprice[findcomma+1:])
        left = (currentprice[finddollar+1:findcomma])
        price = float(left + right)
        return price
    
currentprice = '$3,200.00'        
ConvertPrice(currentprice)
print(price)

output is 'null'

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
DBraun
  • 38
  • 1
  • 7

1 Answers1

-2

When you modify the variable price in a function you have to make sure you pass the variable as an argument or refer to it in the function as global. Because you initialized it in the global scope when you modify it in the function you are just creating a new variable in the local scope. Just add in the first line of the function global price or you can also do def ConvertPrice(currentprice, price)

  • 1
    Python doesn't support pass-by-reference. But either way, OP is already returning the value from the function (`return price`), just needs to capture it (`price = ConvertPrice(currentPrice)`). So using a global in this case is not needed, and [bad practice](https://stackoverflow.com/q/484635/4518341). – wjandrea Dec 25 '20 at 21:42