juan
juan

Reputation: 17

how can i get my code to work, i keep getting name not defined once i run it

T = int(input("food i have?: "))
for x in range(0, T):
     value = float(input("What is the value of item %d: "))

myAns.append(value)
myAns.sort()
print("The result is: ", myAns)

then i get the following NameError: name 'myAns' is not defined

Upvotes: 0

Views: 48

Answers (4)

Mursal Sheydayev
Mursal Sheydayev

Reputation: 31

you need to define myAns above

T = int(input("food i have?: "))
myAns = []
for x in range(0, T):
    value = float(input("What is the value of item %d: "))
    myAns.append(value)
myAns.sort()
print("The result is: ", myAns)

Upvotes: 2

Evan Wunder
Evan Wunder

Reputation: 131

I'm not sure what you're trying to do, but you need to initialize your myAns list before appending to it.

T = int(input("food i have?: "))
myAns = []
for x in range(0, T):
    value = float(input("What is the value of item %d: " % x))
    myAns.append(value)
myAns.sort()
print("The result is: ", myAns)

Live Code -> https://onlinegdb.com/SyDoV9VoU

Upvotes: 0

Marty Sullaway
Marty Sullaway

Reputation: 23

You need to append to myAns after reach loop, so it must be indented.

myAns.append(value)

It also must be defined in advance.

myAns=[]

Upvotes: 0

Red
Red

Reputation: 27577

You should add to the top:

myAns = []

or:

myAns = list()

I think your code should be:

T = int(input("food i have?: "))
myAns = []
for x in range(0, T):
    value = float(input("What is the value of item {}: ".format(x+1)))
    myAns.append(value)
myAns.sort()
print("The result is:", myAns)

Upvotes: 2

Related Questions