Using OR in Python for a yes/no?

后端 未结 4 1355
旧巷少年郎
旧巷少年郎 2021-01-21 23:51

I\'m wanting to have a \"y/n\" in Python, which i\'ve successfully done, but I want the user to be able to input a \"y\" or a \"Y\" and it accepts both.

Here\'s a short

相关标签:
4条回答
  • 2021-01-22 00:04

    It is or as in

    if yn == 'y' or yn == 'Y':.

    Although a better method would be

    if yn in ['y', 'Y']:

    or

    if yn.lower() == 'y':.

    0 讨论(0)
  • 2021-01-22 00:13

    You're looking for

    if yn in ("y", "Y"):
    

    Or better:

    if yn.lower() == 'y':
    
    0 讨论(0)
  • 2021-01-22 00:23
    if yn in "yY":
    

    is more succinct than

    if yn in ['y', 'Y']:
    

    or similar statements. It works because a string is a sequence in Python, just like a list or tuple.

    It would evaluate to True if the user enters literally "yY", though.

    0 讨论(0)
  • 2021-01-22 00:25

    choose:

    if yn in ["y","Y"]:
        break
    
    if yn.lower() == "y":
        break
    
    0 讨论(0)
提交回复
热议问题