Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

'NoneType' object has no attribute 'element'

why in the code below when printing head.element inside the while loop I dont get any error
but the same code print code outside the loop get me an error?

class node:
  def __init__(self, element):
        self.element = element
        self.next = None


head = None

node1 = node(1)
node2 = node(2)

head = node1
node1.next = node2

while head != None:
    print(head.element)
    head = head.next

print(head.element)

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

The error is raised by your last line of code:

print(head.element)

when/if the flow reaches the line above, the head variable is None, since the while loop ends only when head == None.

while head != None:
    print(head.element)
    head = head.next # The last time this will return None
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading