Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
while after while
#1
I am new to Python and I am trying to make a program that lets the user input positive numbers. The program should then return a list of the numbers aswell as the number of even numbers in the list. I have written this piece of code.

numbers = []   # An empty list
print('Input positive whole numbers. Stop with zero.')
x = int(input('First number: '))
n = 0
i = 0
while x > 0:
    numbers.append(x)
    x = int(input('Next: '))
print('List:', numbers)    
while i < len(numbers):
    if numbers[i]%2 == 0:
        n += 1
        i += 1
print('Number of even numbers: ', n)
But it only returns the list and not the number of even numbers. Why?
Reply
#2
The Problem is, that you are running into an endless loop.
You increment he value of i only when you are hitting an even number, but as soon as you hit an uneven number you are stuck in this loop. so, wenn the first number in the list is one, the if-condition will fail, i will not be incremented and at the next step the first number is viewed again. Your program is not printing anything because it is not finished yet and will never be :)
So to solve this just make sure you are incrementing i after the if-condition not in it. but you can also make your program a bit more compact by doing this:
numbers = []   # An empty list
print('Input positive whole numbers. Stop with zero.')
x = int(input('First number: '))
n = 0
i = 0
while x > 0:
    numbers.append(x)
    if x%2 == 0:
        n += 1
    x = int(input('Next: '))
print('List:', numbers)    
print('Number of even numbers: ', n)
Reply
#3
(Jan-28-2020, 01:29 PM)ThiefOfTime Wrote: The Problem is, that you are running into an endless loop.
You increment he value of i only when you are hitting an even number, but as soon as you hit an uneven number you are stuck in this loop. so, wenn the first number in the list is one, the if-condition will fail, i will not be incremented and at the next step the first number is viewed again. Your program is not printing anything because it is not finished yet and will never be :)
So to solve this just make sure you are incrementing i after the if-condition not in it. but you can also make your program a bit more compact by doing this:
numbers = []   # An empty list
print('Input positive whole numbers. Stop with zero.')
x = int(input('First number: '))
n = 0
i = 0
while x > 0:
    numbers.append(x)
    if x%2 == 0:
        n += 1
    x = int(input('Next: '))
print('List:', numbers)    
print('Number of even numbers: ', n)

Thank you!
Reply


Forum Jump:

User Panel Messages

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