Search code examples
pythonbottle

Running function within template file (Python/Bottle)


I'm using bottle to create a simple retirement calculator of sorts, but I'm having trouble with the template file's handling of python code. For example, I have this code

<%
import statistics, numpy

medianStockReturn = []

def stockReturn():
    global medianStockReturn
    yearStockReturn = numpy.random.normal(11.4, 19.7, 1000)
    yearMedianStockReturn = statistics.median(yearStockReturn)
    yearMedianStockReturn = yearMedianStockReturn / 100 + 1
    medianStockReturn.append(yearMedianStockReturn)
stockReturn()
end
%>

<!DOCTYPE html>
<html lang = "en-us">
    <head>
        <title>Retirement Calculator</title>
        <meta charset = "utf-8">
        <link rel="stylesheet" type="text/css" href="../static/retirementStyle.css">
   </head>
   <body>
       <h2> this is a test; your stock return is {{medianStockReturn}}</h2>
   </body>
</html>

However, this code results in an output of: "this is a test; your stock return is []"

As written, the function should append medianStockReturn with a generated value, but it does not, and I am not exactly sure why.


Solution

  • You need to move the end to after the end of function definition above stockReturn()

    <%
    import statistics, numpy
    
    medianStockReturn = []
    
    def stockReturn():
        global medianStockReturn
        yearStockReturn = numpy.random.normal(11.4, 19.7, 1000)
        yearMedianStockReturn = statistics.median(yearStockReturn)
        yearMedianStockReturn = yearMedianStockReturn / 100 + 1
        medianStockReturn.append(yearMedianStockReturn)
    end
    stockReturn()
    %>
    
    <!DOCTYPE html>
    <html lang = "en-us">
        <head>
            <title>Retirement Calculator</title>
            <meta charset = "utf-8">
            <link rel="stylesheet" type="text/css" href="../static/retirementStyle.css">
       </head>
       <body>
           <h2> this is a test; your stock return is {{medianStockReturn}}</h2>
       </body>
    </html>