r/learnpython • • Jul 26 '14

Function/if statement won't work the way I want it to.

I have a problem with a function/ if statement where I take the raw input and if it contains the word 'flee' it goes back to another function. If it contains 'head' or 'eat' it sets a variable to show your death message. If the input contains 'flee' head' or 'eat' it should restart the function. The problem is that if I type something that isn't one of the three words it acts as if the input is 'head' or 'eat' and runs that elif statement. The problem seems to happen when i added the or 'eat' part to that statement. please help. The lesson I'm doing is from learn python the hard way ex35

def cthulu_room():
	print """Here you see the great evil Cthulu.
 He, it, whatever stares at you and you go insane.
 Do you flee for your life or eat your head?"""
	
	choice = raw_input('> ')
	
	if "flee" in choice:
		start()
	elif "head" or 'eat' in choice:
		dead("Well that was tasty!")
	else:
		cthulu_room()
3 Upvotes

17 comments sorted by

2

u/OseOseOse import antigravity Jul 26 '14

Anyways, /u/hakril has the simple correction for your code OP.

But what if you had not two words to check, but lots of them? You wouldn't want to write

if ("a" in choice) or ("b" in choice) or ("c" in choice) or ("d" in choice) or ("e" in choice)

and so on "forever".

Instead you could list the words, then loop through the list and check each word

words = ["a", "b", "c", "d", "e"]
for word in words:
    if word in choice:
        dead("Well that was tasty!")
        break

And since what you have there is a for loop that you want to stop when you get a true value, you can use the any() function which is shorthand for just that.

if any((word in choice) for word in ["a", "b", "c", "d", "e"]):
    dead("Well that was tasty!")

2

u/[deleted] Jul 27 '14

I tried to do that earlier but wasn't successful because lists sort of confuse me. Thanks for really breaking it down and explaining it.

3

u/stubborn_d0nkey and some 3 Jul 27 '14 edited Jul 27 '14

Just to note that if the expected behavior is to, for example, not accept 'fleet' as 'flee' then this won't work (ie. if choice contains 'fleet' it will find 'flee' in there with your code).

If that is so then you can split the text:
choice = choice.split()
though then 'flee.' wont be recognized as 'flee' (if that is necessary).

One more bonus thing, if you are going to split it then why not use sets?

choice_set = set(choice.split())
words = {"a", "b", "c", "d", "e"}
if choice_set.intersection(words):
    dead("Well that was tasty!")

choice_set.intersection(words) will return a set containing the elements present in both choice_st and words. If they don't share any then it will return an empty set that evaluates to false.

edit:

sets:
https://docs.python.org/2/library/stdtypes.html#set-types-set-frozenset

4

u/hakril Jul 26 '14

I guess that what you want is:

"head" in choice or 'eat' in choice

Because with your condition the first test is if "head" and "head" is a non-empty string so it's always true and the second one 'eat' in choice is not even tested.

2

u/OseOseOse import antigravity Jul 26 '14

The term for this behavior is "short-circuit evaluation" by the way, and also happens with "and"-ed expressions (evaluation stops if a false is found).

https://en.wikipedia.org/wiki/Short-circuit_evaluation

http://cis.poly.edu/cs1114/pyLecturettes/short-circuit-eval.html

1

u/autowikibot Jul 26 '14

Short-circuit evaluation:


Short-circuit evaluation, minimal evaluation, or _McCarthy, the usual Boolean operators are short-circuit. In others ([Java](https://en.wikipedia.org/wiki/Java(programming_language)), Ada, both short-circuit and standard Boolean operators are available. For some Boolean operations, like XOR, it is not possible to short-circuit, because both operands are always required to determine the result.


Interesting: Lazy ^evaluation | Test and ^Test-and-set | Program ^optimization | ^Evaluation

Parent commenter can toggle ^NSFW or ^delete. Will also delete on comment score of -1 or less. | FAQs | ^Mods | Magic ^Words

1

u/ingolemo Jul 27 '14

While short-circuit evaluation is happening here, it isn't the cause of the problem. Short-circuit evaluation simply means that when we know what one side of an and or or expression is we don't necessarily have to bother with the other side. This is a nice optimisation but it doesn't really change side-effect-less computations like this one.

The problem is actually due to a linguistic phenomenon called Right node raising. In a phrase like 'head' or 'eat' in choice the in choice part is intended to apply to both the left and right sides of the or (i.e. to both 'head' and 'eat'). As people who speak English, we can understand such a phrase because we are very smart and we're able to use context to understand what is meant. But right node raising breaks a whole bunch of assumptions about the way we think syntax is supposed to work. To a computer, right node raising looks like it should make a phrase ambiguous and we don't really understand how to resolve that ambiguity. So, to make things easier, we don't allow it in our programming languages.

1

u/autowikibot Jul 27 '14

Right node raising:


In linguistics, the term right node raising (RNR) denotes a sharing mechanism that sees the material to the immediate right of parallel structures being in some sense "shared" by those parallel structures, e.g. [Sam likes] but [Fred dislikes] the debates. The parallel structures of RNR are typically the conjuncts of a coordinate structure, although the phenomenon is not limited to coordination. Postal assumed that the parallel structures are complete clauses below the surface. The shared constituent was then raised rightward out of each conjunct of the coordinate structure and attached as a single constituent to the structure above the level of the conjuncts, hence "right node raising" was occurring in a literal sense. While the term right node raising survives, the actual analysis that Postal proposed is not (or no longer) widely accepted. RNR occurs in many languages, including English and related languages.


Interesting: Constituent ^(linguistics) | Coordination ^(linguistics) | Lymphatic ^system | Confederate States of ^America

Parent commenter can toggle ^NSFW or ^delete. Will also delete on comment score of -1 or less. | FAQs | ^Mods | Magic ^Words

-2

u/5n1p Jul 26 '14

change that line to:

elif "head" in choice or 'eat' in choice:

or to

elif ("head" or 'eat') in choice:

the way you typed it is wrong and that is all.

1

u/[deleted] Jul 26 '14

Thanks, I'm just getting started and don't pick up on things like this.

2

u/OseOseOse import antigravity Jul 26 '14

Huh. Today I learned something new. I did not believe that should work, but I tested and what do you know:

l = ["a", "b"]

print "a" in l                      # True
print "b" in l                      # True
print "c" in l                      # False

print ("a" or "b") in l             # True
print ("a" and "b") in l            # True

print ("a" or "b" or "c") in l      # True
print ("a" and "b" and "c") in l    # False

2

u/[deleted] Jul 26 '14
>>> l = ["a", "b"]
>>> ("a" and "b" and "c") in l
False
>>> ("a" and "c" and "b") in l
True
>>> ("a" or "b" or "c") in l
True
>>> ("c" or "b" or "a") in l
False

1

u/OseOseOse import antigravity Jul 26 '14

Okay that's really weird. Looks like it just checks the first item in the parenthesis then returns the result?

3

u/hakril Jul 26 '14

not exactly, this is a 'or' / 'and' tricks:

the expression a or b or c returns the first item evaluated as True or the last one

the expression a and b and c returns the first item evaluated as False or the last one

>>> [] or {} or 2 or []
2
>>> [] or {}
{}
>>> 1 and 2 and [] and  4
[]
>>> 3 and 2 and 1
1

1

u/OseOseOse import antigravity Jul 26 '14

Oh. That's almost the behavior I was expecting when I made that first test, except I believed that an expression like ("a" or "b") would return as True, not "a". So I believed the test should not work unless the boolean True was in the list.

1

u/5n1p Jul 26 '14 edited Jul 26 '14

lol :(

>>> l = ["a", "b"]
>>> ("a" and "b") in l
True
>>> ("a" and "c") in l
False
>>> ("a" and "c" and "b") in l
True
>>> ("a" and "c" and "b" and "d") in l
False
>>> ("a" and "c" and "b" and "d" and "e") in l
False
>>> ("a" and "c" and "b" and "d" and "e" and "a") in l
True

It seems it's the last one. Was quick with example from topic and ... I don't even know why I tried it and it worked, but it's not correct. Like always assumption is mother of all ...

1

u/hakril Jul 26 '14 edited Jul 26 '14

it doesn't work: here is a counter-example:

>>> ('a' or 'b') in "bcd"
False
# Compiled as
>>> x = 'a' or 'b'  # so x = 'a'
>>> x in 'bcd'
False