Search code examples
pythonloopsmultiplication

how to keep multiplying a number until you reach a specific point in python?


I am just beginning python, and I have tried to look up different ways. I know you can add the result with += but that doesn't work with multiplication. I know this is ALL wrong but my code so far is:

Q6=2

while x < 50: result = x * 2 print(result)


Solution

  • You can actually use *= if you want to both assign and multiply to a function in one operation, in fact this same pattern exists for most operators in python (e.g. /=, -=, <<=)

    What you need to do here is actually change the value of Q6 as loop goes on, like this:

    Q6 = 2
    while (Q6 < 50):
        print(Q6)
        Q6 *= 2
    

    Because since every number is double the one before, you can just replace Q6 with the previous number