Omar - 6 months ago 27

Python Question

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 calledwhich takes two`productOfPowersOf2`

arguments, both of which are non-negative integers. For purposes of

this problem, let's call the first argumentand the second`exp1`

argument. Your function should compute and return (not print) the`exp2`

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??

Answer

I assume the assignment says this?

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

^{exp1}to 2^{exp2}

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`