我过去几天一直在研究这段代码。我遇到两件事情有困难(如果我没有正确地将字符串从字符串转换为整数,则可能为3件):
1)总结数组中的数字总和。总计显示以此格式输入的最后一个数字([9],9)。
2)从readData模块中,显示最初输入的数字。它返回项目数,即5
示例输出
请输入1到10:1之间的数字
请输入1到10:3之间的数字
请输入1到10:5之间的数字
请输入1到10:7之间的数字
请输入1到10:9之间的数字
您输入的总数是:([9],9)
数据已写入文件。
您输入的数字是: 5
已从文件中读取数据。 ITEMS = 5
def main():
#assign variable to call a function
numArray = inputNumbers()
#assign variable to call a function and
#pass the argument 'numArray'
total = addNums(numArray)
#display the total amount of the numbers in array combined
print('The total of the numbers in the list is', total)
#call function to write data to a file passing argument numArray
writeArray(numArray)
#call function to read data from a file
readArray()
def inputNumbers():
#set empty array to append items to later
numArray = []
#set up try and except to ensure user puts in a number
#and that the number is between 1 and 10
try:
#set up a for loop for the user to be able to enter up to 5 items
for count in range(1, ITEMS + 1):
print(count,')Please enter a number between 1 and 10: ', sep= '', end='')
numbers = int(input())
#set up while loop so that the user is able to reenter a number if they
#enter a number outside of 1-10
while numbers < 1 or numbers > 10:
print('An error occurred. Please make sure you enter' \
'only a number.')
print()
print(count,')Please enter a number between 1 and 10: ', sep= '', end='')
#convert numbers to an integer
numbers = int(input())
#use append method to add the numbers entered to empty array
numArray.append(numbers)
#return numArray back to the main function
return numArray
#declare except method in the event user enters anything that is not a numer
except:
print('An error occurred. Please ensure that you are entering the information properly.')
#call function to get the total sum of the numbers in the array
def addNums(numArray):
total = 0
#calculate the total sum of the numbers
for i in numArray:
total += i
#return total back to the main function
return total
#declare function to write the data from the array to a file
def writeArray(numArray):
#open the file
num_file = open('Exam2.dat','w')
#declare for loop to convert all the integers back to a string
for index in numArray:
num_file.write(str(index) + '\n')
#close the file
num_file.close()
print('The data has been written to the file.')
def readArray():
#open read file
num_file = open('Exam2.dat','r')
numbers = num_file.readline()
numbers = numbers.rstrip('\n')
#create a while loop to execute as long as the index is 1 less than the max amount of items
#and also will stop the program from continually running once it hits EOF
while numbers != ' ' :
#display the numbers that were originally entered
print('Here are the numbers that you entered:', numbers)
#read each line of the file and strip the separate line after
numbers = num_file.readline()
numbers = numbers.rstrip('\n')
#close file
infile.close()