How to use "or" in code for string values?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Maciu01

i am trying to make a text adventure game. When you’ll type certain words story will go forward , example if i type “go left” character will go left, but i also want the same thing to happen if i’ll write “move left”.

my code:

func _on_text_text_entered(new_text):
if new_text == "walk left" or "Go left":
	$Background/Player_box/Text_/test.visible = true
	$Background/Player_box/Text_/nothing_happens.visible = false
	
if new_text != "walk left" or "Go left":
	emit_signal("wrong_password")
	$Background/Player_box/Text_/nothing_happens.visible = true
	$Background/Player_box/Text_/test.visible = false
:bust_in_silhouette: Reply From: threeoh6000

After the “or”, it’s considered a new comparison so you need to put what you’re comparing against at the start of the new comparison.

In your example, you would have to do this as so:

func _on_text_text_entered(new_text):
if new_text == "walk left" or new_text == "Go left":
    $Background/Player_box/Text_/test.visible = true
    $Background/Player_box/Text_/nothing_happens.visible = false

if new_text != "walk left" or new_text != "Go left":
    emit_signal("wrong_password")
    $Background/Player_box/Text_/nothing_happens.visible = true
    $Background/Player_box/Text_/test.visible = false

You could also use else to be more efficient in your code instead of doing the inverse of the comparisons you just did:

func _on_text_text_entered(new_text):
if new_text == "walk left" or new_text == "Go left":
    $Background/Player_box/Text_/test.visible = true
    $Background/Player_box/Text_/nothing_happens.visible = false
else:
    emit_signal("wrong_password")
    $Background/Player_box/Text_/nothing_happens.visible = true
    $Background/Player_box/Text_/test.visible = false

Thanks, that worked :slight_smile:

Maciu01 | 2022-12-18 13:59

:bust_in_silhouette: Reply From: omggomb

For this use case you could also use the in operator like so:

if new_text in ["walk left", "Go left"]:
    # do the thing

This would save you some typing.