I am a beginner to python and any coding at all for that matter, and I am having some trouble with some code I have written:
loop = 0
hellosentence = "You have selected the hello sentence"
questionsentence = "You have selected the question sentence"
usrinput = raw_input("Which test would you like to bring up? ")
print eval(usrinput)+sentence
end = raw_input("Press any key to quit...")
I am trying to run the code with this in mind.
Have multiple names with sentence at the end.
Request which “sentence” the user wants to bring up
Once the user has typed in the sentence, it evaluates what they have typed, say “hello”
and combines it with “sentence” to make the variable “hellosentence”, thus bringing up the variable’s string.
I’m 14 and really trying to learn how to understand this language, so if anyone knows what I could do to fix this error, I would be very grateful.
evalis going to take the string you give it and evaluate it. In this case it’s taking the input string that was typed in. Judging by the variables you’ve defined, you want to take the input and appendsentenceto it, so if they type ‘hello’ you’ll return the value ofhellosentence.The direct way to fix it is to give
evalthe proper input:That probably solves your problem, but it’s not a good way to do it.
evalis the wrong tool for the job; error recovery is going to be a problem, and if this were production code you’d be opening a big hole for someone who wanted to turn your program into a virus.The proper tool is a dictionary, with which you can use the input to look up the proper output.