我正在尝试在“ show():”中的“ create():”下调用“名称”,但它未定义。如何将输入保存在“ create():”中,以便可以在其他子例程中使用它(对于本例,在“ show():”中)。
谢谢
我试图在选择部分之后询问用户输入,但是并不能解决问题。我不断收到相同的错误。
import sys
class data:
name = ""
average = ""
def menu():
print("1) Data input")
print("2) Print data")
print("3) Give file name")
print("4) Save")
print("5) Read file")
print("0) Stop")
choice = int(input("Give your choice: "))
print()
return choice
def save(datalist, namea):
f = open(namea, "w")
for data in datalist:
row = str("{};{}").format(data.name, data.average)
f.write(row)
f.write("\n")
f.close()
def read(datalist, namea):
f = open(namea, "r")
for row in f:
row = row.split(";")
dataa = data()
dataa.name = str(row[0])
dataa.average = float(row[1])
datalist.append(dataa)
return datalist
def printt(datalist):
for data in datalist:
print(data.name, data.average)
def name():
namea = str(input("Give a name: "))
return namea
def inputt(datalist):
dataa = data()
dataa.name = str(input("Give a name: "))
dataa.average = float(input("Give the average (float): "))
datalist.append(dataa)
print()
return(datalist)
def main():
try:
datalist = []
while True:
choice = menu()
if (choice == 1):
datalist = inputt(datalist)
elif (choice == 2):
printt(datalist)
elif (choice == 3):
namea = name()
elif (choice == 4):
save(datalist, namea)
elif (choice == 5):
datalist = read(datalist, namea)
elif (choice == 0):
print("The program was closed {} at {}".format(datetime.datetime.now().strftime('%d.%m.%Y'), datetime.datetime.now().strftime('%H:%M:%S')))
return False
except Exception:
sys.exit(0)
main()
当我打电话给2)时,我希望它能打印在1)中输入的名称。 例如: 选择1) 1)命名:Daniel 选择2) 2)印刷品:你好,丹尼尔
答案 0 :(得分:2)
您的示波器存在问题。
name 变量仅是本地变量。 有关更多信息,请参见https://www.programiz.com/python-programming/global-local-nonlocal-variables。
一个修补程序将改为使用全局变量,或者使用AaronD。Rodriguez建议将名称作为参数传递给show-function。
def lista():
print("1) Write name.")
print("2) Print written name.")
print("0) Stop.")
choice = int(input("Give your choice: "))
return choice
def create():
global name
name = input("Give name: ")
return(name)
def show():
global name
print(name)
return
def main():
print("Choose from the following list:")
while True:
choice = lista()
if (choice == 0):
print("Thanks for using the program!")
break
elif (choice == 1):
create()
elif (choice == 2):
show()
else:
print("Input not detected.\nStopping.")
break
main()
答案 1 :(得分:1)
您将必须让show()在其中包含一个参数。例如:
def show(n):
print(n)
因此,当您调用show(n)时,它将打印您包含为n的任何内容。
因此,如果您调用show(name)。它会打印出姓名。
def show(n):
print(n)
show(name) #This would print out name.
除非返回值,否则您也不需要 return 。 Return不会使代码返回,而只会使函数返回一个值。因此,您确实需要返回list()和create(),但不需要返回show(n)。
修改 您还希望在调用create时将用户输入设置为变量。
def main():
print("Choose from the following list:")
while True:
choice = lista()
if (choice == 0):
print("Thanks for using the program!")
break
elif (choice == 1):
name = create() #Here is where you should change it
elif (choice == 2):
show(name)
else:
print("Input not detected.\nStopping.")
break