In python, why a variable which is assigned an integer value in a function but outside for loop ,return type as string

huangapple go评论49阅读模式
英文:

In python, why a variable which is assigned an integer value in a function but outside for loop ,return type as string

问题

以下是代码,我想返回字典中值的最大长度。

def longest_value(d={}):
    max_len = 0
    for k, v in d.items():
        if len(v) > max_len:
            max_len = len(v)
    return max_len

if __name__ == '__main__':
    fruits = {'fruit': 'apple', 'color': 'orange'}
    print(longest_value(fruits))

当运行此代码时,抛出的错误是:Type Error。但是,如果我检查 max_len 的类型,它返回字符串,即使我将其分配为全局变量仍然会抛出相同的错误。如果我在 for 循环内部分配变量,它可以工作,但我想知道为什么在第一种情况下不起作用,需要遵循哪些规则。

尽管这个问题可能相当简单,但在发帖之前我已经努力搜索答案,但没有成功。所以感谢任何关于这个问题的帮助。谢谢。

英文:

Here is the code, where I want to return the value in the dictionary with maximum length.
The code goes as follows:

def longest_value(d={}):
    max_len = 0
    for k,v in d.items():
        if len(v) > max_len:
            max_len = v

    return max_len

if __name__ == '__main__':
    fruits = {'fruit': 'apple', 'color': 'orange'}
    print(longest_value(fruits))

When I run this code, the error thrown is:In python, why a variable which is assigned an integer value in a function but outside for loop ,return type as string
however, if I check the type for max_len it returns string, even if I assign it as global still it throws the same error.
If I assign the variable inside the for loop it works, but I want to know why it is not working in the first case, what are the rules which needs to be followed here.

Though this question could be pretty lame, but I tried hard before posting, to search for an answer online, but I dint succeed. So appreciate any help on this.
Thanks

答案1

得分: 3

第一次迭代会得到例如:

k, v = 'fruit', 'apple'

然后你设置 max_len = 'apple'。在下一次迭代中,你会得到

k, v = 'color', 'orange'

然后你会问 len('orange') > 'apple'。左边是一个整数,右边是一个字符串。

如果你在循环内部设置 max_len = 0,你每次都会重置计数器(len(v) > 0),所以函数总是返回最后一个项目。

英文:

The first iteration gives you e.g.

k, v = 'fruit', 'apple'

and you set max_len = 'apple'. In the next iteration, you get

k, v = 'color', 'orange'

and you ask if len('orange') > 'apple'. The left side is an integer, the right one is a string.

If you set max_len = 0 inside the loop, you reset the counter each time (len(v) > 0), so the function always returns the last item.

huangapple
  • 本文由 发表于 2023年5月11日 03:18:44
  • 转载请务必保留本文链接:https://go.coder-hub.com/76221909.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定