简体   繁体   中英

Can not break out of Python “while True” loop

book1 = {"Name":"Biology","id":"001","Author":['Alice', 'Bob'],"Copies":5,"Owners":2}
book2 = {"Name":"Chemistry","id":"002","Author":['Alice'],"Copies":3,"Owners":1}
books = [book1,book2]

def adminMenu():
    print("Welcome Admin! What do you want to do?")
    print("1-List Books")
    print("2-Create a book")
    print("3-Clean a book")
    print("4-Search for a book")
    print("5-Change number of copies of book by id")
    print("6-Show students borrowed a book by id")
    print("7-List Users by id")
    print("8-Create User")
    print("9-Delete User")
    print("10-Exit")
    yourChoice = int(input("Your choice: "))
    if yourChoice == 2:
        while True:
            id = input("What is the id you want to give for the book?: ")
            for book in books:
                if id == book["id"]:
                   print("This id is already in use!")
                else:
                    break

Hello I'm trying to create a simple library management system using python 3.8.3. I try to code the create a book section and if the book id already exist, the program should ask for the id again but it doesn't seems to work. What's the mistake that I do here?

    while True:
        id = input("What is the id you want to give for the book?: ")
        for book in books:
            if id == book["id"]:
               print("This id is already in use!")
            else:
                break

Create a list of ids and then check if the input id exists in the list:

book1 = {"Name":"Biology","id":"001","Author":['Alice', 'Bob'],"Copies":5,"Owners":2}
book2 = {"Name":"Chemistry","id":"002","Author":['Alice'],"Copies":3,"Owners":1}
books = [book1,book2]

book_ids = []
for book in books:
        book_ids.append(book.get("id", None))    
# print(book_ids)
def adminMenu():
    print("Welcome Admin! What do you want to do?")
    print("1-List Books")
    print("2-Create a book")
    print("3-Clean a book")
    print("4-Search for a book")
    print("5-Change number of copies of book by id")
    print("6-Show students borrowed a book by id")
    print("7-List Users by id")
    print("8-Create User")
    print("9-Delete User")
    print("10-Exit")
    yourChoice = int(input("Your choice: "))
    if yourChoice == 2:
        while True:
            b_id = input("What is the id you want to give for the book?: ")
            if b_id in book_ids:
               print("This id is already in use! Please Try Again")
            else:
                # Create the book here
                print("Creating book ...")
                break

adminMenu()

OUTPUT:

Welcome Admin! What do you want to do?                                                                                                                                       
1-List Books                                                                                                                                                                 
2-Create a book                                                                                                                                                              
3-Clean a book                                                                                                                                                               
4-Search for a book                                                                                                                                                          
5-Change number of copies of book by id 
6-Show students borrowed a book by id                                                                                                                                        
7-List Users by id                                                                                                                                                           
8-Create User                                                                                                                                                                
9-Delete User                                                                                                                                                                
10-Exit                                                                                                                                                                      
Your choice: 2                                                                                                                                                               
What is the id you want to give for the book?: 001                                                                                                                           
This id is already in use! Please Try Again                                                                                                                                  
What is the id you want to give for the book?: 002
This id is already in use! Please Try Again                                                                                                                                  
What is the id you want to give for the book?: 003
Creating book ...

This is from one of my first projects:

def get_valid_answer():
    while True:
        answer = input("Type [A] or [B] to continue")
        if answer in "AB":
            return answer
        print("Invalid input, please only type [A] or [B]")

You'd have to change it a bit to work as you're trying to but shouldn't be that hard.

The main error isnʼt Python related but a common coding mistake. Try to perform the cycle in mind and check what is done if you enter 002; it will compare with "Biology", find that ids are different and break without comparing to second book ("Chemistry" with id "002")... is this what you try to reach? I doubt. As this isnʼt a place to teach basics, I stop talking here. Ask your teacher to explain.

For Python specifics, Iʼd deter from using id as variable name because it concurs with standard Python function.

You're doing a break on your else which is causing it to leave your for-loop :

while True:
    bookId = input("What is the id you want to give for the book?: ")
    for book in books:
        # Check if the id already exists, otherwise continue with checking the existing books
        if bookId == book["id"]:
            print("This id is already in use!")
            break # Break to leave the loop

PS Also used bookId instead of id as it can be confusing to just use id when your code base gets larger.

Following this logic, without using while True (Is a bad practice )

book_exists = True

while book_exists == True:
    id = input("What is the id you want to give for the book?: ")

    for book in books:

        if id == book["id"]:
            book_exists = True
            break
        else:
            book_exists = False
        print("book exists = %s" % book_exists)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM