GCN 4
GCN 4

Reputation: 33

I need assistance for my little program (python lists)

I will give you my python code (it's pretty basic and small) and if you can,tell me where i am wrong.I am noob at coding so your help will be valuable.thanks a lot and don't hate :)

lista=[]
for i in range(100):
    a=input("give me  a number")
    if a%2==0:
        a=0
    else:
        a=1
    lista=lista+a
print lista

P.S: I code with python 2 because my school books are written with that in mind.

Upvotes: 1

Views: 50

Answers (1)

abhiarora
abhiarora

Reputation: 10430

You need to use append method to add an item to the end of the list.

lista.append(a)

And you need to convert the str returned by input() to int.

The input() function reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

a = int(input("give me  a number"))

Try this:

lista=[]
for i in range(2): # Changed from 100 to 2 for my own testing
    a = int(input("Give me  a number: "))
    a = 1 if a%2 else 0
    lista.append(a)
print(lista)

Outputs:

[0,1]

EDITED:

So i cant use Lista=lista +a?I thought i could..my book says i can..thanks for your solution,it works!

You can use += operator (similar to extend()) but it requires a list operand. Not an int. So, you need to convert your int to a list. Try this:

lista += [a]

list.append(a) is faster, because it doesn't create a temporary list object. So, better to use append.

Upvotes: 2

Related Questions