Python Forum
HELP - Writing code returning True or False
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
HELP - Writing code returning True or False
#1
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.
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Yes, I found the solution a bit before your answer. Thank you for your response.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Can't stop if statement from executing even though False + Messy code? monkeydesu 1 986 Oct-17-2022, 05:46 AM
Last Post: deanhystad
  I need help writing this code for string properties and methods hannah71605 4 3,120 Mar-22-2021, 12:36 PM
Last Post: menator01
  Need help in Code for Writing View Functions in Flask - Python Web Framework ashishsme14 2 3,037 May-22-2020, 03:43 AM
Last Post: snippsat
  Speed of progress of writing code Johno 2 2,887 Jan-19-2018, 01:56 AM
Last Post: dwiga
  How do you create a true/false response? adamgobin 2 3,817 Jan-08-2018, 06:41 AM
Last Post: squenson
  Problem writing code with my pseudocode MattWilk97 1 2,884 Aug-29-2017, 01:54 AM
Last Post: ichabod801
  Need Help with writing this code!? r6lay 7 5,895 Feb-13-2017, 10:03 AM
Last Post: Ofnuts

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020