【发布时间】:2021-04-19 21:19:09
【问题描述】:
代码:
为什么函数save_path()只被调用一次?
from random import choice
from os.path import exists
from os import mkdir
number_of_chars = int(input('enter the number of letters in each file: '))
data = input('enter the sequence of letters: ')
number_of_files = int(input('enter the number of files: '))
def save_path(folder_name = input('enter name of folder in Desktop(press ENTER for saving in Desktop itself): ')):
# if the folder does not exist on the Desktop, this function creates it
tmp_path = 'C:/Users/MyComputerName/Desktop/%s' % folder_name
if not exists(tmp_path):
mkdir(tmp_path)
return tmp_path
for j in range(1, number_of_files + 1):
# each time a file is created in the given path
with open('%s/test%i.txt' % (save_path(), j), 'w') as f:
current_choice, last_choice = '', ''
for i in range(1, number_of_chars + 1):
# consecutive characters cannot be the same
while current_choice == last_choice:
current_choice = choice(data)
last_choice = current_choice
if i != number_of_chars:
f.write(current_choice + ' ')
# if this is the last character, then no need for a space character
else:
f.write(current_choice)
print('%2i done!' % j)
f.close()
输出:
输入每个文件的字母数:20
输入字母序列:gh
输入文件数:5
在桌面输入文件夹名称(按回车键保存在桌面本身):
1 完成!
2 完成!
3 完成!
4 完成!
5 完成了!
结果: screenshot
【问题讨论】:
-
每次迭代都不会调用哪个函数你也可以把代码分解成Minimal Reproducible Example吗?
-
save_path()被调用了多次。但是,文件夹名称的input()只执行一次,因为它是默认参数值的一部分 - 仅在定义函数时才被评估,而不是在每次调用时。