Advertisement

Why does this change the list to string and this doesn't do that? Python.

Started by May 18, 2016 04:18 AM
2 comments, last by Oberon_Command 8 years, 7 months ago

stuff = []
stuffs = ["Candy", "Vegetable", "Blah"]

stuff = input("What stuff do you want")

if stuff in stuffs:
	stuff.append(stuff)

That stuff above gives me an error -


'str' object has no attribute 'append'

BUT!

This thing below doesn't give me any error!!!!


stuff = []
stuffs = ["Candy", "Vegetable", "Blah"]

item_holder = input("What stuff do you want")

if item_holder in stuffs:
	stuff.append(item_holder)

In the first case,


stuff = input("What stuff do you want")

This line converts the variable 'stuff' into a string, since the input function is returning a string. The previous 'stuff' variable is now lost.

Since, 'stuff' is a string, and a string doesn't have any function append, you get an error.

Whereas in the second case, you are never changing the type of the variable 'stuff' and the code works without any issue.

Obviously, the data and its type should remain the same since you aren't storing anything else into it.

Note that you cannot have two variables having the same type but different names. In that case, what you are doing is actually simply changing the type of the variable and losing your previous data.

Advertisement

Another question.

Look at this code below.. Question is in that comment!


if active == 1:
	print("Now for the items:")
	
	for Item in Items:
		print("\t" + Item)
		
	item_holder = input(items_prompt)
	if item_holder in Items:
		item_select.append(item_holder)
	else:
		print("This isn't an item, sorry.")
                #Even if I change active to 0, add_item = input("Would you like to add more items? If so, enter Yes.\n") still executes!
		active = 0
	add_item = input("Would you like to add more items? If so, enter Yes.\n")

You haven't told Python that it shouldn't. When your code executes the else block, it will set active to 0, but it will still be in the same block that executes if active == 1 - the condition has already been evaluated by that point in the program. Changing active to be 0 won't "rewrite history". ;)

You could either test to see if active is still 0 before you execute add_item = ..., or just put that line in the block that executes if item_holder in Items. Eg.


if item_holder in Items:
    item_select.append(item_holder)
    add_item = input("Would you like to add more items? If so, enter Yes.\n")
else
    print("This isn't an item, sorry.")

This topic is closed to new replies.

Advertisement