Setting multi string variables while having them all apply the same (python) - python

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.

Related

Why don't string variables update when they are changed

Say we have some code like so :
placehold = "6"
string1 = "this is string one and %s" % placehold
print string1
placehold = "7"
print string1
When run, both of the print statements return as if placehold were ALWAYS 6. However, just before the second statement ran, placehold was changed to 7, so why does it not dynamically reflect in the string?
Also, would you be able to suggest a way to make the string return with 7?
Thank you
When you do:
string1 = "this is string one and %s" % placehold
You are creating a string string1 with %s replaced by the value of placehold On later changing the value of placehold it won't have any impact on string1 as string does not hold the dynamic property of variable. In order to reflect the string with changed value, you have to again re-assign the string.
Alternatively, you may use .format() as:
string1 = "this is string one and {}"
placeholder = 6
print string1.format(placeholder)
# prints: this is string one and 6
placeholder = 7
print string1.format(placeholder)
# prints: this is string one and 7
Because you have already assigned a value to that variable once you execute the statement.
It sounds like you'd rather need a function such as:
def f(placehold):
return "this is string one and %s" % placehold
Now you can print(f("7")) to achieve the desired functionality.
Strings are immutable and can't be changed, but what you're trying to do doesn't work with mutable objects either, so mutability (or lack of it) is something of a red herring here.
The real reason is that Python does not work like Excel. Objects do not remember all the operations that have been performed on them, and then re-do those operations when you change any of the information that went into them. For Python to work that way, the language would need to retain either every state that every object had ever been in, or all the operations that had ever been performed on them along with their parameters. Either would make your programs use a lot more memory and run much more slowly. On top of that, suppose you used string1 in another expression: that value, too, would need to be updated. In Python 3, print() is a function; should it be called again when the variable printed is changed?
There are languages that work like that, to some extent, but Python isn't one of them. Unless you explicitly arrange things otherwise (by writing and calling a function), Python evaluates an expression once and uses that exact result going forward.
In fact, what you want isn't even possible in Python. When you do string interpolation (the % operation), the code that does it sees only the value of what you're interpolating. It doesn't know that the "6" is coming from a variable called placehold. Therefore it couldn't change the string later even if it wanted to, because there's no way for it to know that there's any relationship between placehold and string1. (Also, consider that you needn't be interpolating a single variable: it could be an expression such as placehold + "0". So Python would need to remember the entire expression, not just the variable name, to re-evaluate it later.)
You can write your own string subclass to provide the specific behavior you want:
class UpdatingString(str):
def __str__(self):
return self % placehold
placehold = "6"
string1 = UpdatingString("this is string one and %s")
print(string1)
placehold = "7"
print(string1)
But this is fraught with scoping issues (basically, the class needs to be able to see placehold, which means that variable and the class need to be defined in the same function or in the global scope). Also, if you use this special string in an operation with another string, say concatenation, it will almost certainly cease being special. To fix these issues is possible, but... hairy. I don't recommend it.
string1 will use whatever value of placehold existed at the time string1 was declared. In your example, that value happens to be "6". To get string1 to "return with 7" you would need to reassign it (string1 = "this is string one and %s" % placehold) after changing the value of placehold.

Name not defined

I am writing a simple input and I keep getting an error. Fir example if I type in 'Eagle' it get name error eagle is not defined. Why is this?
print("The new word?")
newword = input()
Use raw_input instead if you don't want to evaluate the expression supplied. By default python evaluates whatever you supply to input as python expression, raising the name error.
newword = raw_input('the new word')
Otherwise, if you are meant on using input, then you need to enclose your entry string in quotes. Then python would consider it a string eliminating the NameError. Supply 'Eagle' instead of Eagle. Moreover, its better to supply the prompt string in input parameters i.e.
newword = input('The new word')
#supply 'Eagle' (in quotes)

Convert input to a string in Python

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.

Is it ever useful to use Python's input over raw_input?

I currently teach first year university students python, and I was surprised to learn that the seemingly innocuous input function, that some of my students had decided to use (and were confused by the odd behaviour), was hiding a call to eval behind it.
So my question is, why does the input function call eval, and what would this ever be useful for that it wouldn't be safer to do with raw_input? I understand that this has been changed in Python 3, but it seems like an unusual design decision in the first place.
Python 2.x input function documentation
Is it ever useful to use Python 2's input over raw_input?
No.
input() evaluates the code the user gives it. It puts the full power of Python in the hands of the user. With generator expressions/list comprehensions, __import__, and the if/else operators, literally anything Python can do can be achieved with a single expression. Malicious users can use input() to remove files (__import__('os').remove('precious_file')), monkeypatch the rest of the program (setattr(__import__('__main__'), 'function', lambda:42)), ... anything.
A normal user won't need to use all the advanced functionality. If you don't need expressions, use ast.literal_eval(raw_input()) – the literal_eval function is safe.
If you're writing for advanced users, give them a better way to input code. Plugins, user modules, etc. – something with the full Python syntax, not just the functionality.
If you're absolutely sure you know what you're doing, say eval(raw_input()). The eval screams "I'm dangerous!" to the trained eye. But, odds are you won't ever need this.
input() was one of the old design mistakes that Python 3 is solving.
Python Input function returns an object that's the result
of evaluating the expression.
raw_input function returns a string
name = "Arthur"
age = 45
first = raw_input("Please enter your age ")
second = input("Please enter your age again ")
# first will always contain a string
# second could contain any object and you can even
# type in a calculation and use "name" and "age" as
# you enter it at run time ...
print "You said you are",first
print "Then you said you are",second
examples of that running:
Example: 1
Prompt$ python yraw
Please enter your age 45
Please enter your age again 45
You said you are 45 Then you said you are 45
Example: 2
Prompt$ python yraw
Please enter your age 45 + 7
Please enter your age again 45 + 7
You said you are 45 + 7 Then you said you are 52
Prompt$
Q. why does the input function call eval?
A. Consider the scenario where user inputs an expression '45 + 7' in input, input will give correct result as compared to raw_input in python 2.x
input is pretty much only useful as a building block for an interactive python shell. You're certainly right that it's surprising it works the way it does, and is rather too purpose-specific to be a builtin - which I presume is why it got removed from Python 3.
raw_input is better, It always returns the input of the user without changes.
Conversely The input() function will try to convert things you enter as if they were Python code, and it has security problems so you should avoid it.
In real program don't use input(), Parse your input with something that handles the specific input format you're expecting, not by evaluating the input as Python code.

Learn python the hard way exercise 17 help, mistake in the book?

I'm liking this book so far, but I run into an issue with exercise 17. It won't run:
neil#neil-K52F:~/python$ python ex17.py ex17from.txt ex17to.txt
File "ex17.py", line 8
indata input.read()
^
SyntaxError: invalid syntax
The book makes me create a variable named input. Is this a legal variable name?
The code you posted simply puts one identifier next to another, without anything (but a space) in between. That's as meaningless and invalid in Python as it is in English. The code in the book has an assignment in there (i.e. indata = ...).
Normally you set a value for your input/raw_input(python 2.x)
x = input("Text Here")
You may also call a data type function on input method
x = float(input("Enter a Number")
x = int(input("Enter an Integer")
I use these all the time in Python 2.7 where raw_input() stores the value as a string.

Categories

Resources