Return in python, reading values from .txt file
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
add a comment |
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
1
You should usetry
inside the function, instead of defining the function inside of it.
– Óscar López
Nov 20 '18 at 9:49
add a comment |
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
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
python printing return
asked Nov 20 '18 at 9:30
AleAle
3524924
3524924
1
You should usetry
inside the function, instead of defining the function inside of it.
– Óscar López
Nov 20 '18 at 9:49
add a comment |
1
You should usetry
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
add a comment |
3 Answers
3
active
oldest
votes
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"
add a comment |
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.
Got it! Thanks for explanation
– Ale
Nov 20 '18 at 9:45
add a comment |
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)
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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"
add a comment |
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"
add a comment |
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"
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"
edited Nov 20 '18 at 9:45
answered Nov 20 '18 at 9:37
Óscar LópezÓscar López
176k24225321
176k24225321
add a comment |
add a comment |
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.
Got it! Thanks for explanation
– Ale
Nov 20 '18 at 9:45
add a comment |
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.
Got it! Thanks for explanation
– Ale
Nov 20 '18 at 9:45
add a comment |
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.
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.
answered Nov 20 '18 at 9:36
richflowrichflow
866210
866210
Got it! Thanks for explanation
– Ale
Nov 20 '18 at 9:45
add a comment |
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
add a comment |
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)
add a comment |
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)
add a comment |
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)
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)
answered Nov 20 '18 at 9:55
timmytimmy
708
708
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
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