【问题标题】:Python - input filters [duplicate]Python - 输入过滤器[重复]
【发布时间】:2015-05-26 23:51:54
【问题描述】:

这是my other thread on 10 Green Bottles 的后续行动。我现在想知道如何让我的输入只接受一些单词/数字。如果输入了错误的单词/数字,它会提示您再次输入。如果输入的单词匹配是一个接受的单词,它会传递并运行其余的代码。 代码:

def main():
    num1=int(input('Pick a number between 10 and 30: '))
    hue=str(input('Pick a colour; Red, Green, Blue: '))

    numbers =[ 'no', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen', 'Twenty', 'Twentyone', 'Twentytwo', 'Twentythree', 'Twentyfour', 'Twentyfive', 'Twentysix', 'Twentyseven', 'Twentyeight', 'Twentynine', 'Thirty' ]
    text_one = hue +' bottle%s\nHanging on the wall'
    text_two = "And if one " + hue + " bottle\nShould accidentally fall\nThere'll be"
    text_three =' \n'


    with open(numbers[num1] + ' ' + hue + ' Bottles.txt', 'w') as a:
        for l in range(num1, 0, -1):                                              #
            a.write(numbers[l]+ ' ')
            if l == 1:
                a.write(text_one % '' +'\n')
            else:
                a.write(text_one % 's' +'\n')

            a.write(numbers[l] + ' ')
            if l == 1:
                a.write(text_one %  '' + '\n') 
            else:
                a.write(text_one % 's' +  '\n')
            a.write(text_two + ' ')
            a.write(numbers[l-1] + ' ')
            if (l - 1) ==1 :
                a.write(text_one % ''+'\n')
            else:
                a.write(text_one % 's'+'\n')
            a.write('\n' + '\n')



if __name__ == '__main__':
    main()

【问题讨论】:

  • 不要描述其他问题,而是提供指向它的链接。您可以单击其他问题下的“共享”按钮,获取可以粘贴到此处的链接。如果没有链接,该信息只会帮助那些碰巧记住您的其他问题并知道如何找到它的人。

标签: python string input keyword


【解决方案1】:

简单while:

while True:
    try:
        msg = int(input("Enter: "))
    except ValueError:
        print("Not Valid!")
        continue
    # do some validation like if msg.endswith('hi') and stuff like that ex:

    if msg > 40 or msg < 10: # fail if greater than 40 and smaller than 10
        print("Not Valid!")
        continue
    break

【讨论】:

  • 对不起,我不确定如何将它应用到我的代码中,我可以提示一下
  • 在您收集输入并同时执行验证时使用它。否则,如果您只想获得正确的输入,这就是您所需要的。
  • 好的,这接近我想要的结果,但它只拒绝字符串,这也是我想要的,但我想要的主要是如果数字大于 10 但低于 40 它会跑。如果数字不大于 10 或大于 40,则会失败。
  • 然后添加一些逻辑语句和验证。我会进行编辑。
猜你喜欢
  • 2018-02-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-13
  • 2017-04-22
  • 2017-07-16
  • 2018-03-15
  • 1970-01-01
相关资源
最近更新 更多