n1hlk
Posts: 2
Joined: Fri Mar 31, 2017 2:51 pm

Must be a simple answer to this keyboard input problem

Fri Oct 19, 2018 10:48 pm

input() works great with numbers (int's and float's)
but the below 4 line code comes the error.

Code: Select all

1
2 usr = input('Enter User number : ')
3 fn = input(' Enter First Name : ')
4 print(fn+' is user '+str(usr))
I get this error:
Traceback (most recent call last):
File "/home/keith/test-input.py", line 3, in <module>
fn = input(' Enter First Name : ')
File "<string>", line 1, in <module>
NameError: name 'Keith' is not defined

I don't understand why fn=input(), it want to define the input data Keith as var ?

If I input "Keith" in quote on the input line, it works
I can't be tell users that all text items have to be in quotes

My project, I using a Pi at a fuel tank to collect data of usage at a small bus company.
That 300+ lines code works, At the tank al they have is a number pad and screen.
But somebody wants the reports to names instead of number, So I need to write
a small utils program to add names to the numbers is when this error came up.

Keith aka N1HLK

User avatar
buja
Posts: 474
Joined: Wed Dec 31, 2014 8:21 am
Location: Netherlands

Re: Must be a simple answer to this keyboard input problem

Sat Oct 20, 2018 5:43 am

This runs okay in Python3, but gives the error in Python2.

For Python2 this should do it:

Code: Select all

print fn,"is user", usr

User avatar
Paeryn
Posts: 2171
Joined: Wed Nov 23, 2011 1:10 am
Location: Sheffield, England

Re: Must be a simple answer to this keyboard input problem

Sat Oct 20, 2018 8:15 am

buja wrote:
Sat Oct 20, 2018 5:43 am
This runs okay in Python3, but gives the error in Python2.

For Python2 this should do it:

Code: Select all

print fn,"is user", usr
No, that won't solve anything. The problem is that in Python2 input() will evaluate what was entered and return that. This is why numbers work fine but strings don't. Essentially when the user entered Keith Python tries to return the value of Keith rather than the string "Keith".

For Python2 you need to use raw_input() to return the string that the user enters. Python3 fixed this by removing the evaluating version of input() and renaming raw_input() to input().
She who travels light — forgot something.

n1hlk
Posts: 2
Joined: Fri Mar 31, 2017 2:51 pm

Re: Must be a simple answer to this keyboard input problem

Sat Oct 20, 2018 10:15 am

I knew it was something simple, Thanks
When I first wrote the little utils program a month ago or so, thought it was working. I wasn't watching the IDE at start. Just found out the both IDLE's in the menu goes to 2.7, even the one not lable as 2.7
Image

Thanks

Return to “Python”