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)
Related
I am new to coding. And I would like to know if there's a way for input function to not print newline character after the value is entered. Something like print function's argument end. Is there any way?
Well, you can't make input() trigger by anything besides 'Enter' hit (other way may be using sys.stdin and retrieving character one-by-one until you receive some stop marker, but it's difficult both for programmer and for user, I suppose). As a workaround I can the suggest the following: if you can know the length of line written before + length of user input, then you can use some system codes to move cursor back to the end of previous line, discarding the printed newline:
print("This is first line.")
prompt = "Enter second: "
ans = input(prompt)
print(f"\033[A\033[{len(prompt)+len(ans)}C And the third.")
\033[A moves cursor one line up and \033[<N>C moves cursor N symbols right. The example code produces the following output:
This is first line.
Enter second: USER INPUT HERE And the third.
Also note that the newline character is not printed by your program, it's entered by user.
name=input('Enter your name : ')
print('hello',name,end='')
I know about the end function which is abov
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 want a percentage sign to display after the users enters their number. Thanks
percent_tip = float(input(" Please Enter the percent of the tip:")("%"))
For example, before the user types anything they should see:
Please Enter the percent of the tip:
Once they begin typing the number 20 they should see:
Please Enter the percent of the tip: 20
After they hit <Enter> they should see:
Please Enter the percent of the tip: 20%
Please try this if this is what you are asking for:
import sys
import time
percent_tip = ""
while percent_tip in "123456789": # This part checks with the "if" statement, if its not a integer then it returns
percent_tip = input("Please Enter the % of the tip: ")
if percent_tip in "123456789":
print(str(percent_tip) + " %") # Prints the number and the percentage symbol
sys.exit() #stops the shell
else:
time.sleep(.100) #Shell waits then goes back in the while loop (unless its controlled by the "while" and "if")
Please do not try to harden yourself with a code that you don't know how to do it.
If you are on Windows, you will have the msvcrt module available. It provides, among others, the getwche() function, giving you the key pressed. This allows you to act on individual characters, and then print the % at the end (if you play around a bit more, you can probably also get it to appear while typing).
Example:
def get_chars():
chars = []
new = msvcrt.getwche()
while new != '\r': # returns \r on <RETURN> press
# you probably want to do some input validation here
chars.append(new)
new = msvcrt.getwche() # get the next one
print(end='%', flush=True)
return ''.join(chars) # this returns a str, you might want to directly get an int
Also, you will probably want to add input validation inside to make sure the input is only numbers.
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 running python 2.7 on 64-bit Windows 7.
Here is the code i'm executing:
import sys
while True:
print 'please enter a character:'
c = sys.stdin.read(1)
print 'you entered', str(c)
In the PyDev evironment in eclipse I get the following output for input a and then b.
please enter a character:
a
you entered a
please enter a character:
you entered
please enter a character:
you entered
please enter a character:
b
you entered b
please enter a character:
you entered
please enter a character:
you entered
please enter a character:
It correctly gets input once and then executes twice skipping user input.
Now when I run the same code in the python terminal for input a and b I get the following output:
enter char
a
you entered a
enter char
you entered
enter char
b
you entered b
enter char
you entered
enter char
This executes once getting user input and once skipping user input.
What would be causing this issue? How do I get Python to read one char at a time in an infinite loop?
Problem is probably due to flushing of stdin since the \n lingers on.
as an alternative, use raw_input
while True:
c = raw_input('please enter a character: ')
print 'you entered', c
For the flushing part, see this
sys.stdin is line-buffered by default i.e., your sys.stdin.read(1) won't return until there is full line in stdin buffer.
It means if you enter a character and hit Enter then after you get the first character with sys.stdin.read(1), there is a newline in the buffer (one or two characters: os.linesep) that are read immediately on the next loop iterations.
You could avoid hitting Enter by reading exactly one character at a time (msvcrt.getch()).