Ex23.py line 10 use of "return"

Can someone explain why ‘return’ is needed in line 10 of ex23.py? I removed it and the program ran the same as before.

It’s not needed. It’s more of a style choice to be explicit as that’s how Python prefers things. The other reason is it tends to avoid bugs when you explicitly return where you want to return. In this case it doesn’t do anything, but if I were to later change up the code and forget to add the return then it could cause problems. By explicitly returning at that point I signal to anyone reading it that I am exiting there, and it prevents future bugs.

2 Likes

Hi! I did the same. I took away “return” and the code still running but until something weird happened when I was trying to trace how the function works. I added several additional lines to the code. The code became like that:

1 import sys 
2 script, input_encoding, error = sys.argv ; print("import")
3 
4 
5 def main(language_file, encoding, errors): 
6     line = language_file.readline(); print("main"); print("if"); i = 0
7 
8     if line: 
9     print_line(line, encoding, errors)
10    main(language_file, encoding, errors) 
11    input("if last"); i += 1; print(i)
12 
13 def print_line(line, encoding, errors): 
14     next_lang = line.strip() 
15     raw_bytes = next_lang.encode(encoding, errors=errors) 
16     cooked_string = raw_bytes.decode(encoding, errors=errors); print("print line:")
17     
18     print(raw_bytes, "<===>", cooked_string) 
19 
20 
21 languages = open("languages.txt", encoding="utf-8"); print("open"); print("call main")
22 
23 main(languages, input_encoding, error)
24 print("end")

And the result like that:

PS C:\Users\User\lpthw> python ex23.py utf-8 strict
import
open
call main
main
if
print line:
b'Afrikaans' <===> Afrikaans
recall_main
main
if
print line:
b'\xe1\x8a\xa0\xe1\x88\x9b\xe1\x88\xad\xe1\x8a\x9b' <===> አማርኛ
recall_main
main
if
print line:
b'\xd0\x90\xd2\xa7\xd1\x81\xd1\x88\xd3\x99\xd0\xb0' <===> Аҧсшәа
recall_main
main
if
print line:
b'\xd8\xa7\xd9\x84\xd8\xb9\xd8\xb1\xd8\xa8\xd9\x8a\xd8\xa9' <===> العربية
recall_main
main
if
print line:
b'Aragon\xc3\xa9s' <===> Aragonés
recall_main
main
if
print line:
b'Arpetan' <===> Arpetan
recall_main
main
if
print line:
b'Az\xc9\x99rbaycanca' <===> Azərbaycanca
recall_main
main
....
1
if last
1
end

So, I think it would be better to use ‘return’ to avoid problems.

Good debugging. I cut your output short though because it’s not necessary to paste in the whole thing. In fact, you might get better results if you made a smaller languages.txt file that had a few lines and worked with that to debug this.