Python Forum
How are these while loops being used?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How are these while loops being used?
#1
Very new to programming and simply dont understand how this while loop is being used? Is the itr=itr.next the condition that needs to be maintained? I cant find any examples where there isnt a condition with the while statement.


while itr:
llstr += str(itr.data) + '-->'
itr = itr.next

class Node:
    def __init__(self, data=None, next= None):
        self.data = data
        self.next = next

class linkedlist:
    def __init__(self):
       self.head = None

    def insert_at_beginning(self, data):
         node = Node(data, self.head)
         self.head = node

    def print(self):
        if self.head is None:
            print("Linked List is empty")
            return

        itr = self.head
        llstr = ''

        while itr:
            llstr += str(itr.data) + '-->'
            itr = itr.next

        print(llstr)  
Reply
#2
When itr.next is assigned as None the while itr: will evaluate to False
Reply
#3
(Sep-06-2022, 08:26 PM)Yoriz Wrote: When itr.next is assigned as None the while itr: will evaluate to False

Thank you very much.
Reply
#4
One other point is that you are doing a very bad habit of naming functions the same as system functions. Redefining print() means you cannot use print() in the function (or else it becomes recursive). next() should also be avoided.

And, for good advice regarding style of Python programming, see PEP 8 at PEP 8
Reply


Forum Jump:

User Panel Messages

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