Help with beginner code

Hello , I am new to Godot, I am learning from a book called Learning GDscript. I have this code extends Node2D

func _ready() :
	var inventory = ["Boots", "Banana" , "Bandages"]
	for item in inventory.size() :
		if item == "Banana":
			continue 
	print(item)

it is supposed to print Boots and Bandages but I get error invalid operands “int” and “string” for “==” operator. Any help would be appreciate it.

for item in inventory.size() has the same effect as for item in range(inventory.size()) (docs) and gives you every integer leading up to inventory.size(), starting at zero (for example every integer from 0 to 5 if the inventory size is 6). What you want to do here is get every item in the inventory, which you can do with for item in inventory
(@Mahan explained all this in much detail)

1 Like

Hi, this is why:

Fix code blocks

You should put print() inside for loop, so do this first:

func _ready(): # space between ) and : removed, doesn't matter but this have cleaner syntax, you can use "func _ready() -> void:" instead
	var inventory = ["Boots", "Banana" , "Bandages"]
	for item in inventory.size(): # there is another removed space, doesn't matter too
		if item == "Banana":
			continue 
		print(item)

for … in loops

for loops can use in two ways in this case:

Using index

when you use for item in inventory.size(), inventory.size() will return an integer (3 here) so for loop will run code block for each value between 0 and 3 (Note this in mind: 0 to 3 means 0, 1, and 2), so will execute block with item = 0, item = 1 and item = 2 one by one.

Note: you can use range() function to have more control on this, to see how press F1 in editor and search for range

In this case, you can use item as index and do this:

func _ready():
	var inventory = ["Boots", "Banana" , "Bandages"]
	for item in inventory.size():
		if inventory[item] == "Banana":
			continue 
		print(inventory[item])

Using array

Also, you can use array in for loops, and then it will set its items one by one in loop. In this case, you can use for item in inventory and then for loop will run loop block with item = "Boots", item = "Banana" and item = "Bandages", then everything will be ok:

func _ready():
	var inventory = ["Boots", "Banana" , "Bandages"]
	for item in inventory:
		if item == "Banana":
			continue 
		print(item)
2 Likes

In your code, item is an integer counting from 0 to 3. You’re trying to compare that integer to the "Banana" string.

Change your for loop to:

for item in inventory:

Thank you