Natural language effects in writing Python code
One of the interesting things that I have the privilige to observe when teaching my programming class for beginner students is how they occassionally use a programming language in a similar way as you would use ordinary language. I think the example I will show is interesting because it illustrate the beginners mindset. Additionally, learning to understand this example teaches you a few things both about programming languages as well as natural language.
Or
In English, you can express your doubt about someone's name by asking the question: "is your name Christophe or Tim". We implicitly understand that or is used to separate the possible values for the name that you have in mind. Likewise, when asking the question "is your name Christophe or do I have to call you by something else", it is again implicitly understood that 'do I have to call you by something else' is not an alternative value for the name but an expression that stands by itself.
In Python, the or operator is used to combine boolean expressions. So there has to be something that evaluates to True or False on the left, and something that evaluates to True or False on the right side of the operator. However, if you stick with your experience in ordinary language, it might make sense to write something like te following:
if user_name == "Christophe" or "Tim":
Here, we are using the or-operator to separate alternative values for user_name. There is an additional challenge because this code is not technically wrong and will actually work, just not as it was intended. To understand this, let's first have a look at how you would actually specify the comparison that is needed:
if user_name == "Christophe" or user_name == "Tim":
Here there are two expresssions that will evaluate to either True or False, and the or-operator will take care of combining them. When we do not write a boolean expression but simply the value of a string, this value is technically equivalent to the boolean value of True. As a consequence, the if-statement in the first example will always evaluate to True, irrespective of the value of user_name!