#python #python-3.x #function
#python #python-3.x #функция
Вопрос:
У меня есть этот код, но я не знаю, как использовать «возраст» от пользователя в другой функции, есть какие-либо подсказки, что я не так?
def accounts():
yourCode = input("Please enter your user code. nIf you already have an account, type your account user code. nOtherwise, enter a new one to create an account: ")
with open("users.txt", "r") as rf:
users = rf.readlines()
for each_user in [user.split(",") for user in users]:
if each_user[0] == yourCode:
print(f"Welcome {each_user[1]}")
age = each_user[2]
xxApp()
return None
with open("users.txt", "a") as af:
name = input("Please enter your name: ")
age = input("Enter your age: ")
af.write(f"{yourCode},{name},{age}n")
print(f"Thank you {name}, your information has been added.")
xxApp()
def xxApp():
age = each_user[2]
print(age)
Ответ №1:
Передать его в качестве параметра
def accounts():
yourCode = input("Please enter your user code. nIf you already have an account, type your account user code. nOtherwise, enter a new one to create an account: ")
with open("users.txt", "r") as rf:
users = rf.readlines()
for each_user in [user.split(",") for user in users]:
if each_user[0] == yourCode:
print(f"Welcome {each_user[1]}")
xxApp(each_user)
return None
...
def xxApp(user):
age = user[2]
print(age)
Ответ №2:
Вы определяете age = each_user[2]
, но each_user
переменная доступна только в области accounts()
.
Вы можете прочитать о областях python здесь
Я бы изменил xxApp()
функцию, чтобы принимать переменную в качестве параметра, подобного этому
def xxApp(each_user):
age = each_user[2]
print(age)
затем вы вызываете xxApp()
с each_user
переданным в качестве параметра, чтобы он был доступен внутри области видимости xxApp()
, например xxApp(each_user)