-1

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?

halfer
  • 19,824
  • 17
  • 99
  • 186
Mark Smith
  • 757
  • 2
  • 16
  • 27

2 Answers2

2
def function_1():
    print("function 1")


def function_2():
    print("function 2")


foo = True


if foo:
    function_1()
    function_2()
rug3y
  • 104
  • 4
  • Thank you - I think I may have been a bit of a dummy with my function naming, but your post is still useful, – Mark Smith Aug 11 '17 at 21:17
  • 2
    There's almost never a good reason to test `foo is True`. Just test `foo`. – Blckknght Aug 11 '17 at 21:17
  • 1
    No worries. Indentation is important, I think it's best to keep things clear and give each function call it's own line. Reading more code written by other people will help you to internalize how to structure things. – rug3y Aug 11 '17 at 21:18
  • @Blckknght thanks for your comment, please can you elaborate on what you mean as I am a little unclear... – Mark Smith Aug 11 '17 at 21:19
  • 1
    @Blckknght you're correct, I edited my answer accordingly. – rug3y Aug 11 '17 at 21:21
  • 1
    @rug3y thanks for that - I see what Blckknght meant now! – Mark Smith Aug 11 '17 at 21:38
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.

dtauxe
  • 153
  • 11