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)      
toti08
  • 2,448
  • 5
  • 24
  • 36
adiboi
  • 13
  • 3
  • Start with: *"if has_read __not in__ [n, y]: if has_read equals y"*… How can it be ***not*** "y" and equal "y"…? – deceze Dec 10 '18 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! – Neil Dec 10 '18 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. – toti08 Dec 10 '18 at 13:52
  • You probably want *"while not y/n: __ask user again__"*, then afterwards do your `if` outside the `while`. – deceze Dec 10 '18 at 13:52
  • initialize has_read first, and then ask for the input inside the loop. It doesn't enter the loop because has_read is (so far) always Y or N. – KuboMD Dec 10 '18 at 13:53
  • 1
    Possible duplicate of [Asking the user for input until they give a valid response](https://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – Patrick Artner Dec 10 '18 at 13:57
  • read the answers to the dupe - it show's how to ask for input until valid. – Patrick Artner Dec 10 '18 at 13:58

1 Answers1

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)