Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
while loop
#1
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?
Reply
#2
The input is not part of the loop, input is only taken once before the loop so n will always stay the same.
Reply
#3
May I ask how to improve it? Cry
Reply
#4
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.
Reply
#5
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?
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#6
(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.
Reply
#7
(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.
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#8
thx! I will try it.
rob101 likes this post
Reply
#9
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.
ibreeden likes this post
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020