【问题标题】:Why my function is not called in every single iteration?为什么每次迭代都没有调用我的函数?
【发布时间】: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() 只执行一次,因为它是默认参数值的一部分 - 仅在定义函数时才被评估,而不是在每次调用时。

标签: python function file


【解决方案1】:

问题是错误使用默认值。在python中,函数的默认值是在构造时评估一次,而不是每次调用函数时都调用。

def foo():
  print('yay!')

def bar(f=foo()):
  print('boo!')

bar()
bar()

将打印

yay!
boo!
boo!

因此,您的函数在每次迭代中都会被调用,只需从默认参数中提取“输入”调用,并在函数内部或调用之前显式调用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-10
    相关资源
    最近更新 更多