Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (16.4k points)

I attempted to solve an issue, composing a force by a function that does the same work as the operator ** (by python for instance) after I settle it, I got another task: I'm permitted to utilize just one loop and only one if\else. 

I would adore for some understanding I'm a beginner and do not understand how to go further.

Here's my code:

def power(x, y):

    s = x

    if y > 0:

        for i in range (1, y):

            s = s * x

    elif (y < 0):

        for i in range (y, -1):

            s = s * x

        s = 1 / s

    else:

        s = 1

    return s

print(power(3, 5))

print(power(3, -5))

print(power(3, 0))

1 Answer

0 votes
by (26.4k points)
edited by

Try the below code, where you can use abs function:

from typing import Union

def power(x: Union[float, int], y: int) -> Union[float, int]:

    s: Union[float, int] = 1

    for _ in range(abs(y)):

        s *= x

    if y < 0:

        s = 1 / s

    return s

assert power(3, 5) == 243

assert 0.0040 < power(3, -5) < 0.0042

assert power(3, 0) == 1

Are you looking for a good python tutorial course? Come, Join and get certified by joining the python certification course.

Watch this video tutorial on how to become a professional in python course:

Related questions

0 votes
1 answer
asked Feb 14, 2021 in Python by ashely (50.2k points)
0 votes
1 answer
asked Jan 10, 2021 in Python by ashely (50.2k points)
0 votes
1 answer
0 votes
1 answer
asked Dec 12, 2020 in Python by ashely (50.2k points)

Browse Categories

...