【问题标题】:How to get a user to input text n times and store it in a txt file如何让用户输入文本n次并将其存储在txt文件中
【发布时间】: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


【解决方案1】:

您的代码几乎没问题。

n > 0 

这不会使 n 为正数,请删除此行。 改用:

abs(n)

如果您需要反转它.. 例如。如果 n 的值为 -5,abs(n) 将使其变为 5。

当您要求用户输入文本时,您正在使用您的 n 值:

textPrint = input("Enter {}:".format(n))

这样做的结果将是您的函数总是打印“输入 5:”...改用:

textPrint = input("Enter {}/{}:".format(counter+1,n))

结果将类似于“输入 1/5:”、“输入 2/5:”、...

然后你使用:

counter = n+1

这只会使您的计数器变得大于您的 while 循环条件并在仅输入 1 行文本后过早退出您的函数。 改用:

counter += 1

希望这能让你重回正轨:-)

【讨论】:

    猜你喜欢
    • 2013-07-12
    • 1970-01-01
    • 2020-02-20
    • 1970-01-01
    • 2022-10-05
    • 2013-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多