I am currently writing a program that is supposed to return certain values when it completes, but the system that tests it is a black box (don't know how it tests the program), and even though I think it would work if I ran the program by itself, the automated tester always raises an end of file error when it encounters the first input prompt. This the part that is in the main portion of the python code (kind of the first thing that runs).
y=list(input("Enter numbers separated by commas and spaces"))
x=list(input("Do the same as above but for other list"))
The tester raises the end of file error on the first prompt. Any idea what may cause that?
It is quite possible that the tester is not supplying any input at all. In which case, you (I) have to supply the values in the program itself, not as input but as defined values.
Related
When I am importing a function from a module into a script of another file and then run it, the function starts all over after it has finished although it is supposed to run only once.
If I, however, only run the cell with the imported function then the function sometimes only runs once which is confusing because I have deactivated everything else in the script so it should not make a difference, should it? But sometimes it also runs twice which is even more confusing because I have not changed anything in the meantime (at least not that I would know).
One difference is that when I run the entire script the console says
Reloaded modules: mytestmodule
after the script has been executed while when I only run the cell this does not show up. I do not know if this matters though.
Either way, here is the function (from the file mytestmodule.py):
def equation():
print("Hi! Please enter your name.")
name=input()
print("Hello "+name+"! Please enter an integer that is bigger than 1 but smaller than 10.")
answertrue="That is correct!"
answerfalse="That integer is not correct. Please try again."
answernointeger="That is not an integer. Please try again."
biggersmaller=True
while biggersmaller:
task=input()
try:
if int(task)>1 and int(task)<10:
return(print(answertrue))
break
else:
print(answerfalse)
except ValueError:
print(answernointeger)
equation()
And here is the script of the import in the other file:
import mytestmodule
mytestmodule.equation()
This is because inside your mytestmodule.py you are calling the equation function already.
Either:
Remove the call of equation from mytestmodule.py
or
Don't call the function after importing it
You will see in the screenshot that pressing enter after pasting a multiline code doesnt run it but merely send each time a "...".
How can I run this multiline pasted code?
someone asked here, but did not get (the right) answer;
Did not work:
Backspace
Use the arrow key to move the cursor, then use the delete key
Escape
F2
Pressing enter twice when inside the Python interpreter executes a block of code, but you have an unmatched open parenthesis on the last line, so you haven't completed defining the block of code. Also, I'm not sure what dic is in the last line, because you haven't included its definition, so you may need to fix that as well.
Running
a=[1,2]
for x in a:
print(x)
actually works (pressing 2 enters worked as expected). So I made a mistake in the code above. I aplogise, I should have checked that before.
I don't delete the question since the one on google can be confusing (the guy did not mentioned it was his mistake, so I though there was a trick to be found. The trick is to check the code).
you could use IPython link which simplifies the process, better yet you have access to every command line as if executed inside the shell.
The other alternative is to encapsulate this inside a function
I know this answer is a bit late, but someone will need the information sometime:
When you make a new line, i.e. title.quote.... you need to press the tab to create an indent, then it will work. Without indenting, you get the "expected an indent" error message.
Okay, so let me just say beforehand: I am new to Python. I was just experimenting with IDLE and then I had this weird "crash". I put "crash" inside speech marks because I'm not sure if it qualifies as a crash, as rather than the program just crashing the way a normal program would in Windows, it still runs, but whenever I press enter and try and get it to accept new text it doesn't do anything. E.g. if you try and type "print('a')" and then hit enter it just goes to the next line (and doesn't print 'a'). I tried to make a simple function which converted an integer to a string where each character in the string was either a '1' or a '0', forming the binary number representing said (unsigned) integer.
>>> def int_to_str(int_in):
str_out=''
bit_val=1<<int_in.bit_length()
while(int_in>0):
if(int_in>bit_val):
str_out+='1'
int_in-=bit_val
else:
str_out+='0'
bit_val>>=1
return str_out
>>> print('a')
print('c')
Basically, it becomes completely unresponsive to my input, and allows me to edit/change "print('a')" even though I shouldn't be able to if it had actually "accepted" my input. Why is this? What have I done wrong/messed up?
Also, I made sure it isn't something else I was previously messing around with by closing the shell and opening it again and only putting in said code for the "int_to_string" function, and I haven't changed any settings or imported any modules before hand or anything like that (in case it matters).
EDIT: I tried reinstalling, and that helped a bit in that I can now do other stuff fine, but the moment I try to use the "str_to_int()" function, it has this same weird behaviour of not accepting/interpreting any more user input.
Your while loop never terminates, you need to re-arrange your logic. Printing variables can be an effective debugging tool - like this:
>>> def int_to_str(int_in):
str_out=''
bit_val=1<<int_in.bit_length()
while(int_in>0):
print(int_in, bit_val)
if(int_in>bit_val):
str_out+='1'
int_in-=bit_val
else:
str_out+='0'
bit_val>>=1
return str_out
If your program seems to be going on too long you can stop it with ctrl-c.
I have read that the interpreter runs the code line by line and reports the error if any at the same time and stops the further execution.
So in python, consider the file ex1.py,
print "Hello world"
12variable = 'bye'
print 12variable
Now according to the working of interpreter, the interpreter would run the first line i.e. it prints hello world first and then show the syntax error in the next line (line-by-line working). Hence the expected output is:
Hello world
12variable = 'bye'
^
SyntaxError: invalid syntax
But the actual output is -
12variable = 'bye'
^
SyntaxError: invalid syntax
Why it is not printing Hello World at the first?
It depends on how you run the Python interpréter. If you give it a full source file, it will first parse the whole file and convert it to bytecode before execution any instruction. But if you feed it line by line, it will parse and execute the code bloc by bloc:
python script.py : parse full file
python < script.py : parse and execute by bloc
The latter is typically the way you use it interactively or through a GUI shell like idle.
It's a myth that Python is a fully interpreted language. When CPython runs a script the source code is parsed (this is where it will catch syntax errors), and compiled into bytecode (sometimes these are cached in your directory as .pyc files) before anything is executed. In this regard Python is not all that fundamentally different than Java or C# other than that it doesn't spend much time doing any optimizations, and I believe the bytecode is interpreted one instruction at a time, instead of being JITed to machine code (unless you're using something like PyPy).
Because your understanding of the interpreter is faulty. While it is possible for the behaviour you are describing to occur for a subset of errors it is not the common case for many (most?) errors.
If the interpreter can construct what it thinks is a valid program but there is an error at run time then what you are describing will happen.
Since the case you are pointing at is a syntax error that prevents a valid program being constructed the behaviour is as you see it.
I understand it that way:
Python runs the code line by line after it's in byte code state.
The difference between this thing and compilation (in other languages like C++) is that you have to do this process of interpretation each time you run the script.
Python interpreter interprets the code each time you run the script.
In C++ you compile the program and you can execute it without having to compile it again unless you want to change the system.
Step 1:
The interpreter reads a python code or instruction. Then it verifies that the instruction is well-formatted, i.e. it checks the syntax of each line. If it encounters an error, it immediately halts the translation and shows an error message.
Step 2:
If there is no error, i.e. if the python instruction or code is well-formatted then the interpreter translates it into its equivalent form in an intermediate language called “Byte code”.Thus, after the successful execution of Python script or code, it is completely translated into Byte code.
Step 3:
Byte code is sent to the Python Virtual Machine(PVM).Here again, the byte code is executed on PVM. If an error occurs during this execution then the execution is halted with an error message.
So in your case, the "invalid syntax" error is thrown because of step1. But, the actual print function gets executed at step 3. step 3 comes only after step 1 right... I think got it now.
I was writing a little program that takes a list and generates a menu out of it in curses (straight up, standard library or whatever, batteries included python's curses) when I noticed the strangest problem (if you'd like, a heavily commented copy of the entire program is below). Simply put, when accepting the results of an os.listdir generated list, curses crashes with an addstr ERR, BUT, if I feed it a hardcoded list, it works fine. This, of course, makes absolutely no sense, right? A list is a list is a list and a list by any other name should still be a list, right?
To make things even more complicated, I sent the code to a friend of mine who works mainly in python2.6 (mine was originally written to work in python3.1). He uncommented the broken_input() call (which feeds the program the os.listdir generated information) and said that it worked fine for him. I have both python 2.6 and 3.1 installed, so I changed my shebang to make the program run in 2.6, and (with the broken_input() uncommented) for me, it still throws the addstr ERR (yet runs fine with the hardcoded input... which is, of course, btw, entirely useless apart from proof of concept).
Thus, my question is this: is there something broken in my python installation (I'm running Ubuntu lucid, with python2.6.5 and 3.1 installed), and, if so, how do I fix it so I can get curses to execute this code properly. And, if it's not my python installation, how can I get the same functionality out of curses (i.e.: paint a menu from a list containing an arbitrary number of items, numbering them so that the user can make a selection based on the item number).
#!/usr/bin/env python3.1
"""curses_mp3eater.py: a curses-based implementation of my mp3eater program;
diplays the contents of cwd, allows user to make a selection. But I'm having
problems getting it to iterate over a list.
v0.1 03.14.11
by skookie sprite
address#gmail.com
"""
import curses, curses.wrapper, os, sys
def working_input():
"""the following is demo code to demonstrate my problem... main will accept the following,
but won't accept the product of a directorylist for reasons that I can't figure out."""
dircontents=['this','is','a','list','','and','it','will','iterate','fine','in','the','(main) function.']
return dircontents
def broken_input():
"""this is the code that I NEED to have work... but for reasons beyond me will not iterate in
the main function. It's a simple list of the contents of the CWD."""
cwd=os.getcwd()
dircontents=[]
for item in os.listdir(cwd):
dircontents += [item]
return dircontents
def main(stdscr):
"""This is the program. Designed to take a list of stuff and display it. If I can solve
that hurdle, I'll add selection mechanisms, and break it across screens - amongst other
things. But, currently, it can only accept the demo code. Uncomment one or the other to
see what I mean."""
#broken_input returns an addstr() ERR, but I don't see the difference between working_input
#and broken_input as they are both just lists.
#working_input() is demo code that illustrates my problem
stuffin=working_input()
#stuffin=broken_input()
#the rest of this stuff works. The problem is with the input. Why?
linenumber=int()
linenumber=6
itemnumber=int()
itemnumber=1
stdscr.clear()
stdscr.border(0)
for item in stuffin:
stdscr.addstr(linenumber, 10, '%s - %s' % (itemnumber, item), curses.A_NORMAL)
linenumber += 1
itemnumber += 1
curses.doupdate()
stdscr.getch()
if __name__ == '__main__':
curses.wrapper(main)
You're stuffing too much onto the screen and thus passing an out-of-bounds line number to addstr. If you make an empty directory to run the program in (or enlarge your terminal window), it works.
To fix this, check the number of lines in the window before the output loop in main.
use screen.scrollok(1) after addstr to allow the text to scroll.
The problem is explained in the addch manual page:
The addch, waddch, mvaddch and mvwaddch routines put the character ch
into the given window at its current window position, which is then
advanced. They are analogous to putchar(3) in stdio(3). If the
advance is at the right margin:
The cursor automatically wraps to the beginning of the next line.
At the bottom of the current scrolling region, and if scrollok is
enabled, the scrolling region is scrolled up one line.
If scrollok is not enabled, writing a character at the lower right
margin succeeds. However, an error is returned because it is not
possible to wrap to a new line
The given program neither catches an error from the lower right margin (probably should say "corner"), nor calls scrollok to allow the data to scroll up. In the latter case, you will lose information which is scrolled up, while handling the exception would allow you to prompt after a screen's worth of data is displayed, and then either quit or display more data.