2016-10-23 4 views
0

私はかなり新しくコーディングしており、このプロジェクトでクラスプロジェクトを割り当てられています。ゲームを作るために私は機能を記述しようとしていましたが、 def playAgain():関数は、ユーザーに再度再生したいかどうかを尋ねます。彼らは再びプレイしたいとyesまたはnoを入力した場合に応じて、それが機能start()または出口へ行くかのどちらかあればコードを入力するのに2回入力する必要があります

from sys import exit 
def playAgain(): 
print('Do you want to play again? (yes or no)') 
while True: 
    if input("> ").lower().startswith('yes')== True: 
     start() 
    elif input("> ").lower().startswith('no')== True: 
     print ('Bye for now') 
     exit(0) 
    else: 
     print ("I don't understand what you mean?") 

この関数は、ユーザーに尋ねる「すべきです」。

入力が最初に入力されたときにコード内で一見無視され、コード内で何かが起きるのを2回目に入力する必要があるという問題があります。

これは私にかなりの金額を混乱させているので、この問題を解決する方法についてのご意見をいただければ幸いです。

サイドノート - この問題はそうあなたが関数として、その後は本当にそれを書きたい場合は、これはおそらくelifまたはelse

+3

あなたは 'input'を2回呼び出すので、 –

+1

また、 'startswith'は既にブール値を返すので、' == True'の必要はありません。 –

+2

'input'を一度呼び出して結果を保存しますか? – UnholySheep

答えて

0
from sys import exit 

def playAgain(): 
    print('Do you want to play again? (yes or no)') 
    while True: 
     choice = input("> ") 
     if choice.lower().startswith('yes'): 
      start() 
     elif choice.lower().startswith('no'): 
      print ('Bye for now') 
      exit(0) 
     else: 
      print ("I don't understand what you mean?") 
+0

入力を最初に解決した問題を保存しました。ありがとう –

0

の問題である第一の意味を入力した場合に発生する表示されません。次のステップの基礎となる価値を返すべきです。 startswithは、あなたがそうちょうどynではなく、完全な言葉よりを確認することができず、何の

0

ソリューションは、入力に変数を割り当てるし、必要な回数だけ変数を比較することであることを

def playAgain(): 
    while True: 
     ans = input("Do you want to play again? (yes or no) ") 
     if ans.lower().startswith('y'): 
      return True 
     elif ans.lower().startswith('n'): 
      return False 
     else: 
      print ("I don't understand what you mean?") 

def start(): 
    print ("game restarted") 

if playAgain(): 
    start() 
else: 
    print ("Bye for now") 
    quit() 

注意。

from sys import exit 

def playAgain(): 
    print('Do you want to play again? (yes or no)') 

    while True: 
     inp = input("> ").lower() 

     if inp.startswith('y'): 
      start() 
     elif inp.startswith('n'): 
      print ('Bye for now') 
      exit(0) 
     else: 
      print ("I don't understand, what do you mean?") 
関連する問題