如何循环Python 3.4.2?
How to loop on Python 3.4.2?
在我的 Python 代码中,如果问题与我想要的不匹配,我想重复打印一个问题。
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): ")
如果以'ly'或's'结尾,如何让它重复打印出name1?
您可以使用 while
循环。只要指定的条件为真,While 循环就会持续执行某些操作。
如果您不想要以 ly
或 s
结尾的名称,您可以像这样创建一个 while
循环:
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
我还应该提到,因为 if
语句得到满足,它会重新启动循环。一旦名称不以 ly
或 s
结尾,它将移动到 else
块,该块将跳出循环。请注意,break
是强制退出循环的词。
我想这就是你想要的:
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)
这将循环直到 if name1.endswith(('ly', 's'))
为真。
在我的 Python 代码中,如果问题与我想要的不匹配,我想重复打印一个问题。
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): ")
如果以'ly'或's'结尾,如何让它重复打印出name1?
您可以使用 while
循环。只要指定的条件为真,While 循环就会持续执行某些操作。
如果您不想要以 ly
或 s
结尾的名称,您可以像这样创建一个 while
循环:
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
我还应该提到,因为 if
语句得到满足,它会重新启动循环。一旦名称不以 ly
或 s
结尾,它将移动到 else
块,该块将跳出循环。请注意,break
是强制退出循环的词。
我想这就是你想要的:
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)
这将循环直到 if name1.endswith(('ly', 's'))
为真。