Home > Software design >  Def name is not defined Python
Def name is not defined Python

Time:12-24

I am new to python and started a project on my own, long story short I am trying to program a movie selector through scraping from imdb depending on the genre, so far so good except from the second def called horror() is giving me an error saying not defined, any help would be much appreciated..:)

here's my code

import random
import secrets
import requests
from bs4 import BeautifulSoup
import numpy as np

def main():

    print("1 Horror.")
    print('2 Romance.')
    print("3 Sci-Fi.")
    print("4 Comedy.")
    print("0 Exit.")
    menu()

def menu():
    while True:
        choice = int(input("Enter your choice; "))

        if choice == 1:
                print("Horror?")
                horror()
        elif choice == 2:
                print("Romance?")
        elif choice == 3:
                print("Comedy?")
                comedy()
        elif choice == 4:
                print("Sci-Fi?")
        elif choice == 0:
                print("Goodbye!")
                break
        else:
            print("Invalid choice.")


def comedy():
    titles = []
    pages = np.arange(1, 1001, 50)
    pages
    for page in pages:
        page = requests.get(
            'https://www.imdb.com/search/title/?genres=comedy&explore=title_type,genres&pf_rd_m=A2FGELUUNOQJNL&pf_rd_p=3396781f-d87f-4fac-8694-c56ce6f490fe&pf_rd_r=WWP23JMS19Y0FJQ181DT&pf_rd_s=center-1&pf_rd_t=15051&pf_rd_i=genre&ref_=ft_gnr_pr1_i_1')
        soup = BeautifulSoup(page.text, 'html.parser')

        movie_div = soup.find_all('div', {'class': 'lister-item mode-advanced'})

        for container in movie_div:
            name = container.h3.a.text
            titles.append(name)
            ComedyMovie = (secrets.choice(titles))
        print("")
        print(ComedyMovie)
        print("")
        np.delete
        break
main()

def horror():
    titles = []
    pages = np.arange(1, 1001, 50)
    pages
    for page in pages:
        page = requests.get(
            'https://www.imdb.com/search/title?genres=horror&explore=title_type,genres&pf_rd_m=A2FGELUUNOQJNL&pf_rd_p=3396781f-d87f-4fac-8694-c56ce6f490fe&pf_rd_r=WWP23JMS19Y0FJQ181DT&pf_rd_s=center-1&pf_rd_t=15051&pf_rd_i=genre&ref_=ft_gnr_pr1_i_3')
        soup = BeautifulSoup(page.text, 'html.parser')

        movie_div = soup.find_all('div', {'class': 'lister-item mode-advanced'})

        for container in movie_div:
            # Scraping the movie's name
            name = container.h3.a.text
            titles.append(name)
            HorrorMovie = (secrets.choice(titles))
        print("")
        print(HorrorMovie)
        print("")
        np.delete
        break
main()


essentially the comedy genre works fine, horror not so fine

CodePudding user response:

So, what's happening here is, as the file gets booted up, it reads all code line by line till the first time main() method is called, and it starts executing this method immediately, suspending the further reading of the file.

In this main() method, there is another method menu() being called with an input request. Once you provide the input as horror, the system tries to run horror() method but it cannot find it as the last line read while booting up code was first main() and it cannot proceed beyond this point to buffer as its blocked by this method. In short, you cannot call the function horror() as it is technically called before it is defined.

In python, you can define a method anywhere in the file and call them in any order but you cannot call them before it is defined.

So, like @user2357112 suggested, just remove the first main() method, and this gets called at the end of the file instead, preferably with if __name__=='__main__'and everything will work as expected.

CodePudding user response:

Try using if __name__ == __main__: in your script. This allows you to call your script and execute all code within it, instead of trying to execute and run functions as module calls.

import random
import secrets
import requests
from bs4 import BeautifulSoup
import numpy as np

def main():

    print("1 Horror.")
    print('2 Romance.')
    print("3 Sci-Fi.")
    print("4 Comedy.")
    print("0 Exit.")
    menu()

def menu():
    while True:
        choice = int(input("Enter your choice; "))

        if choice == 1:
                print("Horror?")
                horror()
        elif choice == 2:
                print("Romance?")
        elif choice == 3:
                print("Comedy?")
                comedy()
        elif choice == 4:
                print("Sci-Fi?")
        elif choice == 0:
                print("Goodbye!")
                break
        else:
            print("Invalid choice.")


def comedy():
    titles = []
    pages = np.arange(1, 1001, 50)
    pages
    for page in pages:
        page = requests.get(
            'https://www.imdb.com/search/title/?genres=comedy&explore=title_type,genres&pf_rd_m=A2FGELUUNOQJNL&pf_rd_p=3396781f-d87f-4fac-8694-c56ce6f490fe&pf_rd_r=WWP23JMS19Y0FJQ181DT&pf_rd_s=center-1&pf_rd_t=15051&pf_rd_i=genre&ref_=ft_gnr_pr1_i_1')
        soup = BeautifulSoup(page.text, 'html.parser')

        movie_div = soup.find_all('div', {'class': 'lister-item mode-advanced'})

        for container in movie_div:
            name = container.h3.a.text
            titles.append(name)
            ComedyMovie = (secrets.choice(titles))
        print("")
        print(ComedyMovie)
        print("")
        np.delete
        break


def horror():
    titles = []
    pages = np.arange(1, 1001, 50)
    pages
    for page in pages:
        page = requests.get(
            'https://www.imdb.com/search/title?genres=horror&explore=title_type,genres&pf_rd_m=A2FGELUUNOQJNL&pf_rd_p=3396781f-d87f-4fac-8694-c56ce6f490fe&pf_rd_r=WWP23JMS19Y0FJQ181DT&pf_rd_s=center-1&pf_rd_t=15051&pf_rd_i=genre&ref_=ft_gnr_pr1_i_3')
        soup = BeautifulSoup(page.text, 'html.parser')

        movie_div = soup.find_all('div', {'class': 'lister-item mode-advanced'})

        for container in movie_div:
            # Scraping the movie's name
            name = container.h3.a.text
            titles.append(name)
            HorrorMovie = (secrets.choice(titles))
        print("")
        print(HorrorMovie)
        print("")
        np.delete
        break


if __name__ == "__main__":
  main()

CodePudding user response:

Try out this code

import random
import secrets
import requests
from bs4 import BeautifulSoup
import numpy as np

def horror():
    titles = []
    pages = np.arange(1, 1001, 50)
    pages
    for page in pages:
        page = requests.get(
            'https://www.imdb.com/search/title?genres=horror&explore=title_type,genres&pf_rd_m=A2FGELUUNOQJNL&pf_rd_p=3396781f-d87f-4fac-8694-c56ce6f490fe&pf_rd_r=WWP23JMS19Y0FJQ181DT&pf_rd_s=center-1&pf_rd_t=15051&pf_rd_i=genre&ref_=ft_gnr_pr1_i_3')
        soup = BeautifulSoup(page.text, 'html.parser')

        movie_div = soup.find_all('div', {'class': 'lister-item mode-advanced'})

        for container in movie_div:
            # Scraping the movie's name
            name = container.h3.a.text
            titles.append(name)
            HorrorMovie = (secrets.choice(titles))
        print(f"\n{HorrorMovie}\n")
        np.delete
        break

def comedy():
    titles = []
    pages = np.arange(1, 1001, 50)
    pages
    for page in pages:
        page = requests.get(
            'https://www.imdb.com/search/title/?genres=comedy&explore=title_type,genres&pf_rd_m=A2FGELUUNOQJNL&pf_rd_p=3396781f-d87f-4fac-8694-c56ce6f490fe&pf_rd_r=WWP23JMS19Y0FJQ181DT&pf_rd_s=center-1&pf_rd_t=15051&pf_rd_i=genre&ref_=ft_gnr_pr1_i_1')
        soup = BeautifulSoup(page.text, 'html.parser')

        movie_div = soup.find_all('div', {'class': 'lister-item mode-advanced'})

        for container in movie_div:
            name = container.h3.a.text
            titles.append(name)
            ComedyMovie = (secrets.choice(titles))
        print(f"\n{ComedyMovie}\n")
        np.delete
        break


def main():
    print("1 Horror.")
    print('2 Romance.')
    print("3 Sci-Fi.")
    print("4 Comedy.")
    print("0 Exit.")
    menu()

def menu():
    while True:
        choice = int(input("Enter your choice; "))

        if choice == 1:
                print("Horror?")
                horror()
        elif choice == 2:
                print("Romance?")
        elif choice == 3:
                print("Comedy?")
                comedy()
        elif choice == 4:
                print("Sci-Fi?")
        elif choice == 0:
                print("Goodbye!")
                break
        else:
            print("Invalid choice.")

main()
  • Related