Reputation: 7
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!
Upvotes: 0
Views: 440
Reputation: 2374
You 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)
Upvotes: 0
Reputation: 44828
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.
Upvotes: 1