How to loop on Python 3.4.2? [duplicate]

丶灬走出姿态 提交于 2019-12-12 06:16:58

问题


In my Python code, I have a part where I would like to repeatedly print a question if it doesn't match what I want it to.

name1 = input("A male name (protagonist): ")
    if name1.endswith (('ly', 's')):
        print("Sorry mate, this doesn't seem to be a proper noun. Try it again.")
        name1 = input("A male name (protagonist): ")

How do I make it repeatedly print out name1 if it ends with 'ly' or 's'?


回答1:


I think this is what you are after:

while True:
    name1 = input("A male name (protagonist): ")
    if name1.endswith(('ly', 's')):
        print("Sorry mate, this doesn't seem to be a proper noun. Try it again.")
        continue
    break

print("Input name is:", name1)  

This will loop over until if name1.endswith(('ly', 's')) is true.




回答2:


You can use a while loop. While loops will continuously perform something as long as it's specified condition is true.

If you don't want a name that ends with ly or s, you can make a while loop like so:

while True:
    name1 = input("A male name (protagonist): ")
    if name1.endswith ('ly', 's'):
        print("Sorry mate, this doesn't seem to be a proper noun. Try again. ")
    else:
        break # This will exit the loop, when you have a name that doesn't satisfy the condition above

I should also mention that because the if statement was satisfied, it will restart the loop. Once the name does not end with ly or s, it will move to the else block, which will come out of the loop. Note that the break is the word that forces out of the loop.



来源:https://stackoverflow.com/questions/28533622/how-to-loop-on-python-3-4-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!