+ 1

why does this give me an error?

txt = input() list = txt.split() var = 0 for word in list: if len(word) > var: var = word print(var)

15th Aug 2021, 9:24 PM
rain
7 odpowiedzi
+ 3
It will still throw errors for most inputs. var = word means that you again assign a string to var which will cause an error in the next iteration.
15th Aug 2021, 9:34 PM
Simon Sauter
Simon Sauter - avatar
+ 4
Var is a string, so the comparison with len(word) makes no sense and will throw an error. Use var = 0 instead.
15th Aug 2021, 9:27 PM
Simon Sauter
Simon Sauter - avatar
+ 3
A tip for the future: using descriptive variable names makes mistakes like this less likely. E.g. instead of "var" you could use "max_length". That way it's immediately obvious that assigning a word to it makes no sense.
15th Aug 2021, 9:46 PM
Simon Sauter
Simon Sauter - avatar
+ 1
this works!
15th Aug 2021, 9:35 PM
rain
0
i was trying to print the longest word
15th Aug 2021, 9:35 PM
rain
0
txt = input() list = txt.split() var = 0 for word in list: if len(word) > var: var = len(word) for word in list: if len(word) == var: print(word)
15th Aug 2021, 9:35 PM
rain
0
i see, thanks
15th Aug 2021, 9:47 PM
rain