Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialRoss McPherson
774 PointsNameError: name 'search_query' is not defined
I've had a problem with the code so far, when I try doing the if search_query bit, this happens:
NameError: name 'search_query' is not defined.
The code:
#!/usr/bin/env python3
import datetime
import sys
from peewee import *
from collections import OrderedDict
db = SqliteDatabase('diary.db')
class Entry(Model):
content = TextField() #Holds whatever text we want it to hold
timestamp = DateTimeField(default=datetime.datetime.now)
class Meta:
database = db
def initalize():
db.connect()
db.create_tables([Entry], safe=True)
def menu_loop():
choice = None #Makes it a pointless variable. (giving it without a value)
while choice != 'q': #While its not equal to q
print("Enter 'q' to quit.")
for key, value in menu.items(): #KGets the key of the dict, and the value of the dict.a
print('{}) {}'.format(key, value.__doc__)) #The values are functions, reads the doc of
choice = input('Action: ').lower().strip()
if choice in menu:
menu[choice]() #We go back to menu, find the function they selected, and run it.
def add_entry():
"""Add an entry."""
print('Enter your entry. Press ctrl+d when finished.')
data = sys.stdin.read().strip()
if data:
if input('Save entry? [Y/n ').lower() != 'n':
Entry.create(content=data)
print('Saved successfuly.')
def view_entries():
"""View previous entries"""
entries = Entry.select().order_by(Entry.timestamp.desc())
if search_query:
entries = entries.where(Entry.content.contains(search_query))
for entry in entries:
timestamp = entry.timestamp.strftime('%A %B %d, %Y %I:%M%p ')
print(timestamp)
print('='*len(timestamp))
print(entry.content)
print('N) next entry')
print('q) return to main menu')
next_action = input('Action: [N/q] ').lower().strip()
if next_action == 'q':
break
def search_entries():
"""Search entries for a string."""
view_entries(input('Search query: '))
def delete_entry(entry):
"""Delete an entry."""
menu = OrderedDict([
('a', add_entry),
('v', view_entries),
])
if __name__ == '__main__':
initalize()
menu_loop()
Am I missing something?
1 Answer
Ryan S
27,276 PointsHi Ross,
I think the issue is that in your view_entries function you need to pass in a search_query argument, or at least define it somewhere in the function. Otherwise, when you get to the if statement, the variable search_query is undefined and you will get an error. In the video, they set it's default value to None.
def view_entries(search_query=None):