print("Please Enter:")
x = input()
print(x)
In the console after "Please Enter:" is printed the line changes. I want that I should be able to provide input in the same line of "Please Enter:". Is there any method to prevent the change of line?
Instead of print(), use input() to produce the prompt:
x = input("Please Enter: ")
From the input() function documentation:
input([prompt])
If the prompt argument is present, it is written to standard output without a trailing newline.
Related
This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 1 year ago.
I am fairly new to python. I am trying to get an input from the user running the script. Below is my script:
print("This is the program to test if we can get the user's input")
users_input = input("Please enter your name. Please note that it should be a single word >>> ")
print("Is this your name? ", users_input)
Going through a few websites, this seems to be enough. But when i run this script and am asked to enter the name, I type the name and as soon as I press enter, I get the below error:
Traceback (most recent call last):
File "test_input.py", line 3, in <module>
users_input = input("Please enter your name. Please note that it should be a single word >>> ")
File "<string>", line 1, in <module>
NameError: name 'John' is not defined
I was expecting it to print the name but rather I get this error. Not sure why.
Use raw_input() instead, since you're using Python 2.7.
raw_input gets the input as text (i.e. the characters that are typed), but it makes no attempt to translate them to anything else; i.e. it always returns a string.
input gets the input value as text, but then attempts to automatically convert the value into a sensible data type; so if the user types ‘1’ then Python 2 input will return the integer 1, and if the user types ‘2.3’ then Python 2 input will return a floating point number approximately equal to 2.3
input is generally considered unsafe; it is always far better for the developer to make decisions about how the data is interpreted/converted, rather than have some magic happen which the developer has zero control over.
It is the reason why that automatic conversion has been dropped in Python 3 - essentially; - raw_input in Python 2 has been renamed to input in Python 3; and there is no equivalent to the Python 2 input magic type conversion functionality.
Use raw_input() instead of input, check this page for more info
print("Is this your name? ", users_input) is not how you concatenate a literal string and a variable.
print("Is this your name? " + users_input) is probably what you are trying to do.
Python provides us with two inbuilt functions to read the input from the keyboard.
1 . raw_input ( prompt )
2 . input ( prompt )
raw_input ( ) : This function works in older version (like Python 2.x). This function takes exactly what is typed from the keyboard, convert it to string and then return it to the variable in which we want to store. For example –
g = raw_input("Enter your name : ")
print g
Output :
Enter your name : John Wick
John Wick
g is a variable which will get the string value, typed by user during the execution of program. Typing of data for the raw_input() function is terminated by enter key. We can use raw_input() to enter numeric data also. In that case we use typecasting.
input ( ) : This function first takes the input from the user and then evaluates the expression, which means Python automatically identifies whether user entered a string or a number or list. If the input provided is not correct then either syntax error or exception is raised by python. For example –
val = input("Enter your value: ")
print(val)
Output :
Enter your value: 345
345
When input() function executes program flow will be stopped until the user has given an input. The text or message display on the output screen to ask a user to enter input value is optional i.e. the prompt, will be printed on the screen is optional. A notable thing is that whatever you enter as input, input function convert it into a string.
I have a small file with a bunch of phrases on each line. I want the user to type a number and that number will print the selected line.
def printSpecLine(x):
print('started')
with open('c:/lab/save.txt') as f:
for i, line in enumerate(f, 1):
if i == x:
break
print (line)
print('done')
f.close()
s = int(input("Enter a number: "))
printSpecLine(s)
I've ran this with no errors, but the function isn't being called at all. Printing "started" (second line) didn't even occur. Am I missing a step here?
The only explanation for this is that you are not actually inputting to the prompt! There doesn't seem to be any other reason why at least the first print wouldn't be made.
Remember that input() is blocking, so until you enter your number and press enter, the program will be halted where it is (i.e. not call the function).
Apparently the ide i was using has a problem with raw input and integers being converted. Sublime Text 3 doesn't take python input very well. Thank you for your answer.
I'm a complete beginner in Python and I need some 'help' with something which is relatively simple (for a non-beginner).
What I'm trying to make is a quick 'program' which measures the length of a string which has been inputted. Maybe I have not looked hard enough, but I can't seem to find any specific information about this on the interwebs.
Ok, so here is what I have done so far:
print "Please enter a number or word and I will tell you the length of it."
NR = raw_input()
print len(NR)
*NR has no significant meaning, it's just a random variable name
Everything works as expected at first. For example, I enter the word "Hello" and it then replies with "5" or I enter the number 100 and it replies with "3" which is great, but when I attempt to enter another word I get this error:
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
hello
NameError: name 'hello' is not defined
However, when I enter another number (after I have already entered one), it just repeats the number which I have entered. For example, when I first enter the number "50" it replies with "2", but when I enter "50" a second time it just repeats the integer to me.
Note:
I think I understand the problem for the first part: It doesn't work more than once because the variable "NR" only counts as the first string which has been inputted. Even if I'm correct, I still don't know a solution to this.
Your program collects exactly one line of input and then finishes. After your program is finished, you are back in whatever environment you used to start your program. If that environment is a python shell, then you should expect that typing 50 will print a 50, and typing hello will print a no-such-variable-name error message.
To get your code to run more than once, put it in a while loop:
while True:
print "Please enter a number or word and I will tell you the length of it."
NR = raw_input()
print len(NR)
Note that raw_input() can print a prompt, so you don't need the print statement:
while True:
NR = raw_input("Please enter a number or word and I will tell you the length of it: ")
print len(NR)
This program fragment will run forever (or, at least until you interrupt it with Control-C).
If you'd like to be able to stop without interrupting the program, try this:
NR = None
while NR != '':
NR = raw_input("Please enter a number or word (or a blank line to exit): ")
print len(NR)
If you'd like to print the prompt once and then the use can enter many strings, try this:
print "Please enter a number or word and I will tell you the length of it."
while True:
NR = raw_input()
print len(NR)
This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 22 days ago.
I wrote a function in Python which prompts the user to give two numbers and adds them.
It also prompts the user to enter a city and prints it. For some reason, when I run it in a shell, I get "name is not defined" after I enter the city.
def func_add(num1, num2):
a = input("your city")
print a
return num1 + num2
If you're on Python 2, you need to use raw_input:
def func_add(num1, num2):
a = raw_input("your city")
print a
return num1 + num2
input causes whatever you type to be evaluated as a Python expression, so you end up with
a = whatever_you_typed
So if there isn't a variable named whatever_you_typed you'll get a NameError.
With raw_input it just saves whatever you type in a string, so you end up with
a = 'whatever_you_typed'
which points a at that string, which is what you want.
input()
executes (actually, evaluates) the expression like it was a code snippet, looking for an object with the name you typed, you should use
raw_input()
This is a security hazard, and since Python 3.x, input() behaves like raw_input(), which has been removed.
you want to use raw_input. input is like eval
You want to use raw_input() instead. input() expects Python, which then gets evaled.
You want raw_input, not input.
input(...)
input([prompt]) -> value
Equivalent to eval(raw_input(prompt)).
As opposed to...
raw_input(...)
raw_input([prompt]) -> string
Read a string from standard input. The trailing newline is stripped.
If the user hits EOF (Unix: Ctl-D, Windows: Ctl-Z+Return), raise EOFError.
On Unix, GNU readline is used if enabled. The prompt string, if given,
is printed without a trailing newline before reading.
In Python 2.x, input asks for a Python expression (like num1 + 2) which is then evaluated. You want raw_input which allows one to ask for arbitrary strings.
What is the raw_input function? Is it a user interface? When do we use it?
It presents a prompt to the user (the optional arg of raw_input([arg])), gets input from the user and returns the data input by the user in a string. See the docs for raw_input().
Example:
name = raw_input("What is your name? ")
print "Hello, %s." % name
This differs from input() in that the latter tries to interpret the input given by the user; it is usually best to avoid input() and to stick with raw_input() and custom parsing/conversion code.
Note: This is for Python 2.x
raw_input() was renamed to input() in Python 3.
From http://docs.python.org/dev/py3k/whatsnew/3.0.html
raw_input is a form of input that takes the argument in the form of a string whereas the input function takes the value depending upon your input.
Say, a=input(5) returns a as an integer with value 5 whereas
a=raw_input(5) returns a as a string of "5"
The "input" function converts the input you enter as if it were python code. "raw_input" doesn't convert the input and takes the input as it is given. Its advisable to use raw_input for everything.
Usage:
>>a = raw_input()
>>5
>>a
>>'5'
The raw_input() function reads a line from input (i.e. the user) and returns a string
Python v3.x as raw_input() was renamed to input()
PEP 3111: raw_input() was renamed to input(). That is, the new input() function reads a line from sys.stdin and returns it with the trailing newline stripped. It raises EOFError if the input is terminated prematurely. To get the old behavior of input(), use eval(input()).
Ref: Docs Python 3
Another example method, to mix the prompt using print, if you need to make your code simpler.
Format:-
x = raw_input () -- This will return the user input as a string
x= int(raw_input()) -- Gets the input number as a string from raw_input() and then converts it to an integer using int().
print '\nWhat\'s your name ?',
name = raw_input('--> ')
print '\nHow old are you, %s?' % name,
age = int(raw_input())
print '\nHow tall are you (in cms), %s?' % name,
height = int(raw_input())
print '\nHow much do you weigh (in kgs), %s?' % name,
weight = int(raw_input())
print '\nSo, %s is %d years old, %d cms tall and weighs %d kgs.\n' %(
name, age, height, weight)
If I let raw_input like that, no Josh or anything else.
It's a variable,I think,but I don't understand her roll :-(
The raw_input function prompts you for input and
returns that as a string. This certainly worked for
me. You don't need idle. Just open a "DOS prompt"
and run the program.
This is what it looked like for me:
C:\temp>type test.py
print "Halt!"
s = raw_input("Who Goes there? ")
print "You may pass,", s
C:\temp>python test.py
Halt!
Who Goes there? Magnus
You may pass, Magnus
I types my name and pressed [Enter] after the program
had printed "Who Goes there?"