Weird program behaviour in Python - 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.

Related

Python error in a colon.. cant find an answer

As part of a piece of python work I have to ask for a first name and surname, then repeat it three times if it is correct. When I try it Python puts a syntax error on the colon. What do I need to do to correct it?
Basically whats going on
I've already tried removing the colon, bringing the if line down to one equals, and looking for bracket errors, but I cant find anything.
The colon should be at the end,
if input == yes:
However I cannot see how this can work? Is that the full code? If so, what is the yes variable?
If it was intended to be a string, the line should be,
if input == "yes":
The "" tells Python that it is a string (a word).
A link to Python syntax: https://en.wikipedia.org/wiki/Python_syntax_and_semantics

Invalid syntax, Unexpected EOF

What is wrong with my code?
It says there is an invalid syntax and highlighting the colon?
BTW, I'm doing computing GCSE and this is part of the coursework prep.
I want it to take a letter to repeat and then repeat it an inputted number of times.
letter=input("Please enter a letter to be repeated: ")
number=int(input("Please enter the number of times you want it repeated: ")
for a in range(0,number):
print(+letter)
Remember that when you're debugging, compilers and interpreters will report where an error was first detected, not necessarily where the error actually is. You're missing a closing parentheses on this line:
number=int(input("Please enter the number of times you want it repeated: ")
Add another ) to the end of that line. The interpreter is seeing the opening parentheses for the int function call, then is happily looking through the rest of the file to find its match. When it reaches the end of the file without the parentheses being balanced, it gives up and throws the exception.
As Josh points out, +letteris also invalid syntax. I'm not sure what you were trying to achieve with it so I can't recommend a specific fix, but it needs to go.
You are missing your closing parenthesis for the int() function call. Also you need to remove the + from print(+letter)

Python for-loop to print a triangle

This code was given to me by my professor, and prints a triangle of *s:
def printTriangle(size):
for i in range(0,size):
for j in range(0,i+1):
print "*",
print
This is my failed attempt to code an inverse of the triangle:
def printInvertedTriangle(size):
for i in range(size,0):
for j in range(size,i-1):
print "*",
print
I have tried this many different ways, but this is how I think it should be, and it only gives me blank space before the program ends.
My understanding is that this is how his works:
for i in range(start,finish):
for j in range(start,step):
print "*",
print
Can anyone explain to me why the first block my professor gave me works, and why mine prints blank space? I thought I understood his loop; so what was I doing wrong in mine? What should it look like? I want something based off of his for loop. His goes against what I've been reading in Python tutorials in that he has only (start,step), whereas the tutorials say it goes (start,stop,step).
I got started in programming with JS, and thought that some simple Python loops would be a walk in the park...
Thanks a lot for any and all help!! #noob
def printInvertedTriangle(size):
**for i in range(size,0):**
for j in range(size,i-1):
print "*",
print
Your error of having white space shown I believe is as a result of line two. Since this index is counting how many times to step through lines, this needs to still run through x amount of iterations by ranging from (0,size).
In the second for loop, as the lines increase from 1 to 2 to 3 ...etc use variable i and the max (size) to build the reverse triangle.
Try this:
def printReverseTriangle(size):
for i in range(0,size):
for j in range(i,size):
print "*",
print
The reason your script outputs nothing is your range doesn't work.
As we can see in the interpreter:
>>> range(10,0)
[]
It outputs an empty list.
One way to accomplish what you want is to use the reversed() builtin to reverse the list.
for i in reversed(range(0,size)):
for j in range(0,i+1):
To help you in the future, try to use the interpreter more to check the output of things.
You can open any python module in interactive mode, which runs the program and then lets you use the interpreter afterward.
python -i script.py
Here is a program that I had to make for my weekend assignment. It gives a pretty decent reverse triangle as well.
def reverse_triangle(n):
r=n/2+1
for i in range(r-1,0,-1):
print" "*(r-i)," *"*i
def main():
n=input('Enter the size=')
reverse_triangle(n)
main()
Note: In this bit " *"*i I put the space before the asterisk because my PC's version of Python 2.7 does not print the pattern symmetrically if the space is not added. You can try it with the space or without it and check if it works for you.

syntax error with .format() (Python 3.2.3)

So I am trying to write a program that writes a word, fills 20 spaces with markup(< or >), then writes that same word backwards. It also takes user input.
Can anyone tell me what im doing wrong
while test2 == 1 :
test = input("Enter a word to format. Entering QUIT will exit the program:")
if test == ("quit"):
print("You have quit the program.")
break
else:
print("{0:*<20}{1:*>20})".format(
"test")(["test"::-1])
Syntactically you have a " in the wrong place in your last print statement.
print("{0:*<20}{1:*>20}").format("test")(["test"::-1])
^
You also some other syntax errors with your format() arguments, this will work for the literal string "test" but you'll need to replace it with a variable to use it with actual user input:
print("{0:*<20}{1:*>20}").format("test","test"[::-1])
Your last line has errors, try the follwing to get 20 spaces between the words
In [1]: s = "test"
In [2]: print('{0:<20}{1}'.format(s,s[::-1]))
test tset
You can also use print('{0}{1}{2}'.format(s," "*20,s[::-1])) which is subjectively cleaner.

Prevent python from printing newline

I have this code in Python
inputted = input("Enter in something: ")
print("Input is {0}, including the return".format(inputted))
that outputs
Enter in something: something
Input is something
, including the return
I am not sure what is happening; if I use variables that don't depend on user input, I do not get the newline after formatting with the variable. I suspect Python might be taking in the newline as input when I hit return.
How can I make it so that the input does not include any newlines so that I may compare it to other strings/characters? (e.g. something == 'a')
You are correct - a newline is included in inputted. To remove it, you can just call strip("\r\n") to remove the newline from the end:
print("Input is {0}, including the return".format(inputted.strip("\r\n")))
This won't cause any issues if inputted does not have a newline at the end, but will remove any that are there, so you can use this whether inputted is user input or not.
If you don't want any newlines in the text at all, you can use inputted.replace("\r\n", "") to remove all newlines.
Your problem is actually Eclipse. Assuming that you use PyDev, I was able to reproduce the problem. When entering something in the Eclipse console, the problem occurs as described in your question. But when directly executing the very same script with the Python 3.1.1 interpreter, inputted does not include a newline character.
I investigated the Python source code and found out input() uses GNU readline if stdin is interactive (i.e. a TTY or prompt, however you want to call it), but falls back to the .readline() method of the stdin object if necessary. Then, if the result of readline ends with \n, that character is removed. Note: No CR-LF or LF-CR handling here (in the fallback case)!
So I wrote this little script to see what actually happens:
import sys
from io import StringIO
for stdin in [sys.stdin, StringIO("test\r\ntest\r\n")]:
sys.stdin = stdin
print("readline returns this: " + repr(sys.stdin.readline()))
inputted = input("Enter in something: ")
print("inputted: " + repr(inputted))
print("inputted is printed like this: --> {0} <--".format(inputted))
It first executes the code with the normal stdin (console or Eclipse console) and then with a prepared stdin containing the text test\r\ntest\r\n.
Try and run the script in Eclipse - you must enter a string twice. The conclusion: Pressing Enter in the Eclipse console will produce CR-LF ("\r\n"). Printing "\r" in the Eclipse console will jump to the next line.
On the other side, running it in the Windows console will produce the expected output: input() returns a string without a newline at the end because (I guess) GNU readline is used. With the prepared stdin StringIO("test\r\n"), the input() result is "test\r" as in Eclipse (although not printed as newline).
Hope this all makes sense... but what I still don't know is if that is expected behavior of Eclipse.
If you only want to stript the last line endings, you could use rstrip.
inputted.rstrip ("\r\n")
inputted = inputted.strip()
Edit: As noted, this will kill all whitespace at the start and end. A way to get rid of only the trailing newline is:
import re
inputted = re.sub("[\n\r]+$", "", inputted)

Categories

Resources