如何让用户输入文本n次并将其存储在txt文件中

时间:2017-03-30 03:54:48

标签: python python-3.x while-loop user-input prompt

我正在编写应该获取用户信息并将其存储在文本文件中的代码。我想知道如何让用户输入信息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()

1 个答案:

答案 0 :(得分:0)

您的代码几乎没问题。

Option Explicit

'moves selected page to left
Private Sub CommandButton1_Click()

    Dim pag As MSForms.Page
    Dim lngPageCount As Long

    ' get reference to page
    Set pag = Me.MultiPage1.SelectedItem
    ' get number of pages in multipage
    lngPageCount = Me.MultiPage1.Pages.Count
    ' check if trying to go left beyond first page and put to end
    ' otherwise decrement pages position in multipage
    If pag.Index = 0 Then
        pag.Index = lngPageCount - 1
    Else
        pag.Index = pag.Index - 1
    End If

    ' update caption
    Me.Label1.Caption = pag.Name & " is at index " & pag.Index

End Sub

'moves selected page to right
Private Sub CommandButton2_Click()

    Dim pag As MSForms.Page
    Dim lngPageCount As Long

    ' get reference to page
    Set pag = Me.MultiPage1.SelectedItem
    ' get number of pages in multipage
    lngPageCount = Me.MultiPage1.Pages.Count
    ' check if trying to go right beyond number of pages and put to start
    ' otherwise increment pages position in multipage
    If pag.Index = lngPageCount - 1 Then
        pag.Index = 0
    Else
        pag.Index = pag.Index + 1
    End If

    ' update caption
    Me.Label1.Caption = pag.Name & " is at index " & pag.Index

End Sub

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

n > 0 

如果你需要反转它..前。如果n的值为-5,则abs(n)将使其为5。

当您要求用户输入文字时,您使用的是n值:

abs(n)

这样做的结果是你的功能总是打印“输入5:”...改为使用:

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

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

然后你使用:

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

这只会使你的计数器变得比你的while循环条件更大,并在输入一行文本后提前退出你的函数。 改为使用:

counter = n+1

希望这会让你回到正轨: - )