我尝试在函数中打开代码文件,但出现错误

  • 本文关键字:文件 错误 代码 函数 python
  • 更新时间 :
  • 英文 :

myfile.write ('name : '+fill_data({'name'})+'n')
TypeError: fill_data() takes 0 positional arguments but 1 was given
def safeit():
myfile = open('data_user.txt', 'w+')
myfile.write ('name : '+fill_data({'name'})+'n')
def fill_data():
name = input ('enter name : ')
print ('name : '+name)
def runprogram():
safeit()
fill_data()
quest = input ('add data ? (Y/N) : ')
if quest == 'Y':
runprogram()
else:
print('thanks to visit us')
exit()
runprogram()

由于错误指定您的fill_data函数不接受任何参数。有两种方法可以修复它:

  • returnfill_data函数中取名称变量并赋值将其转换为safeit函数内的变量

  • safeit函数内部获取用户输入

我建议你用第二个,因为fill_data函数似乎是无用的,除了接受用户输入,也可以在safeit内完成,没有任何问题:

我建议如下修复:

def safeit():
myfile = open('data_user.txt', 'w+')
name = input('enter name : ')
print ('name : '+name)
myfile.write ('name : '+ name + 'n')
def runprogram():
safeit()
quest = input ('add data ? (Y/N) : ')
if quest == 'Y':
runprogram()
else:
print('thanks to visit us')
# exit()    # you need not call this as the programme will exit on it's own 
runprogram()

否则,如果你想让事情按照你正在做的方式进行,请使用以下命令:

def safeit():
myfile = open('data_user.txt', 'w+')
myfile.write ('name : ' + fill_data() + 'n')    # remember you just need to call the function here
def fill_data():
name = input ('enter name : ')
print ('name : '+name)
return name    # return the name variable
def runprogram():
safeit()
# fill_data()  you need not call this function again as you'll be calling it within safeit()
quest = input ('add data ? (Y/N) : ')
if quest == 'Y':
runprogram()
else:
print('thanks to visit us')
# exit()    # you need not call this as the programme will exit on it's own
runprogram()

相关内容

  • 没有找到相关文章

最新更新