【Python】name ‘table’ is not defined エラー対処方法

Python-name ‘table’ is not defined-アイキャッチ Python

Pythonのコーディング中に発生した「name ‘table’ is not defined」のエラー対処の方法をご紹介します。

name ‘table’ is not defined エラー発生内容

以下の22行目でエラーが発生しました。

22行目のコード → [table=table(data,colWidths=30*mm,rowHeights=30*mm)]


from reportlab.pdfgen import canvas
from reportlab.lib.units import mm
from reportlab.lib.pagesizes import A4
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.cidfonts import UnicodeCIDFont
from reportlab.platypus import Table,TableStyle
from reportlab.lib import colors

pdf_canvas = canvas.Canvas('テスト.pdf')
pdf_canvas.setTitle('Document title')
width,height = A4
pdf_canvas.setPageSize((width,height))

#フォント指定
pdfmetrics.registerFont(UnicodeCIDFont('HeiseiKakuGo-W5'))
font_size = 10

data = [
    ['テスト1','テスト2','テスト3'],
]

table=table(data,colWidths=30*mm,rowHeights=30*mm)

 

エラー発生時のコマンドプロンプト

エラーとして表示されている英語の意味を調べてみました。

「table」を定義してないらしいです。
・[is not defined] → 定義されていない


 
 

エラー解決方法

以下コーディングに修正したところ、解決できました。
22行目を修正して、その他のコードは変更していません。


from reportlab.pdfgen import canvas
from reportlab.lib.units import mm
from reportlab.lib.pagesizes import A4
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.cidfonts import UnicodeCIDFont
from reportlab.platypus import Table,TableStyle
from reportlab.lib import colors

pdf_canvas = canvas.Canvas('テスト.pdf')
pdf_canvas.setTitle('Document title')
width,height = A4
pdf_canvas.setPageSize((width,height))

#フォント指定
pdfmetrics.registerFont(UnicodeCIDFont('HeiseiKakuGo-W5'))
font_size = 10

data = [
    ['テスト1','テスト2','テスト3'],
]

table=Table(data,colWidths=30*mm,rowHeights=30*mm)

 

T 」を入力するべきところに、
t 」を入力していたため発生していたエラーでした。

↓修正したのは赤文字のみです。

× → table=table(data,colWidths=30*mm,rowHeights=30*mm)
○ → table=Table(data,colWidths=30*mm,rowHeights=30*mm)
 
この記事がお役に立ちますと幸いです。
 

【Python】よくあるエラーの原因と対処方法まとめ:38選
...

 

「Python 1年生 体験してわかる!会話でまなべる!」

初めての方でも安心して取り組めるように丁寧に解説
簡単なサンプルを作りながら、対話形式でプログラミングまで紹介
人工知能の導入としてもオススメの1冊です!