将有效用户输入与列表进行比较并返回错误消息

时间:2016-08-06 21:49:06

标签: python-3.x

我试图编写一个用户输入两个足球队的程序。团队不平等。我遇到的问题是我的程序多次写入我的错误信息(每次它都没有在列表中找到它)。反正有没有完全重写代码吗?

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)

2 个答案:

答案 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)

答案 1 :(得分:1)

#include "First.h"
#include "Second.h"

FirstStruct foo(void);
/* Other functions */

我对其进行了更改,以便在单个条件语句中针对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