Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use and meaning of "in" in an if statement?

Tags:

python

In an example from Zed Shaw's Learn Python the Hard Way, one of the exercises displays the following code:

next = raw_input("> ") if "0" in next or "1" in next:     how_much = int(next) 

I'm having a hard time understanding the meaning of in in this statement. I'm used to using if statements, such as in javascript, where the syntax is something like:

var = 5; if (var > 3) {     //code  to be executed } 

Is this if / in statement (in python) the same as if() in javascript?

Finding an answer to this has been tricky because the in is such a short string to narrow down an answer via search engine, and I don't know the proper name for its operation.

like image 237
Scherf Avatar asked Nov 04 '13 19:11

Scherf


People also ask

What does in if condition mean?

An if statement is a programming conditional statement that, if proved true, performs a function or displays information.

What is the IN operator in Python?

The 'in' Operator in Python The in operator works with iterable types, such as lists or strings, in Python. It is used to check if an element is found in the iterable. The in operator returns True if an element is found. It returns False if not.

What is in mean in Python?

The in keyword is used to check if a value is present in a sequence (list, range, string etc.).

Can we use in IF statement in Python?

Python Nested if statementsWe can have a if... elif...else statement inside another if... elif...else statement. This is called nesting in computer programming.


2 Answers

It depends on what next is.

If it's a string (as in your example), then in checks for substrings.

>>> "in" in "indigo" True >>> "in" in "violet" False >>> "0" in "10" True >>> "1" in "10" True 

If it's a different kind of iterable (list, tuple, set, dictionary...), then in checks for membership.

>>> "in" in ["in", "out"] True >>> "in" in ["indigo", "violet"] False 

In a dictionary, membership is seen as "being one of the keys":

>>> "in" in {"in": "out"} True >>> "in" in {"out": "in"} False 
like image 128
Tim Pietzcker Avatar answered Oct 22 '22 06:10

Tim Pietzcker


Using a in b is simply translates to b.__contains__(a), which should return if b includes a or not.

But, your example looks a little weird, it takes an input from user and assigns its integer value to how_much variable if the input contains "0" or "1".

like image 40
utdemir Avatar answered Oct 22 '22 06:10

utdemir