Reputation: 5
Code:
why function save_path() is called only for once?
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()
Output:
enter the number of letters in each file: 20
enter the sequence of letters: gh
enter the number of files: 5
enter name of folder in Desktop(press ENTER for saving in Desktop itself):
1 done!
2 done!
3 done!
4 done!
5 done!
Result: screenshot
Upvotes: 0
Views: 85
Reputation: 66825
The problem is a wrong use of default values. In python, a default value to function is evaluated once at the construction time, not called each time you call the function.
def foo():
print('yay!')
def bar(f=foo()):
print('boo!')
bar()
bar()
will print
yay!
boo!
boo!
So your function is called in every iteration, just take "input" call out of a default argument and call it explicitely either inside your function or before calling it.
Upvotes: 1