TF KALIBER
TF KALIBER

Reputation: 31

python: Input() inside of a for loop error

for i in range(5):
    mylist[i]=int(input("Input an integer: "))

Do I really still have to define mylist before the for loop before I can actually use it? At the first loop it works fine but at the second loop it will show a NameError do I have to use a different inut method or what?

NameError: name 'mylist' is not defined

Upvotes: 3

Views: 152

Answers (5)

Yeshwin Verma
Yeshwin Verma

Reputation: 454

yes you are needed to define the list before the loop and also define the contents too, because it will throw a error Note: here i used 0 you can also use keyword None

myList = [0, 0, 0, 0, 0]
for i in range(5):
    myList[i] = int(input("Enter a int: "))

or you could also use function append using this you don't have to define what does myList contains-

myList = []
for i in range(5):
    myList.append(int(input("Enter a int: ")))

Upvotes: 0

n0nvme
n0nvme

Reputation: 1399

You need to define mylist before you assign values to it.

mylist = [1, 2, 3, 4, 5]
for i in range(5):
    mylist[i]=int(input("Input an integer: "))

Or if you want to fill the empty list use append() list function

mylist = []
for i in range(5):
    mylist.append(input("Input an integer: "))

Upvotes: 0

TimTam
TimTam

Reputation: 63

Yes, you need to define what "mylist" is before you assign values to it.

mylist = []
for i in range(5):
    mylist.append(int(input("Input an integer: ")))

Upvotes: 2

Teejay Bruno
Teejay Bruno

Reputation: 2159

you could just use list comprehension

mylist = [int(input("Input an integer: ")) for _ in range(5)]

Upvotes: 0

rahoo
rahoo

Reputation: 110

Yes, you have to define the list before like this

mylist=[]
for i in range(5):
    mylist[i]=int(input("Input an integer: "))

Upvotes: 0

Related Questions