I am making a quote bank in Python, but my quoteBank.append(new_quote)
does not seem to be working. Here is the entire code:
import random
quoteBank = ["\"That's not a good quote\" - John, 2022", "\"This is a test quote\" - John, 2022"]
random_index = random.randint(0, len(quoteBank)-1)
add_view = input("Welcome to QuoteBank, would you like to add a quote or view a quote? add/view:\n")
if add_view == "add":
new_quote = input("Enter your quote in this format: \"Quote\" - Name, Year:\n")
quoteBank.append(new_quote)
print(new_quote " has been added to QuoteBank")
elif add_view == "view":
print(quoteBank[random_index])
else:
print('Not a valid input')
The console output says: "Test Quote has been added to QuoteBank", but it hasn't
CodePudding user response:
There is no issues with this code at all, try to run your code in debug mode with breakpoint on:
print(new_quote " has been added to QuoteBank")
you should be able to check that it adds a quote
If you ask why you don't see it on second run, it's because you are not writing it to the file but to the memory for that you should move ifs to the function and call itself to be able to check what actually is in your list.
CodePudding user response:
The problem is you have to use everything inside a while loop or run it in a
Notebook to view the changes..
And also you are just viewing a random element in the list, so better print the latest insert using, quoteBank[-1]
Here is what you could do:
import random
quoteBank = ["\"That's not a good quote\" - John, 2022", "\"This is a test quote\" - John, 2022"]
while True:
random_index = random.randint(0, len(quoteBank)-1)
add_view = input("Welcome to QuoteBank, would you like to add a quote or view a quote? add/view:\n")
if add_view == "add":
new_quote = input("Enter your quote in this format: \"Quote\" - Name, Year:\n")
quoteBank.append(new_quote)
print(new_quote " has been added to QuoteBank")
elif add_view == "view":
print(quoteBank[random_index])
else:
print('Not a valid input')
The output:
Welcome to QuoteBank, would you like to add a quote or view a quote? add/view:
add
Enter your quote in this format: "Quote" - Name, Year:
\"This is second Test quote\" - Kalyan, 2022
\"This is second Test quote\" - Kalyan, 2022 has been added to QuoteBank
Welcome to QuoteBank, would you like to add a quote or view a quote? add/view:
view
"This is a test quote" - John, 2022
Welcome to QuoteBank, would you like to add a quote or view a quote? add/view:
view
\"This is second Test quote\" - Kalyan, 2022
Welcome to QuoteBank, would you like to add a quote or view a quote? add/view:
Hope this helps.