Python Forum
Thread Rating:
  • 1 Vote(s) - 3 Average
  • 1
  • 2
  • 3
  • 4
  • 5
while loop question
#5
just to mention that using while in this case/this way is how to say ... unusual

if you have to use while loop, although not recommended
my_list = [-3, 4, 6, 7, -10, -3, 8, -4]
total = 0
j = 0
while j < len(my_list):
    if my_list[j] < 0:
        total += my_list[j]
    j += 1
print(total)
two more pythonic ways, there are also others:
my_list = [-3, 4, 6, 7, -10, -3, 8, -4]
total = 0
for number in my_list:
    if number < 0:
        total += number
print(total)
my_list = [-3, 4, 6, 7, -10, -3, 8, -4]
print(sum(number for number in my_list if number < 0))
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply


Messages In This Thread
while loop question - by Tripler - Jul-24-2018, 05:44 AM
RE: while loop question - by ichabod801 - Jul-24-2018, 05:51 AM
RE: while loop question - by ichabod801 - Jul-24-2018, 05:53 AM
RE: while loop question - by Tripler - Jul-24-2018, 06:17 AM
RE: while loop question - by buran - Jul-24-2018, 06:37 AM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Many iterations for loop question adesimone 9 1,881 Nov-12-2022, 07:08 PM
Last Post: deanhystad
  Please check whether the code about the for loop question is correct. (SyntaxError) lilliancsk01 10 2,636 Nov-08-2022, 01:25 PM
Last Post: deanhystad
  Beginner Python Question: FIzz Buzz using while loop camoyn13 2 1,848 Sep-20-2022, 09:00 AM
Last Post: deanhystad
  Repeat question (for loop) rs74 7 6,541 Jun-17-2020, 03:17 PM
Last Post: rs74
  Question about running comparisons through loop from input value Sunioj 2 2,429 Oct-15-2019, 03:15 PM
Last Post: jefsummers
  Loop question kraven 3 3,658 Sep-10-2017, 07:31 AM
Last Post: wavic
  Question about loop Pires 4 3,603 Jul-23-2017, 03:01 AM
Last Post: Pires
  Udacity while loop question liquidmetalrob 6 5,401 Jul-21-2017, 02:56 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

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