【问题标题】:How do you return the result in my code?你如何在我的代码中返回结果?
【发布时间】:2016-02-12 01:16:57
【问题描述】:
#Soccer Matchup Possibilities 
def soccermatchups(team1,team2):
    result=" "
    if (team1== "Brazil" and team2== "Canada"):
        result= "These teams could play each other in the World Cup!"
    if (team1== " England" and team2== "Netherlands"):
        result= "These teams could play each other in both Cups!"
        return(result)

我遇到了上面显示的结果没有返回的问题,我该怎么办?我在这方面遇到了一些麻烦!我会很感激帮助,这是在 Python 2.7 中。

【问题讨论】:

  • return 语句缩进一级太远,无法始终返回 result

标签: python python-2.7 syntax return


【解决方案1】:

如果您的第二个 if 计算结果为 False,则返回的值是 None,因为您只返回一个值第二个 if

return result(取消缩进一次)移到第二个if 语句之外以获得结果,无论您的if 语句评估为什么:

def soccermatchups(team1, team2):
    result=" "
    if (team1== "Brazil" and team2== "Canada"):
        result= "These teams could play each other in the World Cup!"
    if (team1== " England" and team2== "Netherlands"):
        result= "These teams could play each other in both Cups!"

    # return value either way
    return(result) 

【讨论】:

  • 它仍然没有返回结果我需要打印一些东西吗?
  • 它是否可能返回一个空字符串" "?如果是这样,您的任何if 子句都不会评估为True
  • 所以我应该让这些球队互相比赛?
  • 不太清楚你的意思。返回的函数是什么?
  • 在我输入这两支球队后它什么也没返回,它只在我打印时输出/返回 (str(soccermatchups))
【解决方案2】:

将最后一行左移一个制表符。

如果两个 if 语句都不为 True,你将返回 None。

【讨论】:

  • 如何显示结果我需要打印语句吗?
  • 打印soccermatchups(team1, team2)
  • 如果你打算走那条路,你还应该将'result'设置为有意义的东西。喜欢结果 = False。
  • 是的,我只需要那个打印声明,我认为现在可以使用了!非常感谢!
【解决方案3】:
def soccermatchups(team1,team2):
    if (team1== "Brazil" and team2== "Canada"):
        print "These teams could play each other in the World Cup!"
    if (team1== "England" and team2== "Netherlands"):
        print "These teams could play each other in both Cups!"
    return False


soccermatchups('Brazil', 'Canada')
soccermatchups('England', 'Netherlands')

【讨论】:

    【解决方案4】:
    '''
    #Soccer Match-ups Program
    #Author: Coleton Ishmael
    #Class: ICS3U
    #Date: 11/10/15
    '''
    #Soccer Matchup Possibilities 
    def soccermatchups(team1,team2):
        result="They cannot play each other in either the Euro or World Cup."
        if (team1== " Brazil" and team2== " Canada"):
            result= "They can play in the World Cup!"
        if (team1== " England" and team2== " Netherlands"):
            result= "They can play in both the Euro and World Cup!"
        return (result)
    
    '''
    Main Program
    @parm Brian
    @parm Alyssa
    @return result
    '''
    # Get User's team selection
    team1= raw_input (" Enter your first team:")
    team2= raw_input (" Enter your second team:")
    
    
    #Output
    print soccermatchups(team1,team2) 
    

    这就像一个魅力!感谢贡献者,你们帮助我理解了这个概念! :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-04-20
      • 1970-01-01
      • 2021-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-15
      相关资源
      最近更新 更多