-2

I'm new to Python and after going through an example using a function to raise a number to a specific exponent, I tried to have it as the user for the numbers instead of just inputting them into the code.

Below is what I have:

def raise_to_power(base_num, pow_num):
    int(base_num)
    int(pow_num)
    result = 1
    for index in range(pow_num):
        result = result * base_num2

    return result


base_num = input("What number would you 
like to exponentially raise?: ")

pow_num = input("To what power?: ")

print(raise_to_power(base_num, pow_num))`

When I try to run it though, I get the error listed below:

Traceback (most recent call last):
File "C:/Users/PycharmProjects/Exponent 
Function.py", line 17, in <module>
print(raise_to_power(base_num, pow_num))
File "C:/Users/PycharmProjects/Exponent 
Function.py", line 7, in raise_to_power
for index in range(pow_num):
TypeError: 'str' object cannot be 
interpreted as an integer

Could someone explain why this might be happening?

Thank you,

4 Answers4

0

int(base_num) doesn't change the argument. To convert the base_num to string and save into the same variable use:

base_num = int(base_num)

This code sample shows some weaknesses of the design: why should base_num be of the string type initially. Try to call the variables with more meaningful names that would avoid this confusion.

Dmitry Kuzminov
  • 6,180
  • 6
  • 18
  • 40
0

your conversion of input string to integer is not correct.

Try the below code:

def raise_to_power(base_num, pow_num):  
    result = 1
    for index in range(int(pow_num)):
        result = result * int(base_num)
    return result
0

You did two mistake. 1- int(base_num) is not good way to type casting. 2- In method you are passing base_num but in for loop you are using base_num2. Here is the correct code.

def raise_to_power(base_num, pow_num):
    result=1
    for index in range(int(pow_num)):
        result = result * int(base_num)
    return result
base_num = input("What number would you")
pow_num = input("To what power?: ")
print(raise_to_power(base_num, pow_num))
Vaibhav Mishra
  • 227
  • 2
  • 11
0
def raise_to_power(base_num, power_num):

    result = 1

    for index in range(power_num):
        result = result * base_num

    return result 
          
base_num = input("enter a base number you want : ")
power_num = input("enter the power of base number : ")

print(str(raise_to_power(int(base_num), int(power_num))))
David Buck
  • 3,752
  • 35
  • 31
  • 35