【问题标题】:Trouble getting if statement to work in def, but not in interpreter无法让 if 语句在 def 中工作,但不能在解释器中工作
【发布时间】:2015-02-09 01:26:14
【问题描述】:

当我在解释器中运行这些命令时,我得到了我想要的结果。但是,当我尝试使用 .py 文件运行它时,我没有。我是编码新手,在我的脑海中,我不明白为什么这段代码不起作用。

在解释器中:

>>> a = 'This dinner is not that bad!'
>>> n = a.find('not')
>>> b = a.find('bad')
>>> if n < b:
      a.replace(a[n:], 'good')
'This dinner is good'

这就是我想要的结果。

当我运行这段代码时,我没有得到我想要的结果。我做错了什么,为什么这段代码不起作用?

def test(s):
  n = s.find('not')
  b = s.find('bad')

  if n < b:
    s.replace(s[n:], 'good')
print test('This dinner is not that bad!')

这是来自 google intro to python 课程的练习。我从这个例子中得到了正确的答案,并理解它是如何工作的。我只是不确定为什么我的代码不起作用。

感谢您的帮助。

【问题讨论】:

    标签: python string if-statement function


    【解决方案1】:
    def test(s):
      n = s.find('not')
      b = s.find('bad')
    
      if n < b:
        return s.replace(s[n:], 'good')
    print test('This dinner is not that bad!')
    

    你应该return函数test的结果。

    【讨论】:

    • 完美!谢谢...我只是在 s.replace 之后做 return s,它给了我相同的 str。感谢您的帮助
    【解决方案2】:

    因为在函数版本中,你会得到None作为默认值,你没有返回值:

    def test(s):
      n = s.find('not')
      b = s.find('bad')
      return_res = ''
    
      if n < b:
        return_res = s.replace(s[n:], 'good')
    
      return return_res
    
    print test('This dinner is not that bad!')
    

    输出:

    This dinner is good
    

    或者不使用return_res:

    def test(s):
      n = s.find('not')
      b = s.find('bad')
    
      if n < b:
        return s.replace(s[n:], 'good')
    
      return "something else"
    
    print test('This dinner is not that bad!')
    

    【讨论】:

    • 谢谢!这很有帮助
    【解决方案3】:

    大多数(或所有?)IDE 中的解释器,如果我没记错的话(我使用 Sublime 执行我的代码,它会在执行时保存并运行文件),你会自动打印最后一个表达式的结果,给你一种 Python 代码以这种方式运行的错误印象。它没有。

    换句话说:您的代码在解释器和文件中的工作方式相同。您遇到的问题是一种误解,即代码在解释器中做了不同的事情。真正发生的是,在代码 sn-p 中,您实际上都没有catch 结果并打印它;在解释器的情况下,它会自动打印它作为一种视觉辅助工具,但你不能依赖它。

    在你的第二个 sn-p 中,你必须写:

    return s.replace(s[n:], 'good')
    

    注意在这种情况下使用 return。在您的第一个示例中,您 应该捕获它或至少显式打印结果。但是因为它没有包含在函数中,所以等价于:

    if n < b:
        print a.replace(a[n:], 'good')
    

    或:

    if n < b:
        newString = a.replace(a[n:], 'good')
    
    print newString
    

    【讨论】:

    • 感谢您的详细回复!我清楚地看到了我所缺少的东西。谢谢
    猜你喜欢
    • 1970-01-01
    • 2018-02-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-13
    • 2016-06-18
    • 2011-03-14
    • 1970-01-01
    相关资源
    最近更新 更多