Can I call several Python functions when an if statement is true?
Question:
I am using Python 3.6.
I am trying to write some code that contains a number of if statements.
I would like to create an if statement, that when ‘true’, will call two (or more functions) but I am having trouble doing this…
For example:
if x == 1: function_1()
works as expected, but
if x == 1: function_1(), function_2()
does not work, I get an ‘object is not callable’ error for function_2.
If I try:
if x == 1: function_1()
function_2()
I get an unexpected indent error… if I try:
if x == 1: function_1()
function_2()
Pycharm tells me that the function_2() statement has no effect and only function_1() is called.
I am left scratching my head on how this can be done as its seems logical to expect that I would be able to ‘do’ more than one thing at the end of an if statement.
What can I try next?
Answers:
def function_1():
print("function 1")
def function_2():
print("function 2")
foo = True
if foo:
function_1()
function_2()
Python uses indentation level to organize blocks instead of using curly braces like C or Java.
if x == 1:
function_1()
function_2()
This will call both functions.
I am using Python 3.6.
I am trying to write some code that contains a number of if statements.
I would like to create an if statement, that when ‘true’, will call two (or more functions) but I am having trouble doing this…
For example:
if x == 1: function_1()
works as expected, but
if x == 1: function_1(), function_2()
does not work, I get an ‘object is not callable’ error for function_2.
If I try:
if x == 1: function_1()
function_2()
I get an unexpected indent error… if I try:
if x == 1: function_1()
function_2()
Pycharm tells me that the function_2() statement has no effect and only function_1() is called.
I am left scratching my head on how this can be done as its seems logical to expect that I would be able to ‘do’ more than one thing at the end of an if statement.
What can I try next?
def function_1():
print("function 1")
def function_2():
print("function 2")
foo = True
if foo:
function_1()
function_2()
Python uses indentation level to organize blocks instead of using curly braces like C or Java.
if x == 1:
function_1()
function_2()
This will call both functions.