HELP - Writing code returning True or False - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: Homework (https://python-forum.io/forum-9.html) +--- Thread: HELP - Writing code returning True or False (/thread-13748.html) |
HELP - Writing code returning True or False - Kokuzuma - Oct-30-2018 Hello, I am a student (of which English is not my mother tongue, then excuse the mistakes) and a beginner in learning python coding, and I'm stuck on a self-numbers exercise, where I'm asked to return, from the autonb(n) function, True or False if n is a self-number or not with n belonging to N*. So I came to this code : def autonb(n) : if n==1 : return(True) else : for k in range(1,n) : if n==(k+(sum(list(int(c) for c in str(k))))) : return(False) else : return(True)But it returns True for n=1, False for n=2 and True for everything else. I understand that the problem comes from my placements of the returns since they completely stop the function as soon as one of the two conditions with k=1 is verified but I really don't know how to place them differently. Can you guide me to the solution please ? Thank you in advance. RE: HELP - Writing code returning True or False - ichabod801 - Oct-30-2018 Think about it: you only want to return True if no number plus it's own digits equals n. So you need to check all of the numbers up to n-1 before returning True. So return True (you don't need the parentheses) should come after the loop, not inside it as you have it now.
RE: HELP - Writing code returning True or False - Kokuzuma - Nov-01-2018 Yes, I found the solution a bit before your answer. Thank you for your response. |