首页 > 解决方案 > 为什么这现在给了我一个 UnboundedLocalError?

问题描述

这工作正常,现在已经停止,给我一个错误,我看不出它有什么问题?

def grade(R):
    x = str(R)
    if 'Practitioner' in x:
        y = x.replace('Practitioner', ' ')
    elif 'P' in x:
        y = x.replace('P', ' ')
    elif 'p' in x:
        y = x.replace('p', ' ')
    elif 'Graduate' in x:
        y = x.replace('Graduate', ' ')
    elif 'G' in x:
        y =x.replace('G', ' ')
    elif 'g' in x:
        y = x.replace('g', ' ')

    y = int(y)
    g = inf.number_to_words(y)
    return (g)

完整脚本

import datetime
import os
from random import choice
from string import digits
import subprocess
import inflect
import pandas as pd
import reportlab
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen import canvas
# import xlrd
from reportlab.lib.units import mm

# set inflect
inf = inflect.engine()

# set fonts
folder = os.path.dirname(reportlab.__file__) + os.sep + 'fonts'
ttfFile_b = os.path.join(folder, 'VeraBd.ttf')
ttfFile_r = os.path.join(folder, 'Vera.ttf')
pdfmetrics.registerFont(TTFont("VeraBd", ttfFile_b))
pdfmetrics.registerFont(TTFont("Vera", ttfFile_r))

# Set date usage stuff

w = datetime.datetime.now()
d = datetime.date.today()
m = d.month
y = d.year + 1
p = str(w.hour) + '-' + str(w.minute) + '_' + str(w.second)
end_date = str(m) + '/' + str(y)


def grade(R):
    x = str(R)
    if 'Practitioner' in x:
        y = x.replace('Practitioner', ' ')
    elif 'P' in x:
        y = x.replace('P', ' ')
    elif 'p' in x:
        y = x.replace('p', ' ')
    elif 'Graduate' in x:
        y = x.replace('Graduate', ' ')
    elif 'G' in x:
        y =x.replace('G', ' ')
    elif 'g' in x:
        y = x.replace('g', ' ')

    y = int(y)
    g = inf.number_to_words(y)
    return (g)


def level(R):
    x = str(R)
    y = x.replace('Practitioner', ' ')
    int(y)
    g = inf.number_to_words(y)
    return (g)


# Routine to get location
def location(L):
    x = str(L)
    if 'London' in x:
        l = str("London")
    elif 'Stratford' in x:
        l = str("Stratford Upon Avon")
    elif 'Bristol' in x:
        l = str("Bristol")
    elif 'Penrith' in x:
        l = str("Penrith")
    else:
        l = str("United Kingdom")

    return (l)


# Get date
def when(D):
    dt = D.strftime('%d %B %Y')

    d = str(dt)

    return (d)


# get random diploma number
def dip():
    x = ''.join(choice(digits) for i in range(6))
    k = str(x)
    return (k)


def p_certs(df):
# set PDF file name and canvas size
#  file_location = 'C:\Users\Suely\Desktop\Ouput_PDF\'
# Set date usage stuff

    w = datetime.datetime.now()
    d = datetime.date.today()
    m = d.month
    y = d.year + 1
    p = str(w.hour) + '-' + str(w.minute) + '_' + str(w.second)
    # end_date = str(m) + '/' + str(y)

    file_name = 'CERTIFICATES_' + str(d) + '_' + str(p) + '.pdf'
    c = canvas.Canvas(file_name, pagesize=(210 * mm, 297 * mm))
        # 1mm = 0.35277777 pt


    # draw each page
    for index, row in df.iterrows():
        # D = str(row['Date'])
        # R = row['Grading Level (National Grading)']
        # L = row['Select Grading Event']
        # g = location(L)

        # A = row['Grading Committee']
        # I = row['Instructor']
        g = row['Location']
        fn = str.strip(row['First Name'])
        ln = str.strip(row['Last Name'])
        f = row['Grade']
        # r = row['Grade']
        r = grade(f)
        # d = str('11 August 2018')
        # d = when(D)
        d = str(row['Date'])
        N = fn + ' ' + ln
        # N = row['First Name'] + ' ' + row['Last Name']
        # N = row['First Name'] + row['Last Name']
        k = dip()
        #k2 = str('KMG-UK -') + str(k)
        k2 = row['Diploma Number']

        # Draw Name
        c.setFont('VeraBd', 24, leading=None)
        c.drawCentredString(297.63786, 160 * mm, str.title(N))

        # Draw Grade
        c.setFont('VeraBd', 18, leading=None)
        c.drawCentredString(110 * mm, 130 * mm, str.upper(r))

        # Draw Place
        c.setFont('VeraBd', 14, leading=None)
        # c.drawCentredString(297.63786, 261.8581643, str.title(g))
        c.drawCentredString(105 * mm, 91 * mm, str.upper(g))

        # Draw Date
        c.setFont('VeraBd', 14, leading=None)
        # c.drawCentredString(297.63786, 236.3463527, str.title(d))
        c.drawCentredString(105 * mm, 81 * mm, str(d))

        # Draw Diploma number
        c.setFont('VeraBd', 11, leading=None)
        c.drawCentredString(105 * mm, 71 * mm, str.upper(k2))
        c.showPage()

        # Draw Administration & Instructor
        # c.setFont('VeraBd', 12, leading=None)
        # c.drawCentredString(60*mm, 25*mm, str.upper(I))
        # c.setFont('VeraBd', 12, leading=None)
        # c.drawCentredString(105*mm, 25*mm, str.upper(A))

    c.save()
    subprocess.Popen([file_name], shell=True)

# set data file
data_location = '007. P1_P2 Data Sheet.csv'
file_name2 = '007. P1_P2 Data Sheet.xlsx'

# read dataframe
df = pd.read_csv(data_location, encoding='latin1', na_values=['nan'], keep_default_na=False)

# df = pd.read_excel(file_name2, 'Sheet1', index_col=None, na_values=['NA'])

p_certs(df)

错误 C:\Users\James\AppData\Local\Programs\Python\Python37\python.exe "D:/Dropbox/Dropbox/00000001 License Print/P certs/002 P1 Certificates/Certificatea.py" Traceback(最近调用最后):文件“D:/Dropbox/Dropbox/00000001 License Print/P certs/002 P1 Certificates/Certificatea.py”,第 179 行,在 p_certs(df) 文件“D:/Dropbox/Dropbox/00000001 License Print/P certs/002 P1 Certificates/Certificatea.py”,第 127 行,在 p_certs r = Grade(f) 文件“D:/Dropbox/Dropbox/00000001 License Print/P certs/002 P1 Certificates/Certificatea.py”,第 50 行,在年级 y = int(y) UnboundLocalError: 分配前引用的局部变量 'y'

进程以退出代码 1 结束

标签: python-3.x

解决方案


如果没有满足之前的and条件,则不会在语句中使用局部变量y之前对其进行初始化。y = int(y)ifelif

您可以改为在子句中分配y默认值:else

def grade(R):
    x = str(R)
    if 'Practitioner' in x:
        y = x.replace('Practitioner', ' ')
    elif 'P' in x:
        y = x.replace('P', ' ')
    elif 'p' in x:
        y = x.replace('p', ' ')
    elif 'Graduate' in x:
        y = x.replace('Graduate', ' ')
    elif 'G' in x:
        y =x.replace('G', ' ')
    elif 'g' in x:
        y = x.replace('g', ' ')
    else:
        y = '0'

    y = int(y)
    g = inf.number_to_words(y)
    return (g)

或者您可以尝试修复您的输入数据,以确保该参数R始终会导致满足ifandelif子句中的条件之一。


推荐阅读