有人可以告诉我为什么即使定义了'lname'也会出现此错误。错误消息最后。
in k = ['Antony','Mark','Mdel']。名是“ Anthony”,名是“ Mark Mdel”。我知道姓氏,以“ Mar”开头的项目(此处为“ Mark”)开头。因此需要找到以“ Mar”开头的项目,然后提取该项目以及之后的所有项目。但是我得到了错误。
k = ['Antony', 'Mark', 'Mdel']
for word in k:
if word.startswith('Mar'):
fidx = k.index(word)
lname_i = k[fidx:]
lname = []
for nm in lname_i:
lname.append(nm)
print(lname)
fname = [x for x in k if x not in lname]
email = fname[0] + '.' + lname[0] + '@' + 'gmail.com'
fn = ' '.join(fname)
print(fn)
ln = ' '.join(lname)
print(ln)
C:\Users\Path\python.exe C:/Users/Path/Trail.py
Traceback (most recent call last):
File "C:/Users/Path/Trail.py", line 26, in <module>
fname = [x for x in k if x not in lname]
File "C:/Users/Path/Trail.py", line 26, in <listcomp>
fname = [x for x in k if x not in lname]
NameError: name 'lname' is not defined
答案 0 :(得分:0)
lname
is being defined within the if-statement. However, since 'Antony' doesn't start with 'Mar', the code within the if-statement isn't executed. Thus, lname
is not defined.