0
class tree :

    def __init__(self):

        self.val=0
        self.right=None
        self.left=None

def create_tree():

    x=input()

    if x==-1:
        return None

    root=tree()
    root.val=x

    print(root)
    print(root.val)
    print(root.right)
    print(root.left)



    while(True):
        print ("reach1")
        root.left=create_tree()
        root.right=create_tree()
        print("reach2")
        break


    return root

def main():

    root=tree()
    root=create_tree()

main()

Why None is not returned when x==-1 in create_tree() ?

sample output:

2 <__main__.tree object at 0x7f58cbf11128> 2 None None reach1
-1 <__main__.tree object at 0x7f58cbf11208>
-1 None None reach1
1
  • 1
    Becasue -1 != '-1' Commented May 8, 2018 at 10:25

1 Answer 1

8

Why None is not returned when x==-1 in create_tree() ?

Because input() returns a string from stdin input. input reads a line from input, converts it to a string and returns that.

You can check this using type operator.

type_of = type(x)
>> string

The solution is to compare what you've entered with "-1"

if x == "-1":
    return None

or just use int method.

x = int(input())
if x == -1:
    return None
Sign up to request clarification or add additional context in comments.

1 Comment

@IshaanKalsi, if you find that this answers your question, I encourage you to press the green check mark.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.