Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Understanding "while True"
#1
The following program works:

#!/usr/bin/env python3
#MovieList.py

def displayMenu():
    print("COMMAND MENU")
    print("list - List all movies")
    print("add  - Add a movie")
    print("del  - Delete a movie")
    print("exit - Exit program")

def list(movieList):
    i = 1
    for movie in movieList:
        print(str(i) + ". " + movie)
        i += 1
    print()

def add(movieList):
    movie = input("Name: ")
    movieList.append(movie)
    print(movie + " was added.\n")

def delete(movieList):
    number = int(input("Movie Number: "))
    if number < 1 or number > len(movieList):
        print("Invalid movie number.\n")
    else:
        movie = movieList.pop(number-1)#movie numbers on the console may start
        #with 1, but the indexes for the movies in the movieList start with 0.
        #Therefore, (number-1) causes the correct index of the movie that we
        #want to delete to be referenced.
        print(movie + " was deleted successfully.\n")

def main():
    movieList = ["Monty Python and the Holy Grail",
                 "Uncle Bazerko's Violent Adventure",
                 "The Expendables",
                 "Duke Nukem: Fate of Humanity"]
    displayMenu()

    while True:
        command = input("Enter command: ")
        if command.lower() == "list":
            list(movieList)
        elif command.lower() == "add":
            add(movieList)
        elif command.lower() == "del":
            delete(movieList)
        elif command.lower() == "exit":
            break
        else:
            print("Not a valid command. Please try again.\n")

    print("Bye!")

if __name__ == "__main__":
    main()
However, I don't quite understand line 41. While what is true? Is the condition simply set to false once we have officially exited the program on line 54?
Reply
#2
while True means "while bool(True) == True`, which will always be the case - it's an infinite loop.
The loop would continue on forever, if not for the break statement which exits it.
Reply
#3
In a function return can also be used to get out of the loop.
Here a refactor version,new stuff like f-string(3.6), enumerate() and following PEP-8.
Use of try:except in delete function,also with a way out(back to menu) if change of mind.
#!/usr/bin/env python3
#MovieList.py

def display_menu():
    print("\nCOMMAND MENU")
    print("list - List all movies")
    print("add  - Add a movie")
    print("del  - Delete a movie")
    print("exit - Exit program\n")

def list(movie_list):
    for index,movie in enumerate(movie_list, 1):
        print(f'{index}. {movie}')

def add(movie_list):
    movie = input("Name to add: ")
    movie_list.append(movie)
    print(f'<{movie}> was added')

def delete(movie_list):
    '''Use docstring if need to explain about this function'''
    while True:
        try:
            number = int(input("Movie number to delete,<0> to not delete: "))
            if number == 0:
                return
            movie = movie_list.pop(number-1)
            print(f'<{movie}> was deleted successfully.\n')
            return
        except(IndexError, ValueError):
            print(f'Movie number not found<{number}>,try again')

def menu():
    movie_list = [
        "Monty Python and the Holy Grail",
        "Uncle Bazerko's Violent Adventure",
        "The Expendables",
        "Duke Nukem: Fate of Humanity"
        ]
    display_menu()
    while True:
        command = input("Enter command: ")
        if command.lower() == "list":
            list(movie_list)
        elif command.lower() == "add":
            add(movie_list)
        elif command.lower() == "del":
            delete(movie_list)
        elif command.lower() == "exit":
            return 'Bye!'
        else:
            print(f"Not a valid <{command}>.Please try again.\n")

if __name__ == "__main__":
    print(menu())
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Returning True or False vs. True or None trevorkavanaugh 6 9,284 Apr-04-2019, 08:42 AM
Last Post: DeaD_EyE

Forum Jump:

User Panel Messages

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