2016-11-24 200 views
0

初學者程序員在這裏學習的過程。我只是想知道我輸入的這個簡單的代碼是否是最佳的方式。有沒有辦法縮短這個?

with open('guest_book.txt', 'a') as file_object: 
    while True: 
     name=input("What is your name?") 
     print("Welcome " + name + ", have a nice day!") 
     file_object.write(name + " has visited! \n") 
     another = input("Do you need to add another name?(Y/N)") 
     if another == "y": 
      continue 
     elif another == "n": 
      break 
     else: 
      print("That was not a proper input!") 
      while True: 
       another = input("Do you need to add another name?(Y/N)") 
       if another == "y": 
        a = "t" 
        break 
       if another == "n": 
        a = "f" 
        break 
      if a == "t": 
       continue 
      else: 
       break 

我的問題是在if語句中。當我詢問輸入內容時(「是否需要添加另一個名稱?(y/n)」),我輸入了重新提問的最佳方式,如果我得到的答案不是y或n,基本上我想。要重複的問題,如果我沒有得到任何一個是或否的回答,我找到了解決辦法似乎並不像最優化的解決方案

+1

既然你是新的,在代碼審查上http://codereview.stackexchange.com/通常做,請有此張貼。 – ishaan

+0

在「這不是正確的輸入」打印後面添加一個「繼續」。 – sal

+0

[請求用戶輸入,直到他們給出有效響應]的可能重複(http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-迴應) – tripleee

回答

2

你基本上那裏你可以簡單地說:

with open('guest_book.txt', 'a') as file_object: 
    while True: 
     name=input("What is your name?") 
     print("Welcome " + name + ", have a nice day!") 
     file_object.write(name + " has visited! \n") 
     another = input("Do you need to add another name?(Y/N)") 
     if another == "y": 
      continue 
     elif another == "n": 
      break 
     else: 
      print("That was not a proper input!") 
      continue 
0

您可以使用函數在一個地方寫你的所有邏輯。

def calculate(file_object): 
    name=raw_input("What is your name?") 
    print("Welcome " + name + ", have a nice day!") 
    file_object.write(name + " has visited! \n") 
    another = raw_input("Do you need to add another name?(Y/N)") 
    if another == "y": 
     calculate(file_object) 
    elif another == "n": 
     return 
    else: 
     print("That was not a proper input!") 
     calculate(file_object) 

if __name__=='__main__':  
    with open('guest_book.txt', 'a') as file_object: 
     calculate(file_object) 
0

你能做到這樣,但有將不會有任何無效的意見,說不。它只會檢查說y

with open('guest_book.txt', 'a') as file_object: 
    another = 'y' 
    while another.lower() == 'y': 
     name=input("What is your name?") 
     print("Welcome " + name + ", have a nice day!") 
     another = input("Do you need to add another name?(Y/N)")