Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
loop trouble
#1
The problem here is that after i type "quit" it still asks one last time "write something"  before it quits Think

keepgoing = True

def sub(testme):
    if len(testme) > 5:
        return 0
    else:
        return 1

def main():
    ask = input("Write something (quit ends): ")  
    vastus = sub(ask)
    if ask == "quit":
        keepgoing = False        
    elif vastus == True:
        print("Too short")    
    else:
        print(ask)
            
while keepgoing:    
    if __name__ == "__main__":
            main()
Reply
#2
Well, the keepgoing inside your function main is not the same as the one outside of it.
The former is a local, and the latter a global; they're not connected in any way, they only have the same name.

One way to fix this would be moving the loop inside the function (probably a good idea even if you don't have this problem).
Reply
#3
For me it never ends. This is because there are really two keepgoing variables. The one you define at the top of the program has module scope, it's available everywhere. The one you define in the main function has local scope: it is only available in the main function. Assigning False to it there doesn't change the keepgoing in the global scope. So you get an infinite loop.

I would put all of the keepgoing stuff into the main function, including the while loop. Then you don't have to worry about handling the scope. In a more complicated program you might fix this sort of scope issue by passing the value of keepgoing from main to the module scope.

The if __name__ == "__main__" block should not be conditional on other things. It should just be by itself.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
def sub(testme):
    if len(testme) > 5:
        return 0
    else:
        return 1

def main():
    while True:
        ask = input("Write something (quit ends): ")  
        vastus = sub(ask)
        if ask == "quit":
            break        
        elif vastus == True:
            print("Too short")    
        else:
            print(ask)
            
    
if __name__ == "__main__":
        main()
got it Tongue
Reply


Forum Jump:

User Panel Messages

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