How do I count the number of entries in a python code using while loops?

20,208

Every time you read an input total += int(entry), immediately afterward you should increment a variable.

num += 1 is all it would take, after you've initialized it to 0 elsewhere.

Make sure your indentation level is the same for all statements in the while loop. Your post (as originally written) did not reflect any indentation.

Share:
20,208
Admin
Author by

Admin

Updated on March 07, 2020

Comments

  • Admin
    Admin about 4 years

    I'm working on a homework assignment for my introductory python programming class and I am stuck on a problem. The instructions are to:

    Modify the find_sum() function so that it prints the average of the values entered. Unlike the average() function from before, we can’t use the len() function to find the length of the sequence; instead, you’ll have to introduce another variable to “count” the values as they are entered.

    I am unsure on how to count the number of inputs and if anyone can give me a good starting point, that would be great!

    # Finds the total of a sequence of numbers entered by user 
    def find_sum(): 
         total = 0 
         entry = raw_input("Enter a value, or q to quit: ") 
         while entry != "q": 
             total += int(entry) 
             entry = raw_input("Enter a value, or q to quit: ") 
         print "The total is", total 
    
  • BlackVegetable
    BlackVegetable about 11 years
    He was forbidden from using the len() function, according to the assignment directions though.
  • Admin
    Admin about 11 years
    Wow, that was so simple. I was definitely overthinking it. Thank you for all your help and I will definite fix the indentation!
  • BlackVegetable
    BlackVegetable about 11 years
    Glad I could help. Some friendly editor seems to have fixed your indentation in this post for you, but only you can fix the indentation in your code on your computer!
  • Rushy Panchal
    Rushy Panchal about 11 years
    @BlackVegetable Ah, should have read the OP more thoroughly. I will leave this up for reference, however.
  • Admin
    Admin about 11 years
    Sooo glad I discovered this website. I'm a first year Software Engineering major and I feel like this won't be the first time I post here! Such a cool, helpful place!
  • BlackVegetable
    BlackVegetable about 11 years
    I hope you enjoy it here! Be sure to select one of the questions as the "accepted answer" to this question by selecting the checkmark next to the score on the answer.