user3307366
user3307366

Reputation: 327

convert a for loop into a while loop

I am trying to figure out how to change a for loop into a while loop for this function:

def sumIt():
    A=1
    number=int(input('Enter a number(integer):'))
    total=0.0
    for counter in range(number):
        total+=A
        A+=1
    print('The sum from 1 to the number is:',total)
    averageIt(total,number)

#average sum and number
def averageIt(total,number):
    print('The average of the sum and the number is:',(total+number)/2)

sumIt()

would I just say:

while number>1:

Upvotes: 0

Views: 188

Answers (3)

Red Alert
Red Alert

Reputation: 3816

Why even use a loop at all?

Instead of

for counter in range(number):
        total+=A
        A+=1

Just use

total += (number*(number+1) / 2) - (A*(A-1)/2) # account for different starting values of A
A += number

Upvotes: 0

Maxime Lorant
Maxime Lorant

Reputation: 36161

You can by creating the counter yourself:

number=int(input('Enter a number(integer):'))
total = 0.0
counter = 0
while counter < number:
    total += A
    A += 1
    counter += 17

The for block is still the more Pythonic and readable way however. Also try to avoid to cast the result of an user input without verification/try block: if he entered 'abc', your code will raise the exception ValueError, since it's impossible to convert abc into an integer.

Upvotes: 1

Martijn Pieters
Martijn Pieters

Reputation: 1122092

You can increment the counter variable manually:

counter = 0
while counter < number:
    total += A
    A += 1
    counter += 1

or you could decrement the counter starting at number:

counter = number
while counter:
    total += A
    A += 1
    counter -= 1

where we use the fact that any non-zero number is True in a boolean context; the while loop will end once counter reaches 0.

You use counter instead of number here because you still need to use number later on for the averageIt() function.

Upvotes: 1

Related Questions