2017-02-03 9 views
3

私はPythonの初心者です。ユーザーが無効な入力を行うまで関数を呼び出す方法が不思議でした。ここ はコードのサンプルです:無効な入力まで関数を呼び出す方法は?

start = input("For sum of squares, type 'squares'. For sum of cubes, type 'cubes'. " 
       "\nIf you would like to raise a number to something other than 'squares' or 'cubes', type 'power'. " 
       "\nIf you would like to exit, type 'exit':") 

def main_function(start): 
    while start.lower() != "exit": 
     if start.lower() in "squares": 
      initial = input("What is the initial constant for the sum of the squares: ") 
      terms = input("Number of terms: ") 

     if start.lower() in "cubes": 
      initial = input("What is the initial constant for the the sum of the cubes: ") 
      terms = input("Number of terms: ") 



      if start.lower() in "power": 
       initial = input("What is the initial constant for the the sum: ") 
       terms = input("Number of terms: ") 

     else: 
      print("Program halted normally.") 
      quit() 

main_function(start) 

私はそれが何を取得しようとしています何を求めるプロンプトは表示ユーザーが適切な入力を入力した場合「開始」し、それが再び機能を介して実行するために取得することです。私は 'else'ステートメントの上と下の関数内に 'start'を入れようとしましたが、新しい入力を受け付けません。

+0

ループインループを使用するとユーザーの入力に最も適しています – dawg

+0

whileループ内で別のwhileループを追加しない限り、私が使っていることは何ですか? – Veyronvenom1200

+0

@ user7433120ビンゴ:) – Peter

答えて

2

私はこのようにして、メソッドの開始入力を定義し、loop内で"exit"に等しいときにループ内で呼び出します。

elifまた、最初の条件文がTrueの場合は、このようにして、他の条件をチェックしないでください。

def get_start_input(): 
    return input("For sum of squares, type 'squares'. For sum of cubes, type 'cubes'. " 
       "\nIf you would like to raise a number to something other than 'squares' or 'cubes', type 'power'. " 
       "\nIf you would like to exit, type 'exit':") 

def main_function(): 
    while True: 
     start = get_start_input() 
     if start.lower() == "squares": 
      initial = input("What is the initial constant for the sum of the squares: ") 
      terms = input("Number of terms: ") 

     elif start.lower() == "cubes": 
      initial = input("What is the initial constant for the the sum of the cubes: ") 
      terms = input("Number of terms: ") 

     elif start.lower() == "power": 
      initial = input("What is the initial constant for the the sum: ") 
      terms = input("Number of terms: ") 

     elif start.lower() == "exit": 
      print("Program halted normally.") 
      break 

main_function() 

EDIT:仲の良い友達がコメントで書いた

として、それはあなたがいくつかの試合とあいまいな意味を持つことができるので、ここで==の代わりinを使用するのが好ましいです。

+0

素晴らしい作品!ありがとう – Veyronvenom1200

+1

'in'の代わりに' start == "squares" [0:len(start)] '(例えば)それ以外の場合、デバッグが難しいあいまいなマッチがあります。また、ループの開始時に 'start = start.lower()'を実行してください。 – dawg

+0

@dawgあなたと同意して、完了! –

関連する問題