簡體   English   中英

Python 如何在其中添加一個循環,以便在用戶將該字段留空時不斷詢問他們的姓名。 然后一旦輸入名稱,它就會返回

[英]Python How do I add a loop to this so that it keeps asking user for their name if they leave the field blank. Then once name is entered it returns

我希望系統檢查以確保輸入了名稱。 如果是,它將返回 Hello name 我希望你喜歡這個測驗。 如果不是,它會給出一條錯誤消息,提示“此字段不能留空”。

這讓用戶輸入他們的名字

def hello():

    name=str(input("Please enter your name : "))
    
    if name == (""):
        print ("please enter your name this field cannot be blank")

    while name == (""):
        return
        name=str(input("Please enter your name : "))

    
    print("hello " + str(name))
    print ("I hope you enjoy this quiz")
    
hello() 

您在檢查名稱之前調用 return,因此 function 將在任何事情發生之前return (退出)。

代碼:

def hello():

    name = input("Please enter your name : ")
    while name == (""):
        print("please enter your name this field cannot be blank")
        name = input("Please enter your name : ")

    print("hello", name)
    print("I hope you enjoy this quiz")
   
hello()

Output:

Please enter your name : 

please enter your name this field cannot be blank
Please enter your name : 
Ryan
hello Ryan
I hope you enjoy this quiz

另請注意, input的默認類型是str ,因此您不需要強制轉換它。

暫無
暫無

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

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