2016-11-24 11 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以外の答えが得られた場合は、質問を再入力するための最良の方法をタイプしたものです。 。。私はyesまたはnoの答えのいずれかを取得しない場合は質問が繰り返されるように、そして私が見つけた解決策は、最も最適なソリューションのように見えるしていません

+1

あなたは新しいしているのでyを言うかどうかを確認します、コードのレビューが通常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

。一つの場所であなたのすべてのロジックを記述するための関数を使用しますが、そこにすることができますいいえと言っても間違った入力はありません。それが唯一の

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)")