user10225373
user10225373

Reputation:

How to filter search criteria for Web Browsing in Python?

I wanted to make a basic search program to demonstrate to a colleague. But for some reason, I am having difficulty applying a "filter" to the search program. Right now, I am filtering out amazon and games for a pseudo work environment. When I run my code and search for amazon.com, it says "Invalid Search Criteria. Try Again." which is perfect. But on the second try, it still says "Invalid Search Criteria. Try Again." but then completes the search. Even if I am not searching amazon or games. How can I make the code react appropriately?

Example:

import webbrowser

search=input('Search: ')

while search == str('amazon') or str('games'):
  print('Invalid search criteria. Try again')

  if search != str('amazon') or str('games'):
    webbrowser.open('http://'+search)

Upvotes: 1

Views: 162

Answers (2)

MarianD
MarianD

Reputation: 14191

First, you don't need to convert string to string with expressions like str('amazon').

Second, Pythonic way for for your if statement is

if search in ('amazon', 'games'):

Third - you probably want from your program to not stop after the first correct answer, but to allow user ask other and other one - almost infinitely, until the user just press Enter (= empty string), so your program may be something as:

import webbrowser

while True:
    search=input('Search: ')
    if not search:                  # Means search is not empty
        break;                      # Jump from your infinite loop

    if search in ('amazon', 'games'):
        print('Invalid search criteria. Try again')
    else:
        webbrowser.open('http://'+search)

Upvotes: 0

Mia
Mia

Reputation: 2676

You can change your code to use simple if-else branching:

import webbrowser
while True:
    search=input('Search: ')
    if search == 'amazon' or search == 'games':
        print('Invalid search criteria. Try again')

    else:
        webbrowser.open('http://'+search)

Also it may be a good idea to change the condition to 'amazon' in search or 'games' in search to handle input better

Upvotes: 1

Related Questions