簡體   English   中英

創建 if 語句的循環

[英]Creating a loop of if statments

if explication == "y":
    print("The game is very simple, the programe generate a random number between 0 and 100 and your" +
    " objective is to guess it, if you type a number lower than the generated number i'll tell you" +
    " and the same will happen if you type a bigger number and there's a score if you guess wrong" +
    " it will decrease and when the score reach 0 you loose, that's all enjoy the game!")
if explication == "n":
    print("Great then we'll go straight to having fun!")

if explication != "n" and explication != "y":
    explication = input("please choose y or n: ")

於是我開始學習python,想做一個簡單好玩的程序,這里想問一下用戶是否需要解釋這個簡單易做的游戲,但如果他錯過點擊我也想讓他選擇另一個時間或者他只是想輸入其他東西,所以我做了第三個 if 語句,我也希望它重復,所以如果他繼續輸入除 y 和 n 以外的東西,程序將始終發送“請選擇 y 或 n”,直到他輸入y 或 n 有沒有辦法做到這一點?

explication = None

# keep asking until we get "y" or "n"
while explication not in ["y", "n"]:
    # retrieve input
    explication = input("please choose y or n: ")

    # check whether it's y or n
    if explication == "y":
        print("The game is very simple...")
    elif explication == "n":
        print("Great then we'll go straight to having fun!")
    
    # if the input is neither y nor n, the program ends up here
    # and loops again

選擇:

# keep looping unconditionally
while True:
    # retrieve input
    explication = input("please choose y or n: ")

    if explication == "y":
        # print and break
        print("The game is very simple...")
        break  # <- this gets us out of the while loop
    elif explication == "n":
        print("Great then we'll go straight to having fun!")
        break

這是編寫代碼的簡單方法

explication = None
while(explication != "n" and explication != "y"):
    explication = input("please choose y or n: ")
    if explication == "y":
        print("The game is very simple, the programe generate a random number between 0 and 100 and your" +
        " objective is to guess it, if you type a number lower than the generated number i'll tell you" +
        " and the same will happen if you type a bigger number and there's a score if you guess wrong" +
        " it will decrease and when the score reach 0 you loose, that's all enjoy the game!")
        break
    if explication == "n":
        print("Great then we'll go straight to having fun!")
        break
    
#Code to start the game after this comment

解釋

我們將 explication 設置為 None 因為必須首先初始化 explication 變量。 while 循環在輸入不是 y 或 n 時運行。 如果是 y,我們解釋游戲,然后使用 break 退出循環。 如果它是 n,我們跳過解釋並從循環中中斷。 退出循環后,您可以輸入游戲代碼!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM