0

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!

2
  • can you pls refine your function indentation? Commented Mar 19, 2015 at 18:10
  • Yes, you always need this. Since function returns values and procedures perform operations. Commented Mar 19, 2015 at 18:17

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

Why on earth would you provide the global version?
@jonrsharpe, OP asked if it was possible to remove return - yes, it is - with globals
At the very least, you should point out that that is a terrible way of writing the program...
The wrong answer to this question is: "Because I can". The right version: True, why the hell I did that!?
0

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)

1 Comment

Thanks, yeah I noticed I didn't need the function, I was just trying to gain a better understanding! I probably chose the wrong example. Thanks for the input!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.