问题
Just your personal preference, which do you prefer?
if filename in filesAndFoldersList:
while a != "TEST":
a = input("Input: ")
Or
if(filename in filesAndFoldersList):
while(a != "TEST"):
a = input("Input: ")
Either one works, so this is just personal preference I think. Second one is more similar to Java/C++. But which you do prefer and why?
回答1:
You should never use parentheses directly after the keyword of a statement, as you do in your second style. You are confusing the reader by making it look like they are functions. All you are doing is group the expression in parentheses, Python will ignore these and all you have achieved is the removal of the space after the keyword.
Neither can you use the style with all compound statements; you cannot use the style with a for
loop or a with
statement that includes the as <target>
clause.
The Python Style Guide makes no mention of the second (parenthesized) style, at all; it makes the assumption that no-one would use it.
Note that this is separate from using parentheses around long expressions, where you use (...)
around the if
condition expression if it is otherwise too long to fit on a single line. In such a situation you want to put a space between the opening (
and the if
keyword:
if (
this_is_one_thing and
that_is_another_thing or
(more_conditions and such_things)
):
do_something()
来源:https://stackoverflow.com/questions/30549554/python-coding-style-parentheses-in-ifs-loops-etc