2016-08-06 8 views
0

ユーザーが2つのフットボールチームに入力するプログラムを作成しようとしています。チームは平等ではありません。私が持っている問題は、私のプログラムが自分のエラーメッセージを何度も書き込むということです(毎回リスト内で見つからない)。コードを完全に書き直すことなくこれを回避する方法はありますか?有効なユーザー入力をリストと比較してエラーメッセージを返す

teamlist = ["arsenal", "liverpool", "manchester", "newcastle"] 

def finding_team(home_or_away): 
    while True: 
     user_input = input("Type in " + home_or_away + " team: ") 
     for team in teamlist: 
      if team.upper() == user_input.upper(): 
       return team 
      else: 
       print("Didn't get that, try again") 
       continue 
def team_input(): 
    print() 
    hometeam = finding_team("HOME") 
    awayteam = finding_team("AWAY") 
    while hometeam == awayteam: 
     print("The away team can't be the same as the home team!") 
     awayteam = finding_team("AWAY") 
    return(hometeam, awayteam) 


the_teams = team_input() 
print("The teams you typed in are ", the_teams) 

答えて

1
teamlist = ["arsenal", "liverpool", "manchester", "newcastle"] 

def finding_team(home_or_away): 
    while True: 
     team = input("Type in " + home_or_away + " team: ") 
     if team.lower() in teamlist: 
      return team 
     else: 
      print("Didn't get that, try again") 

def team_input(): 
    print() 
    hometeam = finding_team("HOME") 
    awayteam = finding_team("AWAY") 
    while hometeam == awayteam: 
     print("The away team can't be the same as the home team!") 
     awayteam = finding_team("AWAY") 
    return(hometeam, awayteam) 

the_teams = team_input() 
print("The teams you typed in are ", the_teams) 

teamに格納されている)、ユーザの入力は、単一の条件文でteamlist内のすべての項目に対してチェックされるように、私はそれを変更しました。

Type in HOME team: foo 
Didn't get that, try again 
Type in HOME team: arsenal 
Type in AWAY team: arsenal 
The away team can't be the same as the home team! 
Type in AWAY team: manchester 
The teams you typed in are ('arsenal', 'manchester') 
>>> 
+0

ありがとうございました!しかし、私はまた、大文字/小文字の入力を除いてプログラムにしたい。私はこれを "if team.upper()== user_input.upper()"で解決しようとしていますが、今はもう使えません。 –

+0

@PeterNydahlこのコードは、ユーザーが入力するとうまくいくはずです。それがあなたが求めているのであれば、 "arsenal"の代わりに "arsenal"。 'teamlist'に入力したすべての値は小文字で、' .lower() 'を通してユーザーの入力は小文字に強制されます。 – Tagc

+0

はい、動作しますが、リスト内のチーム名は大文字で始まりますアーセナル、マンチェスターなど)、どうすれば修正できますか?申し訳ありませんが私は質問でこれについて明確にすることを忘れてしまった! –

1

あなたのチームがteamlisteであるかどうかを確認するだけであれば、forループは必要ありません。

teamlist = ["arsenal", "liverpool", "manchester", "newcastle"] 

def finding_team(home_or_away): 
    while True: 
     user_input = input("Type in " + home_or_away + " team: ") 
     if user_input.lower() in teamlist: 
      return user_input.upper() 
     else: 
      print("Didn't get that, try again") 

def team_input(): 
    print() 
    hometeam = finding_team("HOME") 
    awayteam = finding_team("AWAY") 
    while hometeam == awayteam: 
     print("The away team can't be the same as the home team!") 
     awayteam = finding_team("AWAY") 
    return(hometeam, awayteam) 


the_teams = team_input() 
print("The teams you typed in are ", the_teams) 
関連する問題