This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 7 years ago.
I'm trying to make a program in Python 3 (IDLE) which lets the user input a quote and outputs it in upper case, lower case and in reverse. I've tried this:
quote = input("Enter your quote here: ")
print(quote.upper())
print(quote.lower())
print(quote.reverse())
...but all I get back when I test it is this error text:
Enter your quote here: You are always unique.
Traceback (most recent call last):
File "C:\Users\shobha m nair\Documents\Quote Conversion.py", line 2, in <module>
quote = input("Enter your quote here: ")
File "<string>", line 1
You are always unique.
^
SyntaxError: invalid syntax
You are probably using Python 2.x that's why you got the unexpected behaviour. The following code ran fine with Python 3.5:
quote = input("Enter your quote here: ")
print(quote.upper())
print(quote.lower())
print(quote[::-1])
There is no "reverse" method for strings.
This works for me:
quote = input("Enter your quote here: ")
print(quote.upper())
print(quote.lower())
print(quote[::-1])
The last one is the extended splice operator. AFAIK there's no reverse method in Python 3.
Related
This question already has answers here:
How can I limit the user input to only integers in Python
(7 answers)
Closed 9 months ago.
I'm trying to teach myself how to code in Python and this is my first time posting to Stack Overflow, so please excuse any improprieties in this post. But let's get right to it.
I'm trying to use the input command to return an integer. I've done my research, too, so below are my multiple attempts in Python 3.4 and the results that follow:
Attempt #1
guess_row = int(input("Guess Row: "))
I get back the following:
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'Guess Row: 2`
Attempt #2
guess_row = float(input("Guess Row: "))
I get back the following:
Traceback (most recent call last):
File "<input>", line 1, in <module>
ValueError: could not convert string to float: "Guess Row: 2""
Attempt #3
try:
guess_row=int(input("Guess Row: "))
except ValueError:
print("Not an integer")
Here, I get back the following:
Guess Row: 2
Not an integer
Although it returns something, I know this is wrong because, for one, the input returns as a string and it also returns the print command.
Point being, I've tried int, float, and try, and so far nothing has worked. Any suggestions? I just want to be able to input an integer and have it returned as one.
Your third attempt is correct - but what is happening to guess_row before/after this code? For example, consider the following:
a = "Hello"
try:
a = int(input("Enter a number: "))
except ValueError:
print("Not an integer value...")
print(str(a))
If you enter a valid number, the final line will print out the value you entered. If not, an exception will be raised (showing the error message in the except block) and a will remain unchanged, so the final line will print "Hello" instead.
You can refine this so that an invalid number will prompt the user to re-enter the value:
a = None
while a is None:
try:
a = int(input("Enter a number: "))
except ValueError:
print("Not an integer value...")
print(str(a))
To illustrate the comments, from 3.4.2 Idle Shell on Windows, python.org (PSF) installer
>>> n = int(input('Guess1: '))
Guess1: 2
>>> n2 = float(input('Guess2: '))
Guess2: 3.1
>>> n, n2
(2, 3.1)
What system are you using and how did you install Python?
However, I noticed something odd. The code works if I run it just by using the traditional run (i.e., the green button) that runs the entire code, rather than trying to execute individuals lines of code by pressing F2. Does anyone know why this may be the case?
This seems to be a problem in Eclipse, from the PyDev FAQ:
Why raw_input() / input() does not work correctly in PyDev?
The eclipse console is not an exact copy of a shell... one of the changes is that when you press in a shell, it may give you a \r, \n or \r\n as an end-line char, depending on your platform. Python does not expect this -- from the docs it says that it will remove the last \n (checked in version 2.4), but, in some platforms that will leave a \r there. This means that the raw_input() should usually be used as raw_input().replace('\r', ''), and input() should be changed for: eval(raw_input().replace('\r', '')).
Also see:
PyDev 3.7.1 in Eclipse 4 — input() prepends prompt string to input variable?,
Unable to provide user input in PyDev console on Eclipse with Jython.
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.
This question already has answers here:
input() error - NameError: name '...' is not defined
(15 answers)
Closed 4 years ago.
Using VScode + code runner extension
Once input() function receives a string like "qwe", program returns "NameError: name "qwe" is not defined"
If input receives a string of numbers like "123", everything goes well.
All files exist in right directory,and named/formatted pretty fine.
Example of function:
def maker():
fileVar = str(input())
fileVar = lineFixer(fileVar)
with open(fileVar+".csv","r") as workfile:
for line in workfile:
return(line)
lineFixer is a dumb function for some cases (has no influence on result):
def lineFixer(line):
line = line.strip('\n')
line = line.strip('\t')
line = line.replace('\n','')
line = line.replace('\t','')
return line
Without str(input()), it's rubbish.
The trouble that you are having is because you are using input() rather than raw_input().
Modify your code to read fileVar = raw_input()
The difference between these two is that input is trying to evaluate your input as code. That's why you get the error with XYZ not being defined, it thinks it is a variable. Also, with using raw_input, you no longer should need the casting into a string with str().
EDIT: I am assuming, since you have not specified this and from the error you are getting, that you are using Python2.X. In Python3, there should be only input(), working as raw_input().
This question already has answers here:
How do I escape curly-brace ({}) characters in a string while using .format (or an f-string)?
(23 answers)
Closed 7 years ago.
I am trying to write a piece of python code which will write a piece of CMake code ...
But when I get to the following phase:
def_desc = "blaa"
s = " FILE(WRITE ${CONFIG_H} \"/* {0} */\\n\")\n".format(def_desc)
then python yells at me:
Traceback (most recent call last):
File "/home/ferencd/tmp/blaa.py", line 2, in <module>
s = " FILE(WRITE ${CONFIG_H} \"/* {0} */\\n\")\n".format(def_desc)
KeyError: 'CONFIG_H'
[Finished in 0.0s with exit code 1]
I understood that somehow the interpreter thinks that {CONFIG_H} is supposed to mean a parameter from the parameter list of format ... but no, I'd really like to print out that into the output ... as it is.
How can I deal with this situation?
You need to escape brackets "}" if it uses not for format variable.
def_desc = "blaa"
s = " FILE(WRITE ${{CONFIG_H}} \"/* {0} */\\n\")\n".format(def_desc)
you need to use double braces:
s = " FILE(WRITE ${{CONFIG_H}} \"/* {0} */\\n\")\n".format(def_desc)
It is much easier, though, to use template library for stuff like this, like jinja or mako.
This question already has answers here:
Str.format() for Python 2.6 gives error where 2.7 does not
(2 answers)
Closed 8 years ago.
I am trying to use the ".format" with a string to insert values in a for loop. This is what I'm trying to do:
with open('test.txt', 'w') as fout:
for element in range (0, 5):
line1 = 'Icon_{}.NO = Icon_Generic;'.format(element)
fout.write(line1)
When I do this it chokes. My best guess is that it doesn't like the underscore directly beside the {} ("_{}"). Is this correct? Is there a good workaround for this?
I have used something like this and it works:
line1 = Icon_Generic.NO = Icon_%02d.NO;\n' % element
However, if I want to do a large multiline bunch of code using the "% element" doesn't work well.
Thanks in advance!
EDIT: As best I can tell I'm using Python 3.3
This is the error I get (using IDLE 3.3.2 shell):
>>> with open('p_text.txt', 'w') as fout:
for element in range(0, 5):
template = """if (!Icon_{0}.notFirstScan) {""".format(element)
fout.write(template)
fout.write('\n\n')
input('press enter to exit')
Traceback (most recent call last):
File "<pyshell#13>", line 3, in <module>
template = """if (!Icon_{0}.notFirstScan) {""".format(element)
ValueError: Single '{' encountered in format string
It's the final opening brace that's given you the problem, as indicated by the error message: a "Single '{' encountered". If you need literal curly braces in the formatted string, you must escape them by doubling up ('{{') wherever you mean them to be literals:
template = """if (!Icon_{0}.notFirstScan) {{""".format(element)
^ escape the literal '{'
Note that this is true for closing curly braces (}) as well!
>>> print('{{{0}}}'.format('text within literal braces'))
{text within literal braces}