0

I've written the following block of code. The code is correct syntax wise but has some logical error that I can't find. The code takes in name, author and assigns a bool value to read based on user input. The while loop section has some logical error due to which the interpreter never get to while loop and hence add_book function fails as read has no value assigned.

name = input("Title: ").lower()
author = input("Author: ").lower()
has_read = input("Mark as Read (y/n): ").lower()
while has_read not in ['n', 'y']:
    if has_read == 'y':
        read = True
    else:
        read = False
    add_book(name, author, read)      
7
  • Start with: "if has_read not in [n, y]: if has_read equals y"… How can it be not "y" and equal "y"…? Commented Dec 10, 2018 at 13:50
  • 5
    Your while loop condition makes it impossible to enter the loop. You ask the user to input a y or a n, but you can only enter the loop if they entered something other than that! Commented Dec 10, 2018 at 13:51
  • I guess you want to re-ask the user to input something if you get something other than y or n. Once you get that answer you can exit the while loop and mark your book. Commented Dec 10, 2018 at 13:52
  • You probably want "while not y/n: ask user again", then afterwards do your if outside the while. Commented Dec 10, 2018 at 13:52
  • 1
    Possible duplicate of Asking the user for input until they give a valid response Commented Dec 10, 2018 at 13:57

1 Answer 1

1

You'll probably need to re-ask the user if they don't give a valid input. Maybe something like this:

name = input("Title: ").lower()
author = input("Author: ").lower()
valid = False
while not valid:
    has_read = input("Mark as Read (y/n): ").lower()
    if had_read in ['n', 'y']:
        valid = True
        if has_read == 'y':
            read = True
        else:
            read = False
        add_book(name, author, read)   
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.