0

Could you please tell me why I am getting this error? When I enter the input I am expecting a string but I get the below error instead,

File "ifelif.py", line 1, in <module> first_name = input("What is your first name? ") File "<string>", line 1, in <module> NameError: name 'Caitlin' is not defined

I am using this code:

first_name = input("What is your first name? ") 
print("Hello,", first_name) 
if first_name == "Caitlin": 
 print(first_name, "is learning Python") 
 print("Have a great day {}!".format(first_name))

When I enter the name in the Terminal with quotes to make a string, it works but I get 2 strings instead of 1 string :

('Hello,', 'Ed')

The name of the file is 'ifelif.py'

Many thanks!

  • Does this answer your question? https://stackoverflow.com/questions/21122540/input-error-nameerror-name-is-not-defined/21122817 – adamgy May 26 '20 at 23:26
  • Does this answer your question? [input() error - NameError: name '...' is not defined](https://stackoverflow.com/questions/21122540/input-error-nameerror-name-is-not-defined) – adamgy May 26 '20 at 23:31
  • @adamgy Thanks! This really helped! – trailrunner89 May 26 '20 at 23:34

2 Answers2

0

If you are using Python2 you should be using raw_input. In Python2 input will evaluate what you type which is why you are getting that error.

RedKnite
  • 1,525
  • 13
  • 26
0

tested your code. looks fine with me. no error at all. it behave the way I expect it to do, or what is your output expectation?

first_name = input("What is your first name? ") 
print("Hello,", first_name) 
if first_name == "Caitlin": 
 print(first_name, "is learning Python") 
 print("Have a great day {}!".format(first_name))

1st input: boy, output is:

What is your first name? boy
Hello, boy

2nd input: Caitlin, output is:

What is your first name? Caitlin
Hello, Caitlin
Caitlin is learning Python
Have a great day Caitlin!

this is probably just code writing style/preference, but I would do it like:

print(f"{first_name} is learning Python") 
print(f"Have a great day {first_name}!")

it's called "f string print" where you put the variable in curly bracket