【问题标题】:Python Yes/No User InputPython 是/否用户输入
【发布时间】:2016-03-15 17:31:36
【问题描述】:

我正在尝试创建一个用户输入来写入当前代码有效的文件,但我必须在它们周围写下我的答案,无论如何我可以只写是或 Y 而不必包含 ''

Join = input('Would you like to write to text file?\n')
if Join in ['yes', 'Yes']:
    for key, value in ip_attacks.iteritems(): #for key(the IPAddress) and value(the occurrence of each IPAddress) in ip_attacks 
        if value > 30: #if the value (number of occurrences) is over 30  
            myTxtFile.write('\n{}\n'.format(key)) #then we want to write the key(the IPAdress) which has been attack more than 30 times to the text file
else:
    print ("No Answer Given")

【问题讨论】:

    标签: python python-2.7 input


    【解决方案1】:

    改用raw_input

    Join = raw_input('Would you like to write to text file?\n')
    

    raw_input 以字符串形式获取输入,而input 获取准确的用户输入并将其评估为 Python。您必须输入“是”而不是“是”的原因是因为您需要将输入评估为字符串。 raw_input 表示你不需要这样做。

    Python 3.x 的注意事项

    raw_input 在 Python 3.x 中更改为 input。如果您需要input 的旧功能,请改用eval(input())

    【讨论】:

      【解决方案2】:

      不要在 Python 2.x 中使用input;使用raw_inputinput 等价于 eval(raw_input(...)),这意味着您必须键入一个字符串,该字符串构成一个有效的 Python 表达式。

      在 Python 3 中,raw_input 被重命名为 input,之前的 input 已从语言中删除。 (您很少希望将输入评估为表达式;当您这样做时,您可以自己调用eval(input(...))。)

      【讨论】:

        【解决方案3】:

        您可以将 if 语句更改为使用 lower() 或 upper() 与字符串进行比较,而不必在 'yes' 或 'y' 周围使用单引号,如下所示

        if Join.lower() == 'yes' or Join.lower() == 'y':
        

        如果使用 Python3,试试这个:

        Join = input('Would you like to write to text file?\n')
        if Join.lower() == 'yes' or Join.lower() == 'y':
            for key, value in ip_attacks.iteritems(): #for key(the IPAddress) and value(the occurrence of each IPAddress) in ip_attacks
                if value > 30: #if the value (number of occurrences) is over 30
                    myTxtFile.write('\n{}\n'.format(key)) #then we want to write the key(the IPAdress) which has been attack more than 30 times to the text file
        else:
            print ("No Answer Given")
        

        否则,如果使用 Python2,正如其他人所说,您将希望使用 raw_input() 而不仅仅是 input()

        【讨论】:

          【解决方案4】:

          请改用raw_input。见docs

          所以在你的第一行你会使用:

          Join = raw_input('Would you like to write to text file?\n')
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 2018-05-08
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2017-04-23
            • 2020-09-21
            • 2021-03-25
            相关资源
            最近更新 更多