This question already has an answer here:
Why doesn't the result from sys.stdin.readline() compare equal when I expect it to?
(1 answer)
Closed 6 years ago.
Im new to this so Im sorry if this isn't the best way to ask the question...
here is the code -
import sys
print("What is ur name?")
name = sys.stdin.readline()
answer = "jack"
if name is answer :
print("ur awesome")
exit();
right now when I run it in cmd I don't get anything printed even though
I input - jack? thank you in advance
Firstly, replace is with ==. is checks whether the two underlying strings are the same entity (in memory) whereas == just wants to check if they have the same value.
Because the source of "jack" is coming from two sources (one from the user, another hard-coded by you) they are two seperate objects.
As #dawg mentioned you also have to use the .strip() to get rid of the newline when using sys.stdin.readline() for input. The best way to read input is to use the input() method in python3, or raw_input() in python2.
name = input('What is your name?\n')
Use == for string comparison. Also, readline() will include the newline at the end of the string. You can strip it with e.g.
name = name.strip()
Alternatively, you can use raw_input() (input() in python 3) instead of readline(), as it will not include the newline to begin with.
name = raw_input("What is your name?\n")
It's helpful to be able to print a string to see if it has any extra whitespace, e.g.
print("name: [%s]\n" % name)
Related
This question already has answers here:
Safe way to parse user-supplied mathematical formula in Python
(3 answers)
Closed 1 year ago.
So I wanna make a code that solves simple problems (For example 3+4=? or 2/4+5=?) that are typed in by the user with input() but it treats the returned value as a string and it doesn't wanna work.
Basicly I wanna do this correctly:
print('Enter a problem:')
equals = input()
print('The answer is {}.'.format(equals))
Thanks in advance and have a nice day!
Well input() always returns a string. There is no way around that. However, you can't just "cast" it to be an equation. However, if you know the operations that will be inputted you can do some parsing. For example, this is how you might handle addition.
print('Enter a problem:')
equation = input() # user inputs 3+4=?
equalsIndex = equation.index('=')
# Reads the equation up to the equals symbol and splits the equation into the two numbers being added.
nums = equation[:equalsIndex].split('+')
nums[0] = int(nums[0])
nums[1] = int(nums[0])
print('The answer is {}.'.format(nums[0] + nums[1]))
In general, you would have to parse for the different operations.
You can't transform this from "string" to "code". I think that exist a lot of libraries that can help you (example).
Other option is that you write your own code to do that.
Main idea of that is to get numbers and operators from string to variables. You can use "if" to choosing operations.
Example.
You have a input string in format "a+b" or "a-b", where a,b - integers from 1 to 9. You can take first and last symbol of that string. Convert it into integer and save into variables. Next step is check if second symbol of the string is "+" than you can add this two variables. Otherwise you can sub this variables. That's it.
Obviously if you want some powerful application you need more work, but it only an idea.
To my experience, I have no idea on how to solve problem directly inside the input(). The only way to solve your issue (I think) is overide the input() method. You can Google 'overriding method python' and you'll find the syntax.
Hope you'll figure out this problem. Have a nice day :)
Use exec as follows.
equation = input("Input your equation")
exec("output = {}".format(equation))
print(output)
Here is an example (Note. "=" should not be included in the equation)
Input your equation: 2+4
6
This question already has answers here:
How do I put a variable’s value inside a string (interpolate it into the string)?
(9 answers)
Closed 4 years ago.
in C# it was Possible to Use a Code Like This:
Console.WriteLine ("hello{0}" ,Hello);
i Want to do Same Thing in Python,i Want to Call Variable With {0} and {1} Way.
How Can I Do This ?
You can use format for the same
"hello {0}".format("Hello")
You can use the str.format function:
"Hello {0} {1}".format(firstname, lastname)
You can also leave the space in between the {} blank to automatically pick the next argument:
>>> "{}, {}".format("one", "two")
one, two
You can also use a prettier "f string" syntax since python 3.6:
f"Hello{Hello}"
The variable inside the {} will be looked up and placed inside the code.
You can use place holders to format strings in Python. So in this example, if you want to use a place holder such as {0}, you have to use a method called .format in Python. Below is a mini example.
name = input('Please enter your name: ')
with open('random_sample.txt', 'w') as sample:
sample.write('Hello {0}'.format(name))
As you can see, I ask the user for a name and then store that name in a variable. In my string that I write to a txt file, I use the place holder, and outside of the string I use the .format method. The argument that you enter will be the variable that you want to use.
if you want to add another variable {1} you would do this:
sample.write('Hello {0}. You want a {1}').format(name, other_variable))
so whenever you use a placeholder like this in Python, use the .format() method. You will have to do additional research on it because this is just a mini example.
I'm new to python so excuse any poor code you may find
The problem I'm having is that I'm trying to compare two strings, one from a file and one from user input, to see if they match. However, when comparing what seem to me identical strings, the if statement returns false. I have used the str() function to turn both of the values into strings, but it still doesn't want to play ball.
For reference, the line of the file is two strings, separated by a comma, and the 'question' part is before the comma and the 'answer' after it. At present, both the strings are test strings, and so have the values of 'Question' and 'Answer'
import linecache
def askQuestion(question, answer):
choice = input(question)
str(choice)
if choice == answer:
print("Correct")
else:
print("Bad luck")
file = "C://questions.txt"
text = linecache.getline(file, 1)
question = text.split(",", 1)[0]
answer = text.split(",", 1)[-1]
str(answer)
askQuestion(question, answer)
I am typing in exactly what the file has i.e. capital letters in the right place, for note.
I'm sure the answer obvious, but I'm at a loss, so any help would be kindly appreciated.
Thanks!
text = linecache.getline(file, 1)
question = text.split(",", 1)[0]
answer = text.split(",", 1)[-1]
this is more commonly written
text = linecache.getline(file, 1)
question, answer = text.split(",", 1)
The results will be a string. There is no interpretation happening. Also, you need to store the result of str().
my_string = str(number)
By calling str() but not saving it the result is being lost. Not important here, but something to keep in mind.
As Alex mentions in the comment above you are missing the call to strip to remove the newline. How do I know? I tried it in the interpreter.
$ python
>>> import linecache
>>> line = linecache.getline("tmpfile", 1)
>>> line
'* Contact Numbers\n'
See that '\n' there? That is your problem.
Another way would have been to invoke pdb the Python Debugger. Just add
import pdb; pdb.set_trace()
where you want to stop the execution of a Python script.
Good luck.
I want to wrap the colour input in quotes within python:
def main():
colour = input("please enter a colour")
So if I enter red into the input box it automatically makes it "red"
I'm not sure how to do this, would it be something along the lines of:
def main():
colour = """ + input("please enter a colour") + """
Kind regards
The issue is that this doesn't pass syntactically, as Python thinks the second " is the end of the string (the syntax highlighting in your post shows how it's being interpreted). The nicest to read solution is to use single quotes for the string: '"'.
Alternatively, you can escape characters (if you wish to, for example, use both types of quote in a string) with a backslash: "\""
A nice way of doing this kind of insertion of a value, rather than many concatenations of strings, is to use str.format:
colour = '"{}"'.format(input("please enter a colour"))
This can do a lot of things, but here, we are simply using it to insert the value we pass in where we put {}. (Note that pre-2.7, you will need to give the number of the argument to insert e.g: {0} in this case. Past that version, if you don't give one, Python will just use the next value).
Do note that in Python 2.x, you will want raw_input() rather than input() as in 2.x, the latter evaluates the input as Python, which could lead to bad things. In 3.x, the behaviour was fixed so that input() behaves as raw_input() did in 2.x.
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.