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

Time:06-09

The actual question reads "create a function that loops through and prints all values less than 50, starting with 2, such that the value is doubled each iteration. should display: 2 4 8 16 32 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 Q6 < 50: result = Q6 * 2 print(result)

CodePudding user response:

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

CodePudding user response:

You can create a function with:

def question6(start, limit):
   
   value = start
   while value<limit:
      print(value)
      value*=2 #It does work!

question6(2,50)

I suggest reading the introductory tutorials: https://wiki.python.org/moin/BeginnersGuide/Programmers

  • Related