Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python one-line if statement calling function if true

I'm using argparse.

def help():
  parser.print_help()
  sys.exit(0)

help() if (args.lock and args.unlock)

This gives me a syntax error. What is wrong with my if statement?

like image 264
justincf Avatar asked Apr 22 '16 18:04

justincf


People also ask

Can an if statement be one line in Python?

In Python, you can have if-else statements on one line. This is handy with short if-else statements because it allows you to save lines of code while preserving code quality. But do not overuse it. Turning longer if-else statements into one-liners can make your code unreadable.

How do you call a function in an if statement in Python?

To call a function, you have to write the function name followed by parenthesis containing the parameters you want to pass to the method.

Can you call a function within an IF statement?

It depends. If words is a Set that already contains an equal object, it won't add it. Please read the doc before asking this kind of question. By the way when you call a function whether it's in a statement (if, try ...) the function is still called and the body executed so yes the obj will be addded to words.

How do you write an if statement with one line?

How to Write If Without Else in One Line? We've already seen an example above: we simply write the if statement in one line without using the ternary operator: if 42 in range(100): print("42") . Python is perfectly able to understand a simple if statement without an else branch in a single line of code.


1 Answers

You are using a conditional expression: true_result if condition else false_result. A conditional expression requires an else part, because it has to produce a value; i.e. when the condition is false, there has to be an expression to produce the result in that case.

Don't use a conditional expression when all you want is a proper if statement:

if args.lock and args.unlock: help() 
like image 85
Martijn Pieters Avatar answered Oct 02 '22 02:10

Martijn Pieters