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.
Related
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)
I'm making a small github script for myself. I'm trying to have the call command with an argument then raw input as another argument. I have no idea how to even start.
file = raw_input("enter file name: ")
call(["command", "argument", "input here"])
How do i add the incorporate the raw input?
You can do this:
file_name = raw_input("enter file name: ")
call(["command", "argument", file_name])
Please don't use file as variable, it's a python type
And you don't need quotes, because file_name will be a string that you can put directly in your list.
You seem to confuse strings with string-literals. The first one is a sequence of characters (actually strings again in Python), whereas the latter is a way to write such a string within a program.
So
foo = "my string"
does not contain any actual quotes. E.g. the length is 9, the first character foo[0] is m and so forth.
raw_input returns a string-object, so if it's content should be passed on, you can just take the variable you assigned it to & and pass it as argument to create a list that in turn you pass to subprocess:
user_input = raw_input()
subprocess.check_call(["program", user_input])
For your actual use-case, don't be confused by having to use quotes in the shell for certain use-cases, as these serve a similar purpose there. The shell tokenizes input by spaces, so
$ command arg1 arg2 arg3
will be 3 arguments for command. But if you need one argument to contain spaces (e.g. certain filenames with spaces in them), you need to do
$ command "my spaceful argument"
However, the Python subprocess module (unless you use shell=True) does not suffer from this problem: there the arguments you pass as list will immediately be passed to the child-process without the need for quotes.
A simple solution is to just put your raw_input into your call:
call(["command", "argument", raw_input("enter file name: ")])
I'm new to programming and I need some help for a ai robot I just started on
Here is my code:
complements = "nice" and "happy" and "good" and "smart" and "wonderful"
var = "You are a "+ complements
input = raw_input
if var in input:
print "Thank you!"
else:
print "Wuhhhhh?"
If I type in something other than "nice" it goes to the else statement.
Or statements don't work
First, the and keyword does not do what you want. It is used as a binary comparison. Due to the inner workings of Python, your variable complements will receive the value "wonderful". You want to put these words in a list (see here). You will then be able to manipulate these words using concatenation as such (for example):
var = "You are a " + ", ".join(complements)
Furthermore, raw_input is a function. It must be called as such: raw_input(). Otherwise, you just create an alias of the function which you named input. You would still have to call it by appending () to it in order to receive the user input.
I also don't understand your if var in input: statement. var is a sentence you made, why would you search it in the user input? It would be clearer to do if raw_input() in complements, or something along the lines of it.
If you are beginning to learn Python, I would recommend you to use Python 3 instead of Python 2. raw_input() was renamed input() in Python 3.
Suppose we are on python3.3 and multi-platform (Linux and WIndow), if I do following:
>>> eval(input("enter a percent from 1-100"))
I get:
enter a percent from 1-100: (Terminal is Waiting for user prompt)
I want it to display:
enter a percent from 1-100: (waiting for user prompt) %
How do I show that % following the parenthesis?
If I understand your question, you want to be able to write a prompt that includes a % sign character, but places the user's cursor to the left of the sign, like this:
Enter a percent from 1-100: %
^ cursor is here
There's not a universal solution to this, since basic text-IO is usually oriented around input and output streams that don't have well defined interactions. There are some approaches that will work in some situations but not others, but I'm not sure of anything that will work everywhere (short of writing a GUI).
One suggestion I have is to include ASCII (and unicode) backspace characters '\b' (or '\x08') in your prompt. On some consoles this will move the cursor to the left one character per backspace. So, the prompt above could be generated by:
input("Enter a percent from 1-100: %\b\b\b\b\b")
This works when I run Python from a windows CMD.exe shell, but not when I run it within IDLE (the '\x08' characters are displayed as a box with a small circle taken out of the middle). It's a bit crude though, as it can't prevent the user from entering more characters than there are spaces before the % (which will be overwritten by the fifth character entered).
Another solution which may be a bit more robust (but not cross-platform, alas) is to use the curses module. I'm not knowledgeable enough about it to suggest code, but it should be possible to make it do what you want (and even control things like preventing the user from entering more than three characters, or moving the % sign to correctly align with values of any length).
One final thing: I strongly suggest that you don't use eval around your input call. If you expect (and require) an integer value, use int(input()). If you might get an integer, but could also get some other kind of value, use multiple lines to test what you got:
def get_val():
str_val = input()
try:
return int(str_val) # handle numbers like 1, 23232, etc.
except ValueError:
pass
try:
return float(str_val) # handles 23.5 and -3e-3 (but beware, also "nan" and "inf")
except ValueError:
pass
try:
return make_some_other_value(str_val) # whatever you want
except ValueError:
pass
return str_val # give up and return the string
Here's an alternative using the getch package. Instead of using input, we'll roll our own.
import string
import sys
try:
from msvcrt import getch
except ImportError:
from getch import getch
def char_valid(char):
"""Do whatever validation you need here."""
return char in string.ascii_letters or char in string.digits
def char_bkspace(char):
"""Matches backspace and delete."""
return char in ['\x08', '\x7f']
message_pre = 'enter a percent from 1-100'
message_post = '%'
user_input = ''
while True:
sys.stdout.write('\r{0} {1} {2}'.format(message_pre, user_input, message_post))
char = getch()
if char_bkspace(char):
user_input = user_input[:-1]
elif char_valid(char):
user_input += char
else:
break
print('\nyour message was', user_input)
This gets user input one character at a time in a while loop using getch. By using sys.stdout.write('\r...') we can avoid newlines and constantly overwrite the previous line.
This has the problem that if you backspace, multiple %'s will be visible because the new line is not entirely overwriting the previous line. This can be fixed by padding the string with spaces.
How do I create an "if" statement to make sure the input variable is a number and not a letter?
radius = input ('What is the radius of the circle? ')
#need if statement here following the input above in case user
#presses a wrong key
Thanks for your help.
Assuming you're using python2.x: I think a better way to do this is to get the input as raw_input. Then you know it's a string:
r = raw_input("enter radius:") #raw_input always returns a string
The python3.x equivalent of the above statement is:
r = input("enter radius:") #input on python3.x always returns a string
Now, construct a float from that (or try to):
try:
radius = float(r)
except ValueError:
print "bad input"
Some further notes on python version compatibility
In python2.x, input(...) is equivalent to eval(raw_input(...)) which means that you never know what you're going to get returned from it -- You could even get a SyntaxError raised inside input!
Warning about using input on python2.x
As a side note, My proposed procedure makes your program safe from all sorts of attacks. Consider how bad a day it would be if a user put in:
__import__('os').remove('some/important/file')
instead of a number when prompted! If you're evaling that previous statement by using input on python2.x, or by using eval explicitly, you've just had some/important/file deleted. Oops.
Try this:
if isinstance(radius, (int, float)):
#do stuff
else:
raise TypeError #or whatever you wanna do