为什么现在给我一个UnboundedLocalError?

时间:2019-03-04 14:42:44

标签: python-3.x

这正在起作用,现在已经停止,并且给我一个错误,我看不出它是怎么回事?

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许可证打印/ P证书/ 002 P1证书/Certificatea.py” 追溯(最近一次通话):   文件“ D:/ Dropbox / Dropbox / 00000001许可证打印/ P certs / 002 P1证书/Certificatea.py”,行179,在     p_certs(df)   文件“ D:/ Dropbox / Dropbox / 00000001许可证打印/ P证书/ 002 P1证书/Certificatea.py”,行127,在p_certs中     r =等级(f)   文件“ D:/ Dropbox / Dropbox / 00000001许可证打印/ P证书/ 002 P1证书/Certificatea.py”,第50行,等级     y =整数(y) UnboundLocalError:分配前已引用本地变量“ y”

以退出代码1完成的过程

1 个答案:

答案 0 :(得分:0)

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

您可以在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始终会满足ifelif子句中的条件之一。