Пример: я набираю положительные числа: 1, 2, 3, 4, а затем заканчиваю первую функцию, набирая -1. Список (nlist), отображаемый во второй функции, представляет собой ['1', '2', '3', '4', '']. Откуда взялся этот дополнительный пятый предмет и как мне его предотвратить?
def pos_num():
# Open num.txt and define num
num_list = open('num.txt', 'w')
num = 1
# While num is positive, ask user for input
while num >= 0:
num = int(input('Type + number to add to num_list, - number to end: '))
# If user input is positive: \
# convert to str, add to list, convert to int to continue loop
if num >= 0:
num = str(num)
num_list.write(num + '\n')
num = int(num)
# If user input is negative: \
# close num.txt and inform user
else:
num_list.close()
print('List has been written to num.txt')
# Call program 1
pos_num()
# Program 2: Number File Reader
def nfread():
# Ask user for filename to open
filename = input('Filename: ')
infile = open(filename, 'r')
# Create empty list
nlist = []
# Read first line, strip '\n', append to nlist, begin line count
line = infile.readline()
line = line.rstrip('\n')
nlist.append(line)
count = 1
# While line is not empty: \
# read line, strip '\n', append line to nlist, add 1 to count
while line != '':
line = infile.readline()
line = line.rstrip('\n')
nlist.append(line)
count += 1
print(line, count)
# Close num.txt
infile.close()
# Return nlist
return nlist