Problem
You have several problems here:
- You never define
size
in the head of the while
loop.
- You're using the
range
builtin class as an integer value which doesn't make sense.
- You never use
alist
in your function.
- You don't need a
for
loop in your while
because you are not trying to find the amount of even numbers for each number between 1
to element
, your trying to find all the even numbers in alist
(presumably).
Here is what the above fixes would look like:
def count_evens_while(alist):
evenIntegers = 0
size = 0
while size < len(alist):
if alist[size] % 2 == 0:
evenIntegers = evenIntegers + 1
size = size + 1
print(evenIntegers)
In the first part of the while
loop:
size < len(alist)
We are telling Python to comparse the value of size
to the length of alist
each time we loop. We then incrmenet size
by one each time in the loop:
size = size + 1
This basically means that each iteration of the loop, the value of size
will correspond to an index of alist
. The loop will stop when size
reaches the last index of alist
. Here's a visual example to help explain. Assume alist
is [1, 2, 3]
and size
initially equals 0
:
First iteration
alist = [1, 2, 3]
^
|
+--- size = 0
Second iteration
alist = [1, 2, 3]
^
|
+--- size = 1
Third (and last) iteration
alist = [1, 2, 3]
^
|
+--- size = 2
The next important part:
alist[size] % 2 == 0
Means we are indexing the list alist
. When you index a list, you use an integer to get a value from the position that the integer corresponds to. In this case, alist[size]
means that we are getting the value of the integer at position of the value of size
. The last part:
% 2 == 0
Means that we are testing if the integer at position size
in alist
is even. If it is, we increment the count of even numbers, if not we do nothing.
Improvements
There are some improvements you can make to your current solution
- Use a
for
loop instead of a while
loop. It would be the more natural solution here.
- You don't need to do
evenIntegers = evenIntegers + 1
. You an use the increment operator, +=
, instead.
Here are the improvements from above applied to your code:
def count_evens_while(alist):
evenIntegers = 0
for element in alist:
if element % 2 == 0:
evenIntegers += 1
print(evenIntegers)
However, this can be improved more! You don't need a for
loop. You can use a generator comprehension combined with the sum()
builtin function to count all of the elements in alist
that are even:
def count_evens_while(alist):
return sum(1 for el in alist if el % 2)
Stylistic improvements
The last thing I would critique on your code would be to use better variable names. Use names that accurately describe what the variable represents.For example, the variable myList
would be better renamed to user_input_numbers
.