numbers = [1,2,3,4,5,6,7,8,9]
number = 1
Can I write the following on one line?
if number in numbers:
print number
Using the style of ruby:
puts number if numbers.include?(number)
I have tried:
print number if number in numbers
But the syntax is invalid.
The python syntax is yes_value if test else no_value
. With optional parentheses for clarity, you can say this:
print "Searching...", ("Found it" if n in numbers else "Not found")
I agree, the syntax is incredibly unintuitive. Even C conditional expressions are easier to read.
Python is Python, Ruby is Ruby. My advice is not to try writing one in the other.
Python does not have Ruby's / Perl's "postfix if", and the Pythonic way to write this is the one you've already got.
But if you really must, this will work:
if number in numbers: print number
It is against the official style guide, PEP8, though:
Compound statements (multiple statements on the same line) are generally discouraged.
Yes:
if foo == 'blah': do_blah_thing() do_one() do_two() do_three()
Rather not:
if foo == 'blah': do_blah_thing() do_one(); do_two(); do_three()
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