-1

Can't figure this one out and there doesn't seem to be any info on the web either. Tried it with both Python 2 and 3.

def load_settings():
    try:
        with open('settings.txt', 'r') as f:
            return f.read()
    except FileNotFoundError:
        with open('settings.txt', 'w') as f:
            f.write('default_settings')
        load_settings()

I would expect the above function to return 'default_settings' given that settings.txt doesn't already exist. Instead it returns None.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555
Kristjan
  • 23
  • 6
  • 3
    you forgot the `return` in the recursive call... Last line should be `return load_settings()`, not `load_settings()`. – Willem Van Onsem Mar 31 '17 at 09:06
  • I apologize for bad Googleing skills - Came out nicely with the right search term. Thanks for all the answers tho! – Kristjan Mar 31 '17 at 15:17

2 Answers2

0

Change your last line to

return load_settings()

Otherwise, you call your function, but don't return its value.

BlueMoon93
  • 2,910
  • 22
  • 39
  • As stated in [answer], please avoid answering unclear, overly-broad, typo, unreproducible, or duplicate questions. Write-my-code requests and low-effort homework questions are off-topic for [so] and more suited to professional coding/tutoring services. Good questions adhere to [ask], include a [mcve], have research effort, and have the potential to be useful to future visitors. Answering inappropriate questions harms the site by making it more difficult to navigate and encouraging further such questions, which can drive away other users who volunteer their time and expertise. – TigerhawkT3 Mar 31 '17 at 09:14
-1

Change your code to this,

def load_settings():
    try:
        with open('settings.txt', 'r') as f:
            return f.read()
    except FileNotFoundError:
        with open('settings.txt', 'w') as f:
            f.write('default_settings')
        return load_settings()
Surajano
  • 2,688
  • 13
  • 25
  • 1
    As stated in [answer], please avoid answering unclear, overly-broad, typo, unreproducible, or duplicate questions. Write-my-code requests and low-effort homework questions are off-topic for [so] and more suited to professional coding/tutoring services. Good questions adhere to [ask], include a [mcve], have research effort, and have the potential to be useful to future visitors. Answering inappropriate questions harms the site by making it more difficult to navigate and encouraging further such questions, which can drive away other users who volunteer their time and expertise. – TigerhawkT3 Mar 31 '17 at 09:14