Power Function using Loops
<p>I just started Python 2.7.
I am trying to make a program that executes power function (using loops) without using <strong>import. math</strong>
I think I got it except my program does not execute negative exponents.
The output only comes out as 1.
Here is what I have so far. </p>

<pre><code>decimal=float(input('Enter the base number:'))
integer=int(input('Enter the exponent number:'))

def power_function(decimal, integer):
    num=1
    for function in range(integer):
        if integer&gt;0:
            num=num*decimal
        if integer&lt;0:
            num=1/(num*decimal)
    return num
print power_function(decimal, integer)
</code></pre>

<p>Simple fix is to use <code>abs(integer)</code> for your <code>range</code>:</p>

<pre><code>def power_function(decimal, integer):
    num = 1
    for function in range(abs(integer)):
        num = num*decimal if integer &gt; 0 else num/decimal
    return num

power_function(2, 2)
# 4
power_function(2, -2)
# 0.25
</code></pre>

<p>Or just using reduce:</p>

<pre><code>def power_function(decimal, integer):
    op = (lambda a, b: a*b) if integer &gt; 0 else (lambda a, b: a/b)
    return reduce(op, [decimal]*abs(integer), 1)

power_function(3, 3)
# 27
</code></pre>

python python-2.7 function loops