Return in python, reading values from .txt file












0















Level: beginner



Hey, i'm trying to resolve an exercise in Python.



The code is comparing userName given in function argument print(getUserPoint("Benny")) ,if that name exists in userScores.txt, i'd like to return user score, otherwise i'd like to return a string "-1".



If i use print a result is printed as expected, however if i use return, function always returns "-1", even if a userName exists in a file.



Looks like it reads only the first user, score values from the .txt file.



Can anybody please explain why "return" works that way in this case?



userScores.txt:



Ann, 100
Benny, 102
Carol, 214
Darren, 129


Code:



  try:
def getUserPoint(userName):
f = open("userScores.txt", "r")
file = f.readlines()
print(file)
for item in file:
print(item)
content = item.split(',')
if content[0] == userName:
f.close()
return content[1]
#print(content[1])
else:
f.close()
return "-1"
#print("-1")
except IOError:
print("File not found")
f = open("userScores.txt", "w")
f.close()
print("-1")









share|improve this question


















  • 1





    You should use try inside the function, instead of defining the function inside of it.

    – Óscar López
    Nov 20 '18 at 9:49
















0















Level: beginner



Hey, i'm trying to resolve an exercise in Python.



The code is comparing userName given in function argument print(getUserPoint("Benny")) ,if that name exists in userScores.txt, i'd like to return user score, otherwise i'd like to return a string "-1".



If i use print a result is printed as expected, however if i use return, function always returns "-1", even if a userName exists in a file.



Looks like it reads only the first user, score values from the .txt file.



Can anybody please explain why "return" works that way in this case?



userScores.txt:



Ann, 100
Benny, 102
Carol, 214
Darren, 129


Code:



  try:
def getUserPoint(userName):
f = open("userScores.txt", "r")
file = f.readlines()
print(file)
for item in file:
print(item)
content = item.split(',')
if content[0] == userName:
f.close()
return content[1]
#print(content[1])
else:
f.close()
return "-1"
#print("-1")
except IOError:
print("File not found")
f = open("userScores.txt", "w")
f.close()
print("-1")









share|improve this question


















  • 1





    You should use try inside the function, instead of defining the function inside of it.

    – Óscar López
    Nov 20 '18 at 9:49














0












0








0








Level: beginner



Hey, i'm trying to resolve an exercise in Python.



The code is comparing userName given in function argument print(getUserPoint("Benny")) ,if that name exists in userScores.txt, i'd like to return user score, otherwise i'd like to return a string "-1".



If i use print a result is printed as expected, however if i use return, function always returns "-1", even if a userName exists in a file.



Looks like it reads only the first user, score values from the .txt file.



Can anybody please explain why "return" works that way in this case?



userScores.txt:



Ann, 100
Benny, 102
Carol, 214
Darren, 129


Code:



  try:
def getUserPoint(userName):
f = open("userScores.txt", "r")
file = f.readlines()
print(file)
for item in file:
print(item)
content = item.split(',')
if content[0] == userName:
f.close()
return content[1]
#print(content[1])
else:
f.close()
return "-1"
#print("-1")
except IOError:
print("File not found")
f = open("userScores.txt", "w")
f.close()
print("-1")









share|improve this question














Level: beginner



Hey, i'm trying to resolve an exercise in Python.



The code is comparing userName given in function argument print(getUserPoint("Benny")) ,if that name exists in userScores.txt, i'd like to return user score, otherwise i'd like to return a string "-1".



If i use print a result is printed as expected, however if i use return, function always returns "-1", even if a userName exists in a file.



Looks like it reads only the first user, score values from the .txt file.



Can anybody please explain why "return" works that way in this case?



userScores.txt:



Ann, 100
Benny, 102
Carol, 214
Darren, 129


Code:



  try:
def getUserPoint(userName):
f = open("userScores.txt", "r")
file = f.readlines()
print(file)
for item in file:
print(item)
content = item.split(',')
if content[0] == userName:
f.close()
return content[1]
#print(content[1])
else:
f.close()
return "-1"
#print("-1")
except IOError:
print("File not found")
f = open("userScores.txt", "w")
f.close()
print("-1")






python printing return






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 20 '18 at 9:30









AleAle

3524924




3524924








  • 1





    You should use try inside the function, instead of defining the function inside of it.

    – Óscar López
    Nov 20 '18 at 9:49














  • 1





    You should use try inside the function, instead of defining the function inside of it.

    – Óscar López
    Nov 20 '18 at 9:49








1




1





You should use try inside the function, instead of defining the function inside of it.

– Óscar López
Nov 20 '18 at 9:49





You should use try inside the function, instead of defining the function inside of it.

– Óscar López
Nov 20 '18 at 9:49












3 Answers
3






active

oldest

votes


















2














You're closing the file after the first iteration, you should eliminate the else that's inside the loop and extract it outside. In fact, I propose that you should refactor the code to use with, it's a much cleaner way to handle closing files:



def getUserPoint(userName):
try:
with open("userScores.txt", "r") as file:
for item in file:
print(item)
content = item.split(',')
if content[0] == userName:
return content[1]
return "-1"
except IOError:
print("File not found")
return "-1"





share|improve this answer

































    1














    On the first iteration of the loop where the name in the file does not match the name you passed to the function, it will return and not continue the loop.



    E.g. If you call getUserPoint('Benny')



    On the first iteration of the loop, it will compare "Ann" == "Benny"



    This returns false, so the control goes to your else clause and return from the function - no more looping.






    share|improve this answer
























    • Got it! Thanks for explanation

      – Ale
      Nov 20 '18 at 9:45



















    0














    import os

    def getUserPoint(userName):
    f=open('userScores.txt')
    file=f.readlines()
    for item in file:

    content=item.split(',')

    if content[0]==userName:
    f.close()
    return content[1]
    else:
    continue

    f.close()
    print('UserNotfound')
    return '-1'

    x=getUserPoint('Benny')
    print(x)





    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function () {
      StackExchange.using("externalEditor", function () {
      StackExchange.using("snippets", function () {
      StackExchange.snippets.init();
      });
      });
      }, "code-snippets");

      StackExchange.ready(function() {
      var channelOptions = {
      tags: "".split(" "),
      id: "1"
      };
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function() {
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled) {
      StackExchange.using("snippets", function() {
      createEditor();
      });
      }
      else {
      createEditor();
      }
      });

      function createEditor() {
      StackExchange.prepareEditor({
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader: {
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      },
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      });


      }
      });














      draft saved

      draft discarded


















      StackExchange.ready(
      function () {
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53389948%2freturn-in-python-reading-values-from-txt-file%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      You're closing the file after the first iteration, you should eliminate the else that's inside the loop and extract it outside. In fact, I propose that you should refactor the code to use with, it's a much cleaner way to handle closing files:



      def getUserPoint(userName):
      try:
      with open("userScores.txt", "r") as file:
      for item in file:
      print(item)
      content = item.split(',')
      if content[0] == userName:
      return content[1]
      return "-1"
      except IOError:
      print("File not found")
      return "-1"





      share|improve this answer






























        2














        You're closing the file after the first iteration, you should eliminate the else that's inside the loop and extract it outside. In fact, I propose that you should refactor the code to use with, it's a much cleaner way to handle closing files:



        def getUserPoint(userName):
        try:
        with open("userScores.txt", "r") as file:
        for item in file:
        print(item)
        content = item.split(',')
        if content[0] == userName:
        return content[1]
        return "-1"
        except IOError:
        print("File not found")
        return "-1"





        share|improve this answer




























          2












          2








          2







          You're closing the file after the first iteration, you should eliminate the else that's inside the loop and extract it outside. In fact, I propose that you should refactor the code to use with, it's a much cleaner way to handle closing files:



          def getUserPoint(userName):
          try:
          with open("userScores.txt", "r") as file:
          for item in file:
          print(item)
          content = item.split(',')
          if content[0] == userName:
          return content[1]
          return "-1"
          except IOError:
          print("File not found")
          return "-1"





          share|improve this answer















          You're closing the file after the first iteration, you should eliminate the else that's inside the loop and extract it outside. In fact, I propose that you should refactor the code to use with, it's a much cleaner way to handle closing files:



          def getUserPoint(userName):
          try:
          with open("userScores.txt", "r") as file:
          for item in file:
          print(item)
          content = item.split(',')
          if content[0] == userName:
          return content[1]
          return "-1"
          except IOError:
          print("File not found")
          return "-1"






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 20 '18 at 9:45

























          answered Nov 20 '18 at 9:37









          Óscar LópezÓscar López

          176k24225321




          176k24225321

























              1














              On the first iteration of the loop where the name in the file does not match the name you passed to the function, it will return and not continue the loop.



              E.g. If you call getUserPoint('Benny')



              On the first iteration of the loop, it will compare "Ann" == "Benny"



              This returns false, so the control goes to your else clause and return from the function - no more looping.






              share|improve this answer
























              • Got it! Thanks for explanation

                – Ale
                Nov 20 '18 at 9:45
















              1














              On the first iteration of the loop where the name in the file does not match the name you passed to the function, it will return and not continue the loop.



              E.g. If you call getUserPoint('Benny')



              On the first iteration of the loop, it will compare "Ann" == "Benny"



              This returns false, so the control goes to your else clause and return from the function - no more looping.






              share|improve this answer
























              • Got it! Thanks for explanation

                – Ale
                Nov 20 '18 at 9:45














              1












              1








              1







              On the first iteration of the loop where the name in the file does not match the name you passed to the function, it will return and not continue the loop.



              E.g. If you call getUserPoint('Benny')



              On the first iteration of the loop, it will compare "Ann" == "Benny"



              This returns false, so the control goes to your else clause and return from the function - no more looping.






              share|improve this answer













              On the first iteration of the loop where the name in the file does not match the name you passed to the function, it will return and not continue the loop.



              E.g. If you call getUserPoint('Benny')



              On the first iteration of the loop, it will compare "Ann" == "Benny"



              This returns false, so the control goes to your else clause and return from the function - no more looping.







              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Nov 20 '18 at 9:36









              richflowrichflow

              866210




              866210













              • Got it! Thanks for explanation

                – Ale
                Nov 20 '18 at 9:45



















              • Got it! Thanks for explanation

                – Ale
                Nov 20 '18 at 9:45

















              Got it! Thanks for explanation

              – Ale
              Nov 20 '18 at 9:45





              Got it! Thanks for explanation

              – Ale
              Nov 20 '18 at 9:45











              0














              import os

              def getUserPoint(userName):
              f=open('userScores.txt')
              file=f.readlines()
              for item in file:

              content=item.split(',')

              if content[0]==userName:
              f.close()
              return content[1]
              else:
              continue

              f.close()
              print('UserNotfound')
              return '-1'

              x=getUserPoint('Benny')
              print(x)





              share|improve this answer




























                0














                import os

                def getUserPoint(userName):
                f=open('userScores.txt')
                file=f.readlines()
                for item in file:

                content=item.split(',')

                if content[0]==userName:
                f.close()
                return content[1]
                else:
                continue

                f.close()
                print('UserNotfound')
                return '-1'

                x=getUserPoint('Benny')
                print(x)





                share|improve this answer


























                  0












                  0








                  0







                  import os

                  def getUserPoint(userName):
                  f=open('userScores.txt')
                  file=f.readlines()
                  for item in file:

                  content=item.split(',')

                  if content[0]==userName:
                  f.close()
                  return content[1]
                  else:
                  continue

                  f.close()
                  print('UserNotfound')
                  return '-1'

                  x=getUserPoint('Benny')
                  print(x)





                  share|improve this answer













                  import os

                  def getUserPoint(userName):
                  f=open('userScores.txt')
                  file=f.readlines()
                  for item in file:

                  content=item.split(',')

                  if content[0]==userName:
                  f.close()
                  return content[1]
                  else:
                  continue

                  f.close()
                  print('UserNotfound')
                  return '-1'

                  x=getUserPoint('Benny')
                  print(x)






                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 20 '18 at 9:55









                  timmytimmy

                  708




                  708






























                      draft saved

                      draft discarded




















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid



                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.


                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function () {
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53389948%2freturn-in-python-reading-values-from-txt-file%23new-answer', 'question_page');
                      }
                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      android studio warns about leanback feature tag usage required on manifest while using Unity exported app?

                      SQL update select statement

                      'app-layout' is not a known element: how to share Component with different Modules