名称'usr_name'未定义

时间:2018-05-31 09:08:19

标签: python python-3.x

在我的while循环中,我想添加我将从usr_name定义的所有用户名。

#!/bin/usr/python3 
import os, sys
import math

try:
    project_file = open('work_good.txt', 'w+')
    text = project_file.read()

except FileNotFoundError:
    text = ('File not found')
    print (text)
    project_file.close()


def Zone():
    #Introduction to the database
    print ('WELCOME TO THE DATABASE', file=project_file)
    print (23*'=', file=project_file)

def Username():
    #Ask for users username
    usr_name = input ('What do you want your current username to be?: ').strip().capitalize()
    print ('Your username is: {}'.format(usr_name), file=project_file)

while True:
    my_list = []
    if usr_name in my_list:
        my_list.append(usr_name)



Zone()
Username()

错误说:

  

Traceback(最近一次调用最后一次):文件“project_work.py”,第27行,   在       如果my_list中有usr_name:NameError:未定义名称'usr_name'

我尝试在列表中添加字符串,但失败了。 我试图更改变量名称(usr_name),但它不起作用。

我想要它做的是将任何用户名添加到列表中,但我不能。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

usr_nameUsername()函数的范围内定义。

因此,除了您尝试使用它之外,它不可用。您需要从usr_name返回Username()

#!/bin/usr/python3 
import os, sys
import math


def Zone():
    #Introduction to the database
    print ('WELCOME TO THE DATABASE', file=project_file)
    print (23*'=', file=project_file)


def Username():
    #Ask for users username
    usr_name = input ('What do you want your current username to be?: ').strip().capitalize()
    print ('Your username is: {}'.format(usr_name), file=project_file)
    return usr_name  # <---- return


try:
    project_file = open('work_good.txt', 'w+')
    text = project_file.read() 
except FileNotFoundError:
    text = ('File not found')
    print (text)
    project_file.close()

Zone()   
while True:
    my_list = []
    usr_name = Username()  # <---- get usr_name from function
    if usr_name in my_list:
        my_list.append(usr_name)