Skip to content
Sign upLog in
← Back to Community

How do you add an exponent function?

Profile icon
IMACODERBOIZ

Hey all,

I was just coding a calculator for fun in python and I wasn't sure how to add an exponent function. Can anyone help me?

Thanks

Voters
Profile icon
doom2679
Profile icon
IMACODERBOIZ
Comments
hotnewtop
Profile icon
IMACODERBOIZ

Alright thank you for helping me guys

Profile icon
Axrevyn

@IMACODERBOIZ

First, you should mark an answer as correct.
Second, have you checked out the calculator? I fixed and finished the area function. I also left some notes that you should probably look through.

Profile icon
IMACODERBOIZ

@Axrevyn

Yes I have checked out the calculator, thanks a lot. But I was wondering what does global choice mean and why did you use it?

Profile icon
Axrevyn

@IMACODERBOIZ
It declares a global variable. If a variable is defined inside of a function, it is specific to that function - which means the same variable can have different values depending on where it is called. That can be really inconvenient at times, so calling a global variable makes sure that I'm using the global version, not the function-specific one.

Example:

def definevar(): var = "1" print(var) var = "2" definevar() print(var)

Both of those print the variable var. However, this code will output

1 2

Even though it's printing the same variable. Using global negates that.

Profile icon
Coder100

There's 4 ways to do this!

1. operator

print(2 ** 3)

2. math

import math print(math.pow(2, 3))

3. loop

def exponent(b, p): val = 1 for i in range(1, p + 1): val *= b return val

4. recursion

def exponent(b, p): if p == 1: return b return b * exponent(b, p - 1)
Profile icon
Axrevyn

A while loop, I suppose?

num=int(input("number: ")) exponent=int(input("exponent: ")) ans = num while exponent>1: ans = ans*num exponent = exponent-1 print(str(ans))

I whipped this up in five minutes, you should probably test it before using it.

Profile icon
IMACODERBOIZ

@Axrevyn

Actually, I searched it up on google and you need to do this pow(base, exponent) in the answer spot. But I think a while loop could work too. BTW, do you wanna work on this calculator together?

Profile icon
Axrevyn

@IMACODERBOIZ
Revised it

num=int(input("number: ")) exp=int(input("exponent: ")) ans = num if exp >= 2: while exp>1: ans = ans*num; exp = exp-1 elif exp == 1: pass elif exp == 0: ans = 1 print(str(ans))

And I realize that there are better ways to do this. Heh.

I'll work with you, why not?