Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do Python Inline if statements execute a function twice?

Tags:

python

When I do something like (totally random example dont read into variable names):

variable = read_file() if read_file() else "File was empty"

In this case does read_file() get excuted twice? If so is there a way to do it to only execute once but keep it within one line?

like image 251
NoviceCoding Avatar asked Jun 10 '12 08:06

NoviceCoding


People also ask

How do I run a function twice in Python?

Use the oml. index_apply function to run a Python function multiple times in Python engines spawned by the database environment. The times argument is an int that specifies the number of times to run the func function. The func argument is the function to run.

Can you use or twice in Python?

Can you use or twice in Python? Using multiple OR operator example The OR operator is used twice in the if statement to evaluate three expressions. If either of the three expressions is True, the print function inside the if statement should display the message.

How to call if function 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.


1 Answers

In that case read_file() would get executed twice. You can do this instead:

variable = read_file() or "File was empty"
like image 126
jamylak Avatar answered Oct 14 '22 02:10

jamylak