Python Forum
while loop - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: while loop (/thread-38350.html)



while loop - idddj - Oct-01-2022

So I was required to solve this question: Write a program to use a while loop to read the numbers from the user repeatedly until he/she inputs 0. Then report the sum of these numbers and the minimum value among them.

And my code for the sum part is like this:
sum1 = 0
n = int(input())
while n != 0:
    sum1 += n
print(sum1)
But when I run the code and input some integer, it does not show the sum although I have input a 0 lastly. Could someone tell me what the problem is in my code?


RE: while loop - Yoriz - Oct-01-2022

The input is not part of the loop, input is only taken once before the loop so n will always stay the same.


RE: while loop - idddj - Oct-01-2022

May I ask how to improve it? Cry


RE: while loop - Yoriz - Oct-01-2022

The answer is in your requirements
Quote:Write a program to use a while loop to read the numbers from the user repeatedly
get input inside the loop.


RE: while loop - rob101 - Oct-01-2022

Don't be afraid of using descriptive names for your variables and as well as some interface message.

As an example:
user_number = int(input("Enter a integer value (0 to finish)> "))
You'll need a way of checking the input, so that you can exit the loop when a zero is entered and a way of storing the inputs.

What data types have you learned about?


RE: while loop - idddj - Oct-01-2022

(Oct-01-2022, 09:19 AM)rob101 Wrote: What data types have you learned about?

Indeed, my teacher has given a brief introduction of all the data types that will possibly use in python.


RE: while loop - rob101 - Oct-01-2022

(Oct-01-2022, 01:45 PM)idddj Wrote: Indeed, my teacher has given a brief introduction of all the data types that will possibly use in python.

Nice. Well, you could use one here, together with a if branch, so you should be good to go.

If you get stuck, then post your best effort and say where you're having issues.


RE: while loop - idddj - Oct-01-2022

thx! I will try it.


RE: while loop - jefsummers - Oct-03-2022

In more recent versions of Python you can also use the "walrus" operator, which allows you to combine assignment with comparison. While statements are probably one of the best examples of use. Here, would be
while (new_num := int(input("Enter value, 0 to end"))) != 0:
This puts the input inside the loop and assigns the input value to new_num. Just sum it up and print the result.