Home > Enterprise >  Final outputs aren't printing after inputting values
Final outputs aren't printing after inputting values

Time:08-31

I'm new to lists in python and trying to write a code where one inputs 10 numbers using a list and the following is performed:

  • Copy the number which is even to a new list named "EvenList" and output that new list.
  • Output the average of the numbers stored in the new list.

Here is my code:

List=[]
EvenList=[]
totalnum=0
count=0
for i in range(10):
    List.append(int(input("Enter a number: ")))
    
    while List[i]%2==0:
        EvenList.append(List[i])
        totalnum=totalnum List[i]
        count=count 1


print(EvenList)
average=totalnum/count
print("Average: ", average)

Whenever I run this module, after inputting my values my outputs (both the EvenList and average) aren't printed. Here's the output I get:

Example 1:

Enter a number: 1
Enter a number: 2

Example 2:

Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 1
Enter a number: 2

By further analysis, I realized whenever an even number was inputted, that's when the code gave an empty output. So I'm speculating my error lies in line 8 - 11 (there may be even more).

I so far changed my inital code: List[i]=int(input("Enter a number: ")) and EvenList[index]=(List[i]) to List.append(int(input("Enter a number: "))) and EvenList.append(List[i]) respectively - which I'm still confused as to why the intial code isn't considered to be correct since I thought they did the exact same thing [if someone could explain, it'd be very appreciated] - but that didn't fix this error.

CodePudding user response:

It's because in while loop condition, if the number is even it gets stuck in infinite loop, instead of while add if:

List=[]
EvenList=[]
totalnum=0
count=0
for i in range(10):
    List.append(int(input("Enter a number: ")))
    
    if List[i]%2==0:
        EvenList.append(List[i])
        totalnum=totalnum List[i]
        count=count 1


print(EvenList)
average=totalnum/count
print("Average: ", average)
  • Related