[英]Restarting my program based on user input on Python?
我是編程新手,老兄。 我希望我的程序根據用戶輸入重新啟動到頂部。 如果用戶輸入2個名稱,它將繼續進行。 如果他們輸入1個名稱或兩個以上的名稱,則應重新啟動程序,但我不確定如何執行此操作。
def main():
print("Hello, please type a name.")
first_name, last_name = str(input("")).split()
while input != first_name + last_name:
print("Please enter your first name and last name.")
main()
您應該使用while循環並在分配前檢查拆分的長度:
def main():
while True:
inp = input("Please enter your first name and last name.")
spl = inp.split()
if len(spl) == 2: # if len is 2, we have two names
first_name, last_name = spl
return first_name, last_name # return or break and then do whatever with the first and last name
好吧,您的程序從一開始就不起作用,因此,為了簡單地解析名字和姓氏,我建議:
f, l = [str(x) for x in raw_input("enter first and last name: ").split()]
如果您在沒有良好的'ol ctrl + c的情況下運行循環,那么while循環將破壞您的生命。 因此,我建議:
def main():
print “type your first & last name”
try:
f, l = [str(x) for x in raw_input("enter first and last name: ").split()]
if f and l:
return f + ‘ ‘+ l
except:
main()
例外:main()將在出現錯誤時為您重新運行該程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.