评估用户的输入后没有退出程序;而是循环执行此操作。例如,一个甚至不使用函数的简单示例:
phrase = "hello, world"
while input("Guess the phrase: ") != phrase:
print("Incorrect.") # Evaluate the input here
print("Correct") # If the user is successful
Run Code Online (Sandbox Code Playgroud)
输出以下内容,同时显示我的用户输入:
phrase = "hello, world"
while input("Guess the phrase: ") != phrase:
print("Incorrect.") # Evaluate the input here
print("Correct") # If the user is successful
Run Code Online (Sandbox Code Playgroud)
这显然很简单,但是逻辑听起来像您所追求的。稍微复杂一些的版本,其中包含定义的功能供您查看逻辑适合的位置,如下所示:
def game(phrase_to_guess):
return input("Guess the phrase: ") == phrase_to_guess
def main():
phrase = "hello, world"
while not game(phrase):
print("Incorrect.")
print("Correct")
main()
Run Code Online (Sandbox Code Playgroud)
输出是相同的。
甚至下面的风格也有效!!
一探究竟。
def Loop():
r = raw_input("Would you like to restart this program?")
if r == "yes" or r == "y":
Loop()
if r == "n" or r == "no":
print "Script terminating. Goodbye."
Loop()
Run Code Online (Sandbox Code Playgroud)
这是 重复执行函数(语句集)的方法。
希望你喜欢 :) :} :]
| 归档时间: |
|
| 查看次数: |
49617 次 |
| 最近记录: |