Python Forum
Script get's really weird error
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Script get's really weird error
#1
Shocked 
Hello,
I am trying to write a Python script to ask the user for a recipe. The script should look up the ingredients needed for the recipe via OpenAI. Then, it should look up the live prices at Albert Heijn, at their site. However, I'm reveiving an error:
Error:
File "<stdin>", line 1 ingredient_prices = get_ingredient_prices(ingredients) IndentationError: unexpected indent >>> total_cost = sum(ingredient_prices.values()) File "<stdin>", line 1 total_cost = sum(ingredient_prices.values()) IndentationError: unexpected indent
It looks good to me tho. Here's the full code:

import requests
from bs4 import BeautifulSoup
import openai

openai.api_key = '*************'

def get_recipe(dish_name):
    prompt = f"Geef me een recept voor {dish_name} inclusief een lijst van ingrediënten."
    response = openai.Completion.create(
        engine="text-davinci-003",
        prompt=prompt,
        max_tokens=150
    )
    return response.choices[0].text.strip()

def search_ingredient_price(ingredient):
    search_url = f"https://www.ah.nl/zoeken?query={ingredient.replace(' ', '%20')}"
    response = requests.get(search_url)
    soup = BeautifulSoup(response.text, 'html.parser')
    
   
    try:
        product = soup.find('div', class_='product-card-portrait')
        if product:
            price = product.find('span', class_='price-amount').text.strip().replace(',', '.').replace('€', '')
            return float(price)
        else:
            return 0.0
    except AttributeError:
        return 0.0

def get_ingredient_prices(ingredients):
    prices = {}
    for ingredient in ingredients:
        prices[ingredient] = search_ingredient_price(ingredient)
    return prices

def main():
    dish_name = input("Voer uw gewenste gerecht in: ")
    recipe = get_recipe(dish_name)
    print("\nRecept voor", dish_name)
    print(recipe)
    

    ingredients = [line.split(' ')[-1] for line in recipe.split('\n') if line.strip()]

    ingredient_prices = get_ingredient_prices(ingredients)
    total_cost = sum(ingredient_prices.values())

    if total_cost < 17:
        print("\nDe geschatte totale kosten voor de ingrediënten zijn €", total_cost)
        for ingredient, price in ingredient_prices.items():
            print(f"{ingredient}: €{price}")
    else:
        print("\nHet totale bedrag voor de ingrediënten overschrijdt €17,-. Probeer een ander gerecht.")

if __name__ == "__main__":
    main()
Please helpppp :)
deanhystad write May-25-2024, 08:03 PM:
Please post all code, output and errors (it it's entirety) between their respective tags. Refer to BBCode help topic on how to post. Use the "Preview Post" button to make sure the code is presented as you expect before hitting the "Post Reply/Thread" button.
Reply
#2
It shows you where the error is.
Output:
IndentationError: unexpected indent
Reply
#3
Yeah, but what is the error exactly?
Reply
#4
The error message does not match your code. The line numbers disagree. How are you entering and running this code? I sometimes get an error like this using VSCode and using the run arrow. If "Run Code" is selected, VSCode runs the selected code, or the line containing the cursor. You want to use Run Program.
Reply
#5
Thanks for your respond. I currently use Python 3.11 to run the code. Should be the right program, shouldn't it?
Reply
#6
How do you run the code? Do you type it into a file and run the file form the command line? Are you using an IDE like VSCode, PyCharm, or, god forbid, IDLE? Do you try to type code in the Python interactive interpreter?
Reply
#7
I don't know what openai does, so I skipped that part.

import requests
from bs4 import BeautifulSoup

def search_ingredient_price(ingredient):
    search_url = f"https://www.ah.nl/zoeken?query={ingredient.replace(' ', '%20')}"
    response = requests.get(search_url)
    soup = BeautifulSoup(response.text, 'html.parser')     
    
    try:
        product = soup.find('div', class_='product-card-portrait')
        if product:
            price = product.find('span', class_='price-amount').text.strip().replace(',', '.').replace('€', '')
            return float(price)
        else:
            return 0.0
    except AttributeError:
        return 0.0

def get_ingredient_prices(ingredients):
    prices = {}
    for ingredient in ingredients:
        prices[ingredient] = search_ingredient_price(ingredient)
    return prices
Now try this in Idle:

ingrediënten = ['meel', 'kaas', 'tomaten']
get_ingredient_prices(ingrediënten)
No indent error:

Output:
{'meel': 0.0, 'kaas': 0.0, 'tomaten': 0.0}
Pizza voor het ontbijt!
Reply
#8
As you have >>> in error message mean that you run in interactive interpreter.
A common mistake when new to Python and use the not so good IDLE💀.
In IDLE has to do file --> new file then write or paste in code in that Window.
Then do Run --> Run module F5.

Also have to change to response = openai.chat.completions.create to use new openai API.
If i try get 429 Too Many Requests in openai as link suggest or sleep in code or need to increase your rate limits.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Weird function defaults error? wallgraffiti 5 2,374 Aug-07-2020, 05:55 PM
Last Post: deanhystad
  Weird SQLAchemy connection string error pawpaw 0 1,584 Jun-28-2020, 10:11 AM
Last Post: pawpaw
  [split] Python beginner: Weird Syntax Error mnsaathvika 1 2,223 Jul-22-2019, 06:14 AM
Last Post: buran
  Weird scoping error Stef 3 2,987 Jan-20-2019, 04:36 PM
Last Post: Stef
  Weird error in pycharm TheRedFedora 1 2,773 Mar-11-2018, 09:01 PM
Last Post: Larz60+
  weird error in random sentence generator bobger 9 5,892 Nov-29-2017, 07:34 PM
Last Post: bobger
  Error Handling is weird PythonAndArduino 1 3,085 Nov-09-2017, 05:08 AM
Last Post: Mekire
  Python beginner: Weird Syntax Error mentoly 5 10,504 Oct-13-2017, 08:06 AM
Last Post: gruntfutuk

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020