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

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.

Related

Setting multi string variables while having them all apply the same (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.

setting "if" to make sure variable is a number and not a letter/symbol

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

Python comparing input to line in file?

My name is Seix_Seix, and I have a doubt about a program in Python that I am building.
The thing is, that I'm doing a "riddle game" (silly, right?), to practise some basical Python skills. The intended flow of the program is that you give it a number from 1 to 5, and then it open a file with all the riddles stored in it, and it prints the one in the line of the number you gave.
Afterwards, it asks you for an input, in which you type the answer, and then (this is where all crumbled down) it compares your answer to the corresponding line on another file (where all the answers are).
Here is the code so you can give it a look *(It's in spanish since it's my mother language, but it also has a translation and explanation in the comments)
# -*- coding: cp1252 -*-
f = open ("C:\Users\Public\oo.txt", "r") #This is where all the riddles are stored, each one in a separate line
g = open ("C:\Users\Public\ee.txt", "r") #This is where the answers to the riddles are, each one in the same line as its riddle
ques=f.readlines()
ans=g.readlines()
print "¡Juguemos a las adivinanzas!" #"Lets play a riddle game!"
guess = int(raw_input("Escoge un número entre 1 y 5. O puedes tirar los dados(0) ")) #"Choose a number from 1 to 5, or you can roll the dice (0)" #This is the numerical input, in which you choose the riddle
if guess==0:
import random
raw_input(random.randrange(1, 5))
print (ques[guess-1]) #Here, it prints the line corresponding to the number you gave, minus 1 (because the first line is 0, the second one is 1 and so on)
a=input("¿Sabes qué es?") #"Do you know the answer?" #Here, you are supposed to type the answer to the riddle.
while True:
if a==(ans[guess-1]): #And here, it is supposed to compare the answer you gave with the corresponding line on the answer file (ee.txt).
print "ok" #If you are correct it congratulates you, and breaks the loop.
break
else:
print "no" #If you are wrong, it repeats its question over and over again
And so, I run the program. Everything is fine for a while until the moment when I have to input the answer; there, no matter what I put, even if it's right or wrong, it gives me the next error:
Traceback (most recent call last):
File "C:\Users\[User]\Desktop\lol.py", line 16, in <module>
a=input("¿Sabes qué es?") #"Do you know the answer?" #Here, you are supposed to type the answer to the riddle.
File "<string>", line 1, in <module>
NameError: name 'aguacate' is not defined #It is the correct answer BTW
I know this problem generates when it starts to compare the answers, and I also KNOW that it's probably because I wrote it wrong... Sooo, any advice on how to do it right?
Thanks in advance
You need to use raw_input() instead of input(), or Python will try to evaluate the entered string - and since aguacate is not an expression that Python knows, it throws the Exception you found.
Also, your "throw the dice" routine doesn't work (try entering 0 and see what happens). That should be
if guess == 0:
# import random should be at the start of the script
guess = random.randrange(1,6)
Some other comments about your code, as requested:
In general, it's quite OK. There are a few little things that you can optimize:
You're not closing the files you have opened. That's not a problem when you're only reading them, but it will cause problems once you start writing files. Better to get used to that quickly. The best way for this is to use a with statement block; that will automatically take care of closing your file, even if an exception occurs during the execution of your program:
with open(r"C:\Users\Public\oo.txt") as f, open(r"C:\Users\Public\ee.txt") as g:
ques = f.readlines()
ans = g.readlines()
Note that I used raw strings (important if you have backslashes in your strings). If you had named your file tt.txt, your version would have failed because it would have looked for a file named Public<tab>t.txt because the \t would have been interpreted as a tab character.
Also, take a moment to study PEP-8, the Python style guide. It will help you write more readable code.
Since you're using Python 2, you can drop the parentheses in print (ques[guess-1]) (or switch to Python 3, which I would recommend anyway because Unicode! Also, in Python 3, raw_input() has finally been renamed as input()).
Then, I think you need to strip off the trailing newline character from your answer strings, or they won't compare correctly (also, drop the unnecessary parentheses):
if a == ans[guess-1].rstrip("\n"):

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.

Weird program behaviour in Python

When running the following code, which is an easy problem, the Python interpreter works weirdly:
n = input()
for i in range(n):
testcase = raw_input()
#print i
print testcase[2:(int(testcase[0])+1)]+testcase[(int(testcase[0])+2):]
The problem consists in taking n strings and deleting a single character from them.
For example, given the string "4 PYTHON", the program should output "PYTON".
The code runs ok, but if I take out the comment mark, the statement print i makes the interpreter give an unexpected EOF while parsing. Any idea on why this happens?
EDIT: I'm working under Python 2.5, 32 bits in Windows.
Are you sure that the problem is the print i statement? The code works as
expected when I uncomment that statement and run it. However, if I forget to
enter a value for the first input() call, and just enter "4 PYTHON" right off
the bat, then I get:
"SyntaxError: unexpected EOF while parsing"
This happens because input() is not simply storing the text you enter, but also
running eval() on it. And "4 PYTHON" isn't valid python code.
I am yet another who has no trouble with or without the commented print statement. The input function on the first line is no problem as long as I give it something Python can evaluate. So the most likely explanation is that when you are getting that error, you have typed something that isn't a valid Python expression.
Do you always get that error? Can you post a transcript of your interactive session, complete with stack trace?
This worked for me too, give it a try...
n = raw_input()
n = int(n)
for i in range(n):
testcase = raw_input()
print i
print testcase[2:(int(testcase[0])+1)]+testcase[(int(testcase[0])+2):]
Note the n = int(n)
PS: You can continue to use n = input() on the first line; i prefer raw_input.

Categories

Resources