【发布时间】:2017-08-23 19:29:09
【问题描述】:
我正在编写应该获取用户信息并将其存储在文本文件中的代码。我想知道如何让用户输入信息 n 次,这样如果我在他们输入 5 后询问“输入 5:”,下一个提示应该是“输入 4:”,依此类推,直到他们退出 while循环。
这个函数将一个正整数 n 作为参数,并创建一个名为 nLinesOfText.txt 的文件,其中包含通过键盘输入获得的 n 行文本。该函数应提示用户输入文本 n 次,并将该信息写入文件。
def userInput(n):
fileName = "nLinesOfText.txt"
outputFile = open(fileName, "w")
counter = 0
# make n positive
n>0
# use a while loop for when counter is less than n
while (counter<n):
# ask user to print n
textPrint = input("Enter {}:".format(n))
#convert the text to a string and write it the output File
outputFile.write(str(textPrint) + "\n")
# exit out of the loop when counter is equal to n
counter = n+1
# close the file
outputFile.close()
【问题讨论】:
-
问题是什么?您这里有一些代码由于语法错误而实际上无法工作,但如果您修复它们,它看起来会很接近。
标签: python python-3.x while-loop user-input prompt