【问题标题】:How do I end my program when my while loop has met a certain condition?当我的 while 循环满足特定条件时,如何结束我的程序?
【发布时间】:2017-03-23 10:29:49
【问题描述】:

我正在学习计算机科学的入门课程,我们现在正在研究 Python。我们只需要制作一个简单的游戏来进行一些练习。我的问题是,当玩家达到 $0 时,我希望我的 while 循环结束并且程序退出。我的程序只是继续从 0 美元减去 5 美元。我需要帮助!!!

print ("Welcome to this game!")
password = input ("please put in $50 for 10 tries to play the game,"\
                      "then type ok.")
while password != ("ok"):
    password = input ("Sorry, wrong password. Please put in $50 for 10 tries to play the game,"\
                      "then type ok.")
    if password== ("ok"):
        print ("Time to play")

import random 
answer=random.randrange(50)+1

total=50

tries=1
guess=int(input("Guess the number and win $100: "))
while guess !=answer:
    print ("you loose $5")
    if guess < answer:
        print ("too low, you now have", total-5, "dollars left.")
    elif guess > answer:
        print ("too high, you now have", total-5, "dollars left.")
    guess=int(input("Guess the number and win $100: "))
    tries=tries+1
    total=total-5

print ("well done, you have won $100 in", tries,"tries") 

【问题讨论】:

  • if total == 0: break; 或更好的if total &lt;= 0: break;
  • 还有while guess !=answer and total &lt;=0:
  • 使用 break 关键字。

标签: python while-loop


【解决方案1】:

break 关键字将结束最小的封闭循环。

【讨论】:

    猜你喜欢
    • 2021-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-12
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多