Python 如何让用户输入n次文本并将其存储在txt文件中
我编写的代码应该是获取用户信息并将其存储在文本文件中。我想知道如何让用户输入n次信息,这样,如果我在用户输入5后询问“enter5:”,下一个提示应该是“enter4:”,依此类推,直到他们退出while循环 此函数将取一个正整数n作为参数,并创建一个名为nLinesOfText.txt的文件,其中包含通过键盘输入获得的n行文本。该函数应提示用户输入文本n次,并将该信息写入文件Python 如何让用户输入n次文本并将其存储在txt文件中,python,python-3.x,while-loop,user-input,prompt,Python,Python 3.x,While Loop,User Input,Prompt,我编写的代码应该是获取用户信息并将其存储在文本文件中。我想知道如何让用户输入n次信息,这样,如果我在用户输入5后询问“enter5:”,下一个提示应该是“enter4:”,依此类推,直到他们退出while循环 此函数将取一个正整数n作为参数,并创建一个名为nLinesOfText.txt的文件,其中包含通过键盘输入获得的n行文本。该函数应提示用户输入文本n次,并将该信息写入文件 def userInput(n): fileName = "nLinesOfText.txt" out
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()
def userInput(n):
fileName=“nLinesOfText.txt”
outputFile=打开(文件名为“w”)
计数器=0
#使n为正
n> 0
#当计数器小于n时,使用while循环
而(counter您的代码几乎正常
n > 0
这不会使n为正,请拆下此线。
改用:
abs(n)
counter += 1
如果你需要将其反转,例如,如果n的值为-5,则abs(n)将使其为5
当您要求用户输入文本时,您使用的是n值:
textPrint = input("Enter {}:".format(n))
这样做的结果是,您的函数将始终打印“Enter 5:”…请改用:
textPrint = input("Enter {}/{}:".format(counter+1,n))
结果将类似于“输入1/5:”、“输入2/5:”、
然后使用:
counter = n+1
这只会使计数器大于while循环条件,并在只输入一行文本后过早退出函数。
改用:
abs(n)
counter += 1
希望这能让你回到正轨:-)问题是什么?这里有一些代码由于语法错误而无法实际工作,但如果您修复了这些代码,它看起来就很接近了。