+ 1

Why can't i add a list element and a string

I have a function that should add 2 items together, the code is: tokens = ''" command = str(input()) chars = [] def read(): for x in range(len(command)): chars.append(command[x]) tokens += chars[x] if chars[x] == " ": break print(tokens) read() it returns an error saying "local variable 'tokens' referenced before assignment" the heck??? I declared tokens first thing, and it isn't even a global variable, what am I doing wrong?

25th Mar 2017, 12:54 AM
Jacob Schneider
Jacob Schneider - avatar
2 Respuestas
+ 2
command = str(input()) chars = [] def read(): tokens="" for x in range(len(command)): chars.append(command[x]) tokens += chars[x] if chars[x] == " ": break print(tokens) read() Now it works, but I think you have a few things off. You are taking each letter of your string (command) and adding them to the list chars. that's fine. then you are taking them from the list and putting them back into a string (tokens) and printing them out. It all works, but it seems strange to run a string thru a function for no reason other than to spit it back out the other side. It does only result in a string of the first word in the command String, if that was your goal, but that could be accomplished without the added step of building a list of chars. here is a simplified version to get you to the same place. commands=input("Enter Some Words - ") def read(x): newString="" for i in x: if i == " ": break else: newString+=str(i) return print(newString) read(commands)
25th Mar 2017, 5:42 AM
LordHill
LordHill - avatar
+ 1
as to your origional question.. you can add a list item to a string. the problem is your using a variable in a function that was declared outside of it. best bet is use a new variable inside your function and return that as a result. if you want tokens to be your actual variable with the result in it for later use, declare it with the function.. tokens=read() Now tokens would have the returned String you desire. think of a function as its own small program with its own variables separate from your main program and you will be fine
25th Mar 2017, 5:50 AM
LordHill
LordHill - avatar