2016-09-23 5 views
0

したがって、私は国名と対応する株価指数で辞書を持っています。ユーザーは5つの異なる国を入力するよう求められ、プログラムは対応する5つの株価指数をとり、データで何かを実行します。キーが辞書にないときに例外処理を使ってforループを作成するには?

国が見つかった場合は入力を求められますが、これは5回発生します。さて、例外が処理される部分は、私が望んだことをしていません。私のループや例外処理で何が問題になっていますか?

ex_dict = {'United States': '^GSPC','United States of America': '^GSPC', 'Usa': '^GSPC', 'Argentina': '^MERV'} #shortened on purpose 

countries = [] 
print('Please choose five stock exchanges to analyse,') 
print('just name the corresponding countries \n') 

for i in range(0, 5): 
    while True: 
     try: 
      countr = input('Please enter country no. %d: ' %(i+1)) 
      countr = countr.title()    
      if countr in ex_dict.keys(): 
       print('Found the corresponding stock index! \n') 
       countries.append(countr) 
      break 
     except KeyError: 
      print('Country not found, please try again! \n') 
+0

あなたは何をしたいと思いますか?代わりに何をしますか? –

+2

KeyErrorに遭遇することはないので、KeyErrorをキャッチする必要はありません。 ex_dictではif countrの代わりに 'if countr in ex_dict'も使用してください。keys() ' – sisanared

+0

KeyErrorのキャッチではなく単純なelse文で問題を解決します – armak

答えて

2

コードが辞書にアクセスするのに疲れないため、keysにあるかどうかを確認するだけで、KeyErrorはありません。あなたは、単に同じロジックを達成するためにこれを行うことができます:

ex_dict = {'United States': '^GSPC','United States of America': '^GSPC', 'Usa': '^GSPC', 'Argentina': '^MERV'} #shortened on purpose 

countries = [] 
print('Please choose five stock exchanges to analyse,') 
print('just name the corresponding countries \n') 

for i in range(0, 5): 
    while True: 
     countr = input('Please enter country no. %d: ' %(i+1)) 
     countr = countr.title() 
     if countr in ex_dict.keys(): 
      print('Found the corresponding stock index! \n') 
      countries.append(countr) 
      break 
     else: 
      print('Country not found, please try again! \n') 

サンプル実行:

Please choose five stock exchanges to analyse, 
just name the corresponding countries 

Please enter country no. 1: sdf 
Country not found, please try again! 

Please enter country no. 1: USA 
Found the corresponding stock index! 

Please enter country no. 2: Aregtng 
Country not found, please try again! 

Please enter country no. 2: Argentina 
Found the corresponding stock index! 

Please enter country no. 3: United States 
Found the corresponding stock index! 

Please enter country no. 4: usa 
Found the corresponding stock index! 

Please enter country no. 5: usa 
Found the corresponding stock index! 

注:.keys()が過剰です:キーが辞書にある場合にのみ必要チェックするk in some_dict

+0

ロット! – cJc

0

あなたのブレークはifスコープ内にないため、最初の試みでブレークします。

+0

コードを試しましたか?エラーの有無にかかわらず、細かいループを繰り返します。 – cJc

+0

私は、発火することが保証されている休憩のあるwhileループは理にかなっていないことを意味しました。しかし、私はそれが例外をキャッチすることについてあなたの質問に答えなかったと認めます...他の人によると、コードは、 'count_をex_dict.keys()で試してもKeyErrorを発生させませんでした。 –

0

からdoc

Pythonは、次のようにKeyErrorを発生させます。 dict()オブジェクトは(a = adict [key]の形式で)要求され、そのキーは辞書にありません。

ユーザーが国dictに存在しないキーを挿入したときにメッセージを表示する場合は、catch例外ではなくelse文を追加するだけです。

あなたは、このようにコードを変更することができます。ポイントの

if countr in ex_dict.keys(): 
    print('Found the corresponding stock index! \n') 
    countries.append(countr) 
    break 
else: 
    print('Country not found, please try again! \n') 
0

カップル:あなたはまたif key in dict.keys()

  • を使用して、キーの存在をチェックしているので、

    • あなたのコードは、例外をヒットするつもりはありません非常に多くのループがあります。私はfor i in range(0,5)で十分だと思っています。はあまり複雑ではありませんです。

      ex_dict = {'United States': '^GSPC','United States of America': '^GSPC', 'Usa': '^GSPC', 'Argentina': '^MERV'} #shortened on purpose 
      
      countries = [] 
      print('Please choose five stock exchanges to analyse,') 
      print('just name the corresponding countries \n') 
      
      for i in range(0, 5): 
          countr = raw_input('Please enter country no. %d: ' %(i+1)) 
          countr = countr.title() 
          if countr in ex_dict.keys(): 
           print('Found the corresponding stock index! \n') 
           countries.append(countr) 
          else: 
           print('Country not found, please try again! \n') 
      

    出力:

    C:\Users\dinesh_pundkar\Desktop>python c.py 
    Please choose five stock exchanges to analyse, 
    just name the corresponding countries 
    
    Please enter country no. 1: USA 
    Found the corresponding stock index! 
    
    Please enter country no. 2: asd 
    Country not found, please try again! 
    
    Please enter country no. 3: asd 
    Country not found, please try again! 
    
    Please enter country no. 4: USA 
    Found the corresponding stock index! 
    
    Please enter country no. 5: United states 
    Found the corresponding stock index! 
    
    
    C:\Users\dinesh_pundkar\Desktop> 
    
  • 0

    私は私が行うには、コードを変更した、あなたは在庫が辞書ex_dictでない場合、それはあなたのメッセージを与えたいと仮定しています同じ。

    ex_dict = {'United States': '^GSPC','United States of America': '^GSPC', 'Usa': '^GSPC', 'Argentina': '^MERV'} #shortened on purpose 
    
    countries = [] 
    print('Please choose five stock exchanges to analyse,') 
    print('just name the corresponding countries \n') 
    
    for i in range(0, 5): 
        while True: 
         try: 
          countr = input('Please enter country no. %d: ' %(i+1)) 
          countr = countr.title()    
          if countr not in ex_dict.keys(): 
           print ('Try again!') 
          else: 
           print('Found the corresponding stock index! \n') 
           countries.append(countr) 
    
    関連する問題