Home > front end >  Converting a for loop to a while loop ( with a range involved)
Converting a for loop to a while loop ( with a range involved)

Time:11-03

Converting this to a while loop is turning out to be more trouble than initially thought. Any tips or tricks on how to solve this would be appreciated

sum = 0
for i in range (10,0,-1):
    sum = sum  1
    print(i,sum)

this is as close as i can get -

i=1
while i in range(10,0,-1):
    print(i)
    print(i, end=' ')
    i=i 1

the hard part seems to be the range numbers this is a specific questions ( i know a for loop is a better solution than a while loop)

CodePudding user response:

I think this code will do what you expect

s = i = 10
while i > 0:
    print(i, s-i 1)
    i=i-1

note: Unless you have a very specific reason to use variable names that have the same name as built-in functions, it is recommended to use a variable name that does not interfere with built-in function names. In the code you provided in the question, the built-in sum function is overwritten with an integer value. Check out the list of built-in names: https://docs.python.org/3/library/functions.html

CodePudding user response:

Your guess was too close to get the same result using while loop. Use two , len() and list() function , to get the same outputs.

i=1
while i in range(10,0,-1):
print(len(list(range(10,0,-1)))-i 1,i)
i=i 1

Thankyou hope it helps

  • Related