0

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:

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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

1 Comment

well... If you want to make the OP code more beautiful, just summarize with sum(range(number)) but I think the OP wants to play with loops just for training.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.