Reputation:
I am just starting with Python and I have a short question.
import sys
# Function creates a list [1,3,5..99]
def createlist():
list = []
for i in range(1, 100, 2):
list.append(i)
return(list)
# Function asks for an odd integer between 1..100
def numberinsert():
n = int(input("Please enter an odd number between 1 and 100: "))
if n in list:
return(n)
else:
sys.exit("Number does not match requirements!")
def main():
createlist()
numberinsert()
It gives me this: TypeError: argument of type 'type' is not iterable
What am I doing wrong?
Upvotes: 4
Views: 1271
Reputation: 58
You named your list as list. List is an data type name (I mean its an keyword). list1 or another name solves that error. And I globalized your list1 variable. I am not sure that globalize part but if I was wrong please warn me. This is my first reply.
import sys
# Function creates a list [1,3,5..99]
def createlist():
global list1
list1 = []
for i in range(1, 100, 2):
list1.append(i)
return list1
# Function asks for an odd integer between 1..100
def numberinsert():
n = int(input("Please enter an odd number between 1 and 100: "))
if n in list1:
return n
else:
sys.exit("Number does not match requirements!")
def main():
createlist()
numberinsert()
main()
Upvotes: 1
Reputation: 9504
You are trying to access a local variable of function createlist
from antother function numberinsert
and it's not possible (local variables are accessible only in the scope they are defined).
I would recommend you to change your code as follows:
import sys
# Function creates a list [1,3,5..99]
def createlist():
odd_list = []
for i in range(1, 100, 2):
odd_list.append(i)
return(odd_list)
# Function asks for an odd integer between 1..100
def numberinsert():
num_list = createlist()
n = int(input("Please enter an odd number between 1 and 100: "))
if n in num_list:
return(n)
else:
sys.exit("Number does not match requirements!")
def main():
numberinsert()
As a side note, try to avoid naming your variables with names of built-in functions (like list
).
You can also write your code in a more compact way, using range(1, 100, 2)
directly in your numberinsert
function:
# Function asks for an odd integer between 1..100
def numberinsert():
n = int(input("Please enter an odd number between 1 and 100: "))
if n in range(1, 100, 2):
return(n)
else:
sys.exit("Number does not match requirements!")
def main():
numberinsert()
Upvotes: 4