Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

python - return and print does not give same result

what I'm trying to do is take the entered string separated by commas and change it to list then for each list as a key print the associated value.

def main():
    myDict = {'a':1, 'b':2, 'c':3, 'd':4, 'e':5....}
    u_input = input("Enter a letter")
    myList = [x.strip() for x in u_input.split(',')]
    result = searchDict(myList)
    print(result)

def searchDict(key):
    for ml in key:
        value = myDict.get(ml, "not found")
        re = []
        re.append(value)
        print('-'.join(re)) #this one shows each value for each entered key separated by comma but it does not print it in one line also prints 'None' on the end

    #res = '-'.join(re)
    #return res //this only shows the value for the first key only even if I enter multiple letter

main();

The prob is that, if I return 'res' instead of printing it, I'm only getting the first key value.

output with print(if I enter a, b): 1, 2, none

output with return 1

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Are these lines indented properly?

for ml in key:
value = myDict.get(ml, "not found"); 
re = [];
re.append(value)

I think you want it to do this:

re = []
for ml in key:
    value = myDict.get(ml, "not found")    
    re.append(value)
return '-'.join(re)

BTW no semicolons used in Python.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...