简体   繁体   中英

Python: Calling a function in If Statement but Not working

Im using python3, The code runs well, but when inserting a function in an if statement nothing happens unfortunately, can you help me please:

    def is_prim(n):
       if (n==1):
           return False
       elif (n==2):
           return True and print(n);
       else:
           for x in range(2,n):
               if(n % x==0):
                  return False
           return True and print(n)

   if (is_prim(11))== True):
      print("1")

The problem im having is in the last 2 code lines.

Your last return statement is not returning True, it's returning the resulting value of True and None , which is None, because the print function in Python 3 always returns None. And in that combination, of True and None , the resulting returned value is None, not True.

If you want to return True, as well as return the value of n so that it may be printed or used later by the code that calls your function, then you can make the return statement return True, n . This will return the tuple (True, n ). Note your if statement will still be False and not execute its statement given a tuple is not equal to True.

If you want to just print(n) and then still have the return statement return True, then simply call your print statement before the return statement as

print(n)
return True

You will have to modify the other return True statement as well.

And of course, given that the code calling your function already has access to the value of n, your function could simply return True or False, and leave the printing or handling of n in the code calling your function. Your function does not need to print anything. (Thanks @chepner for reminding me)

Other side note is that the conditionals in if statements do not require parentheses, like your for loop. You may want to refer to PEP 8 for proper formatting of your Python code.

The if function in the last line is making comparison of is_prim(11) which in actual sense will be True and 11. Comparing these two to a boolean 'True' will end up in a syntax error. So my advice is you do

print(n)
return True

problem fixed

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM