-1

Consider:

print("Welcome to the number program")
number = input("Please give me a number \n")
number = int(number)
total_number = 0
entries = 0

while number > 0:
    total_number = total_number + number
    print(total_number)
    number = input("Please give me another number! \n")
    number = int(number)
    entries = int(entries) + 1
if number < 0:
    print("Sorry, this value needs to be positive. Please enter a
different number.")

if number == -999:
    print(total_number)
    print(entries)
    print(total_number/entries)

I'm in a beginners programming class, and the book is not very helpful at times. I'm trying to write a basic program that takes positive numbers, totals them, and averages them out at the end. It also rejects negative numbers, and asks if -999 is entered. I print the average of all entries, amount of entries, and the value tally.

The program runs ok, but it just doesn't write out some things I wanted.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
  • Share the code you've written and where you are having trouble. Writing the application for you is not going to be a helpful learning exercise. – flakes Feb 11 '23 at 19:33
  • @flakes Thanks, I didn't realize the formatting parameters on the site – mrxblonde614 Feb 11 '23 at 19:37
  • 1
    If your code is working, your question is much too unfocused for SO. It *might* (check their expectations) be on focus on https://codereview.stackexchange.com/ – Thierry Lathuille Feb 11 '23 at 19:39
  • Why does it matter if you enter 0 or a negative number to terminate the loop? (And why would you expect `number` could be `-999` after telling the user a negative number is invalid?) – chepner Feb 11 '23 at 19:40
  • 1
    It looks like you might have some indentation issues, but that may just be how you pasted the code above. Both `if` statements should be indented to be within the `while` loop. For your loop quitting condition, just have `if number = -999: break`. Then put all of the printing info outside of the while loop. A few other notes 1) You don't have to have `int(entries)` because entries will always be an int. 2) Your call of `number = int(number)` may directly force the program to stop due to an Exception if the user input can't be converted to an int. – nigh_anxiety Feb 11 '23 at 19:45
  • Welcome to Stack Overflow! Please take the [tour]. This site is for specific questions, so this is too broad. Try focusing on one problem at a time. See [ask]. But FWIW, there's an existing question for at least part of what you're asking: [Asking the user for input until they give a valid response](/q/23294658/4518341). – wjandrea Feb 11 '23 at 21:04
  • To clarify what @Thierry said: *If* your code were working properly but you wanted to improve it, then you could ask on [codereview.se]. See [their tour](https://codereview.stackexchange.com/tour) for an overview of their requirements. – wjandrea Feb 11 '23 at 21:07
  • Re *"The program runs ok"*: No, not as entered here. The code as entered results in "`SyntaxError: invalid syntax ... IndentationError: unexpected indent`" near "`print("Sorry, this value`" – Peter Mortensen Feb 27 '23 at 16:40

3 Answers3

3

From what you wrote and the comments in your code I am guessing that you want the program to continue running and asking for input if you enter a non-positive number. In that case I would rewrite it as:

print("Welcome to the number program")
total_number = 0
entries = 0

while True:
    number = input("Please give me a number \n")
    number = int(number)

    if number == -999:
        break

    if number <= 0:
        print("Sorry, this value needs to be positive. Please enter a different number.")
        continue

    total_number = total_number + number
    entries += 1
    print(total_number)

print(total_number)
print(entries)
print(total_number / entries)

Also, you can increment numbers with entries += 1

  • This was really helpful Martin, The program I had running would not continue after I entered in a negative number, but yours did. I'm guessing The While True was crucial there so I should look to use that more in loops going forward. – mrxblonde614 Feb 12 '23 at 20:10
  • @mrxblonde614 while loops in Python are not that commonly used in general, usually for loops are used a lot more because they are more readable and you can't accidentally make an infinite loop that is hard to debug with them. But for this specific problem where the end of the loop depends on an operation done inside of the loop it makes sense. I don't think using `while True` more in the future is the correct conclusion to take from this. Just get more comfortable with control flow in general and you will learn what is the correct loop pattern for a specific problem. Good luck. – martinkozle Feb 13 '23 at 00:03
1
  1. In most cases you should NOT create variables first, however this case you should. Create number = 0, tally = 0 and total_number = 0 first
  2. Accept your first number inside your while loop and handle all of the logic in there as well.
  3. Your while loop should continue to loop until the final condition is met which seems to be number == -999
  4. Should tally be incremented if you enter a negative number? I assume not. What about a 0? Wrap the increment for tally and the addition to total_number in an if number > -1: condition. Use an if else to check for number == -999, and an else for handling invalid entries.
  5. Finally, move your print statements outside of your while loop. It also doesn't need a condition around it because now, if you've exited your while loop, that condition has been satisfied.

Final note here, and this is just a nice to know/have and purely syntactic sugar, MOST languages support abbreviated incrementing. Theres a better word for it, but the gist is simply this.

total_number += number
# is exactly the same as 
total_number = total_number + number
# but way nicer to read and write :)
    print("Welcome to the number program")
    number = 0
    total_number = 0
    entries = 0

    while number != -999:
        number = input("Please enter a number! \n")

        number = int(number)

        if number >= 0
            total_number += number
            entries += 1
            print("Current sum: " + total_number)
        elif number == -999:
            break
        else
            print("Sorry, this value needs to be positive.")

    
    print("Sum of entries: "+str(total_number))
    print("Number of entries: " + str(entries))
    print("Average entry: " +str(total_number/entries))
ClearlyClueless
  • 545
  • 2
  • 13
0

I have rewritten your code. But I am not sure what the goal was. Anyways, if the value were ever to be under 0 the loop would have been exited and a new value would have never been accepted from an input. Also some things I have written more elegant.

print("Welcome to the number program")
number=int(input("Please give me a number \n"))
total_number=0
entries=0

while number > 0:
    total_number += number
    print(total_number)
    number = int(input("Please give me another number! \n"))
    entries += 1
    if number == -999:
        print(total_number)
        print(entries)
        print(total_number/entries)
        break
    elif number < 0:
        number = input("Sorry, this value needs to be positive. Please enter a different number!")
  • What would be the best way to add strings at the end to display "This is the..." for total number or entries? When I add print("The total number is" total_number) I know thats incorrect because the variable total_number isn't in the quotes – mrxblonde614 Feb 11 '23 at 20:05
  • You can do: `print("Total entries:\t\t" + str(total_number))` or `print(f"Total entries:\t\t{total_number}")` which is a little more elegant. This will format the values with tabs in front of them. – Andreas Sabelfeld Feb 11 '23 at 20:08
  • Great, this was very helpful as i knew parts but couldn't piece it together. One more, The loop is not breaking with how you edited what I wrote; when I entered in -999 its registers as a negative number and asks for another. Any tips on this? I'm just trying to get these loops down pat – mrxblonde614 Feb 11 '23 at 20:20
  • The logic here is a little suspect. Number == -999 needs to be checked before < 0 or else you'll never hit the break and print the values. – ClearlyClueless Feb 11 '23 at 20:30
  • Oh you're right. I've written this in a hurry and haven't noticed that. – Andreas Sabelfeld Feb 11 '23 at 20:52