I am trying to write a simple function to take a char out of a user input in python but keep getting the following error:
Traceback (most recent call last):
File "C:/Users/chris/Desktop/Python_Stuff/replace.py", line 4, in <module>
new= old.replace("*","")
NameError: name 'old' is not defined
This is my code:
def remove_char(old):
old =input("enter a word that includes * ")
return old #do I even need this?
new= old.replace("*","")
print (new)
Thanks in advance for the help!
-
can you pls refine your function indentation?Kasravnd– Kasravnd2015年03月19日 18:10:04 +00:00Commented Mar 19, 2015 at 18:10
-
Yes, you always need this. Since function returns values and procedures perform operations.Mauro Baraldi– Mauro Baraldi2015年03月19日 18:17:36 +00:00Commented Mar 19, 2015 at 18:17
2 Answers 2
Your function's returning a value. Please do not ignore it.
def remove_char(old):
old =input("enter a word that includes * ")
return old
new= remove_char(old).replace("*","")
print (new)
Yes, you may not need return:
old=None
def remove_char():
global old
old =input("enter a word that includes * ")
remove_char() # NOTE: you MUST call this first!
new= old.replace("*","")
print (new)
Note: I agree with @jonrsharpe - the second example shows one of the ugliest ways to achieve what you want! You asked whether you can omit return - yes, but you'd better do not.
4 Comments
global version?return - yes, it is - with globalsYou can not use a method in old variable, because you never defined this variable before. (old is defined and visible just in the function, not outside). You do not really need a function to input the word. Try this:
old = raw_input('enter a word that includes * ')
new= old.replace("*","")
print (new)