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.
An if statement is a programming conditional statement that, if proved true, performs a function or displays information.
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.
The in keyword is used to check if a value is present in a sequence (list, range, string etc.).
Python Nested if statementsWe can have a if... elif...else statement inside another if... elif...else statement. This is called nesting in computer programming.
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
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"
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With