2017-12-30 39 views
0

3 개의 입력을 요구하는 간단한 프로그램을 작성 중이며 3 개의 입력이 모두 일치하면 환영 메시지가 인쇄됩니다. (이니셜 == YNH, 나이 == 42, 의사 신참 == 1/27/74).여러 if 문을 파이썬으로 인쇄 하시겠습니까?

또한 사용자 이름 (YoungNathanHeather)의 길이와 3 개의 다른 문자열 중 하나를 인쇄하는 입력 (색상)이 인쇄됩니다.

파란색, 분홍색 및 노란색을 입력 할 때 변수 (색)가 다른 경우에도 세 개의 if 문이 모두 true이고 해당 문자열이 인쇄되는 문제가 있습니다.

어쩌면 여기서 if 문을 여러 개 중첩시켜 놓은 거대한 누락 된 부분이있을 수 있습니다. 그러나 누군가 여기에 무슨 일이 일어나고 있는지 아이디어가 있습니까? 나는 "Yellow"를 입력하고 오직 하나의 문자열 프린트만을 볼 것을 기대한다.

 if color == 'blue' or 'Blue': 

이 해석이야 당신이 말하는

#checks if inputted information matches criteria. 
#if all inputted information matches variable criteria 
#(Initials == YNH, Age == 42, DOB == 1/27/74), then 
#prints a Welcome message for the user. 
if Initials == 'YNH': 
    if Age == '42': 
     if DOB == '1/27/74': 
      print('Welcome Young Nathan Heather') 
      print('Did you know that your name has ' +str((len('YoungNathanHeather'))) +' letters.') 
      #Asks for a color and prints a response based on if the color is pink, yellow, or blue 
      color = input("If you could describe your mood in a color, what would it be ?") 
      if color == 'blue' or 'Blue': 
       print('According to my research Master, Blue and Yellow together makes green. Green seems to be equal to money.') 
      elif color == 'pink' or 'Pink': 
       print('According to my research Master, Pink attracts women or makes a human into a women. Whatever comes first.') 
      elif color == 'yellow' or "Yellow": 
       print('According to my research Master, Yellow indicates a "mellow" mood. Prolong this mood if feasible.') 
      else: 
       print("My apologies Master. My research is shallow and I am not yet familiar with that mood's \"color\"") 



     else: 
      print('Sorry, Wrong Credentials Entered') 
    else: 
     print('Sorry, Wrong Credentials Entered') 

else: 
    print('Sorry, Wrong Credentials Entered') 
+1

'SIVABALANs-MBP : Desktop siva $ python test.py Young Nathan Heather에 오신 것을 환영합니다. 귀하의 이름은 18 자라고 알고 계셨습니까? 당신의 기분을 색깔로 표현할 수 있다면, 그것은 무엇입니까? yellow 색깔은 : 노란색 나의 연구 주인에 따르면, 푸른 색과 노란색은 함께 녹색을 만듭니다. 녹색은 돈과 같은 것처럼 보입니다. SIVABALANs-MBP : Desktop siva $'예상 한 결과는 무엇입니까? – Siva

답변

1

, color == 'blue'에 해당하는 경우 사실이다

 if (color == 'blue') or ('Blue'): 

, 또는 경우 'Blue'는 사실이다. 파랑은 항상 사실입니다. color 색상의 목록 내에서 존재하는지 여부를 확인합니다

 if color in [ 'blue', 'Blue']: 

: 당신이 좋아하는 일을 할 수있는 다른 색상

와 동일합니다. 하지만 'BlUe', 'bLuE'등은 어떨까요? 여기에 더 좋은 해결책이 있습니다.

 if color.lower() == "blue": 

이제는 파란색의 대문자와 일치합니다!

다음으로,이 부분을 고려 : a lot of repetition

if Initials == 'YNH': 
    if Age == '42': 
     if DOB == '1/27/74': 
      print('Welcome Young Nathan Heather') 
      ... ... ... 
     else: 
      print('Sorry, Wrong Credentials Entered') 
    else: 
     print('Sorry, Wrong Credentials Entered') 

else: 
    print('Sorry, Wrong Credentials Entered') 

뿐만 아니라 불필요한 들여 쓰기를 많이, 그것은 디버깅 코드를 읽기 힘들어합니다. 더 좋아할 이유가없는 이유는 무엇입니까?

if Initials == 'YNH' and Age == '42' and DOB == '1/27/74': 
    print('Welcome Young Nathan Heather') 
    ... ... ... 
else: 
    print('Sorry, Wrong Credentials Entered') 

이렇게하면 코드를 읽기 쉽고 쓰기도 쉬울 것입니다.

1

파이썬에서는이 작업을 수행하지 않습니다 : if color == 'blue' or 'Blue', 항상 참입니다! if color in ('blue', 'Blue') 또는 더 나은 것으로 변경해야합니다 (if color in {'blue', 'Blue'}).

왜 아무 것도 작동하지 않습니까? 이런 식으로 if를 작성할 때, 파이썬은 if color == 'blue'을 체크한다. True라면 실행한다; False이면 if 'Blue'을 검사합니다. 색상이 빨간색이라고 가정하면 기준의 첫 번째 부분이 충족되지 않으므로 파이썬은 if 'Blue'으로 이동합니다. 파이썬에 따르면, 이제는 항상 True입니다.

bool(any string except empty string)이 참이므로 bool(any number except 0*)도 마찬가지입니다. 따라서 아무 것도 부울 값이 True이므로 if color == 'blue' or 'Blue'의 if 조건은 빈 문자열이나 0 이외의 값을 입력하는 것과 관계없이 항상 만족됩니다....

if Initials == 'YNH' and Age == '42' and DOB == '1/27/74'...

* 글쎄, 0과 같은 0L, 0j, 0.0, 0.00로 그 변종을, 더 정확하게하기 :

또한, 한 줄에 if의 모든 가입하실 수 있습니다