Search code examples
python-3.x

Using python range function for multiplication


I have a question referring to my python prp programming course that I have been struggling to grasp! This assignment has a question and basically I must define the function Power(x,n), which must raise the value x to the power of n! I am not allowed to use the operator "**" and also we can only use what was learned in the class so basically using if-else statements, boolean algebra, range, and for loops! It must only return a value for the inputted values! Help is greatly appreciated as I am struggling with this concept! The range function must be used... Thanks!


Solution

  • Try this:

    def power(x, n):
        result = 1
        for i in range(n):
            result *= x
        return result
    

    Which gives you the correct answers. Examples:

    >>> power(2, 3)
    8
    >>> 2**3
    8
    >>> 
    >>> power(4, 6)
    4096
    >>> 4**6
    4096
    

    Or if you're allowed to use the math module you can include negatives and fractions by generalizing to:

    def power(x, n):
        return math.exp(math.log(x) * n)
    

    Returning:

    >>> power(2, 0.5)
    1.414213562373095
    >>> power(2, -1)
    0.5
    >>>