2016-11-24 1 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

새로운 것 때문에 y 말을 확인합니다, 코드에 대한 검토는 일반적으로 http://codereview.stackexchange.com/에서 수행되고, 거기에이 게시하시기 바랍니다. – ishaan

+0

'That is not input' 인쇄 직후에 "continue"를 추가하십시오. – 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

당신은 이런 식으로 할 수 있지만,이 no라고 말하는 것에 대한 잘못된 입력이되지는 않습니다. 그것은 단지

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)") 
관련 문제