Calling a function from another function

Hi,

I am just learning Python, so sorry for this really beginners question. That’s how we learn though, right? :slight_smile:

SCENARIO:

I am using Jupyter Notebook. I have made a Class which fetches a html page and saves it as a PDF file. This works very well. You can see the first and last part of the code here:


import requests
from bs4 import BeautifulSoup
from fpdf import FPDF, XPos, YPos


# Function to summarize text
def Getsummarizetext():
    # your code to summarize text goes here
    summarizetext()


class PDF(FPDF):
    
    def chapter_title(self, num, label):
        # Arial 12
        self.set_font('ArialUnicodeMS', '', 12)

After this, the code ends like this:

# Save HTML content to file
with open('SummarizedText.html', 'w', encoding='utf-8') as f:
    f.write(html_content)

# Create PDF object
pdf = PDF()
pdf.add_font('ArialUnicodeMS', '', 'arialuni.ttf')
pdf.set_font('ArialUnicodeMS', '', 12)

# Set document properties
title = 'Guidelines'
pdf.set_title(title)
pdf.set_author('Castor')

# Print chapter
pdf.print_chapter(1, 'Summarized Text', 'SummarizedText.html', 'document.txt')

# Save PDF file
pdf.output('SummarizedGuidelines.pdf')


I have another function which also work well called ‘summarizetext()’ This function summarizes the file called ‘document.txt’ just created in the code above.

I was expecting that when I add this line ‘summarizetext()’ (see below) to the end of the PDF code then the PDF code would just execute the summarize code that summarizes document.txt


# Print chapter
pdf.print_chapter(1, 'Summarized Text', 'SummarizedText.html', 'document.txt')

# Save PDF file
pdf.output('SummarizedGuidelines.pdf')
Getsummarizetext()

However, I get an error NameError: name ‘summarizetext’ is not defined

I rather not insert all the ‘summarizetext’ code into the PDF code, but rather call the function. The function is saved in another code file in my python directory.

What am I doing wrong?

Thanks in advance for all responses.

If the summarizetext() function is defined in another file, you need to import it. For example, if the summarizetext() function is defined in a file named otherfile.py, then you would add the following line at or near the top of the file you’ve shown.

from otherfile import summarizetext

1 Like

Note that you can’t import from jupyter notebook files. You can only import from normal python files.

1 Like