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!
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.