Omar - 1 year ago 101
Python Question

# Python While Loop for Products of Powers of 2

I need help creating a function that uses a while loop in order to find the products of powers of 2.

Here's the question:

Create a Python function called
`productOfPowersOf2`
which takes two
arguments, both of which are non-negative integers. For purposes of
this problem, let's call the first argument
`exp1`
and the second
argument
`exp2`
. Your function should compute and return (not print) the
product of all powers of 2 from 2exp1 to 2exp2. Here are some examples
of how your function should behave:

``````>>> productOfPowersOf2(0,0)
1
>>> productOfPowersOf2(1,1)
2
>>> productOfPowersOf2(1,2)
8
>>> productOfPowersOf2(1,3)
64
``````

what i have written is:

``````def productsOfPowersOf2(exp1,exp2):
total=0
num=0
while num<=exp2:
total=(2**exp1)*(2**(exp1+num))
num=num+1
return(total)
``````

but this doesnt work. can anyone help??

I assume the assignment says this?

Your function should compute and return (not print) the product of all powers of 2 from 2exp1 to 2exp2

1) You aren't taking the cumulative product; you only reassigned `total` to the next value.

``````total=(2**exp1)*(2**(exp1+num))
``````

In other words, when the loop exits, you only get this, which is too probably always greater than the value you want, if I had to guess

``````total=(2**exp1)*(2**(exp1+exp2))
``````

Hint: You could use math. `x^y * x^z = x ^ (y + z)`. Sum the exponents before you take the power of two.

SPOILER

```def productOfPowersOf2(exp1,exp2): total = 2**exp1 exp1 += 1 while exp1 <= exp2: total *= 2**exp1 exp1 += 1 return total```

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download