[Python] I am a student making a news project app using python

Discussão em 'Python' iniciado por Stack, Junho 3, 2025.

  1. Stack

    Stack Membro Participativo

    it is a really simple project but it is throwing an error. it has no gui and is only for a learning experience


    import requests
    import pyttsx3
    import time

    API_KEY = "ed13978dcbd44393abe5b31e8be20fef"
    engine = pyttsx3.init()

    # Default speaker mode
    read_mode_switch = False

    # Speaker functions
    def speaker(text):
    if read_mode_switch:
    engine.say(text)
    engine.runAndWait()
    print(text)

    def speaker2(text):
    if read_mode_switch:
    engine.say(text)
    engine.runAndWait()
    return input(text + ": ").lower()

    # Speaker mode selection
    while True:
    read_mode = speaker2("Would you like to keep speaker mode enabled? (yes/no)")
    if read_mode.startswith("y"):
    read_mode_switch = True
    break
    elif read_mode.startswith("n"):
    break
    else:
    print("Invalid input. Try again.")

    speaker("Welcome!")

    # Country and category data
    country_codes = {
    "us": "United States",
    "in": "India",
    "gb": "United Kingdom",
    "ca": "Canada",
    "au": "Australia"
    }

    news_categories = {
    1: "business",
    2: "entertainment",
    3: "general",
    4: "health",
    5: "science",
    6: "sports",
    7: "technology"
    }

    # Country selection
    def Country_picking():
    while True:
    speaker("Available Countries:")
    for i, key in enumerate(country_codes, start=1):
    speaker(f"{i} - {key.upper()} - {country_codes[key]}")
    country_input = speaker2("Enter country code or serial number")
    try:
    index = int(country_input) - 1
    country_keys = list(country_codes.keys())
    return country_keys[index]
    except:
    if country_input in country_codes:
    return country_input
    speaker("Invalid input. Try again.")

    # Category selection
    def Category_selection():
    while True:
    speaker("Available Categories:")
    for key, value in news_categories.items():
    speaker(f"{key} - {value}")
    category_input = speaker2("Enter category name or number")
    if category_input.isdigit():
    num = int(category_input)
    if num in news_categories:
    return news_categories[num]
    elif category_input in news_categories.values():
    return category_input
    speaker("Invalid input. Try again.")

    # Fetch news
    def fetch_news(country, category):
    url = 'https://newsapi.org/v2/top-headlines'
    params = {
    "country": country,
    "category": category,
    "apiKey": API_KEY
    }
    try:
    speaker("Request is being sent...")
    response = requests.get(url, params=params)
    except Exception as e:
    speaker(f"Network error: {e}")
    return []

    speaker(f"Response Status: {response.status_code}")

    if response.status_code == 200:
    return response.json().get("articles", [])
    else:
    speaker("Failed to fetch news. Check your API key or internet connection.")
    return []

    # Show articles
    def show_articles(articles, start=0, count=5):
    if not articles:
    speaker("No news found.")
    return

    for i, article in enumerate(articles[start:start+count], start=1):
    title = article.get("title", "No title")
    description = article.get("description", "No description")
    url = article.get("url", "No URL")
    author = article.get("author", "Unknown author")

    speaker(f"{i}. {title}")
    speaker(description)
    print("->", url)
    print("Author:", author)
    time.sleep(2)

    if read_mode_switch:
    engine.say(f"Written by {author}")
    engine.runAndWait()

    # Main loop
    country = Country_picking()
    category = Category_selection()
    articles = fetch_news(country, category)
    show_articles(articles, 0, 5)

    while True:
    more = speaker2("Do you want more articles? (yes/no)")
    if more.startswith("n"):
    speaker("Thank you for reading with us!")
    break

    if speaker2("Do you want to change country? (yes/no)").startswith("y"):
    country = Country_picking()

    if speaker2("Do you want to change category? (yes/no)").startswith("y"):
    category = Category_selection()

    articles = fetch_news(country, category)

    if not articles:
    speaker("No news found for the selected country and category.")
    continue

    try:
    number_of_articles = int(input("Enter number of more articles you would like: "))
    if number_of_articles <= 0:
    raise ValueError("Must be more than 0")
    show_articles(articles, 5, number_of_articles)
    except ValueError:
    speaker("Please enter a valid positive number.")


    Please help fix the code I have tried chatgpt it is just optimising it and still gettng same error Name error:"response" not found despite me using the proper syntax I have request library installed

    Continue reading...

Compartilhe esta Página