[Tutor] Odd & Even lists

Mats Wichmann mats at wichmann.us
Sat May 30 12:33:52 EDT 2020


On 5/30/20 8:06 AM, Mary Knauth via Tutor wrote:
> Hello,
> 
> I am working through a Python course, and I’m really stuck on working with lists.  The script I am working on now is:
> 
> Task:
> 
> We are passing in a list of numbers. You need to create 2 new lists in your chart, then
> 
> put all odd numbers in one list
> put all even numbers in the other list
> output the odd list first, the even list second
> Current code I am running:
> 
> 
> # Get our input from the command line
> import sys
> numbers = sys.argv[1].split(',')
> for i in range(0,len(numbers)): # 0 to the length of the list
>   numbers[i]= int(numbers[i]) # creates a list of numbers and converts numberes to an integer
> 
> # Modulo operator to decifer even numbers  
> def isEven(n) :
>   return ((n % 2) == 0) # n % 2 leaves no remainder, therefore even
> 
> for i in range(numbers)
>   if i == isEven:
>     def listEven = [i]
>   else:  
>     def listOdd = [i]
> 
> print(listOdd)
> listOdd.append(i)
> print(listEven)
> listEven.append(i)
> 
> Any advice in the right direction is appreciated, thank you!

Write tests for your function. Then develop code so that it passes the
tests.  Your isEven function is okay.

The next bit isn't.  A 'def' statement is used to write a function.
Only. You appear to be using it for assignment, which is just =.

You aren't calling your isEven function, a function call is always
designated by ().  This may be too much for you at the moment, but
functions are "first class" in Python, so you can do things with them
that you could do with other objects. The line:

if i == isEven:

tests if the value referred to by i is equal to the value referred to by
isEven, which will never be the case; isEven refers to a function object
and i refers to an integer.  You want something more like:

if isEven(i):

then think about what you want to do if that evaluates true....

You can try to talk this out in your head, it often helps. Like:

loop through a range of numbers
   if number is even, add it to the even list
   if number is odd, add it to the odd list

Does that change how you would write the code?






More information about the Tutor mailing list