I was debugging some code that had some never-ending loop issues, and I sometimes couldn't figure out how to make informative print statements to help identify which loop was broken.    An example case is:  def fake_function():     print 'I am about to enter a broken loop.'      while True:     #  Doesn't matter what I'm doing here.         _ = None   When I then call fake_function, I don't get any output until I halt it.  A slightly larger example that might show why I wanted this looks like:  def another_fake_function():      #  This loop is fine and not broken.       print 'I am entering a loop that might be broken.'         leave_loop = False     while not leave_loop:         #  Do a thing.         leave_loop = True      #  This loop actually is broken.     print 'I am about to enter a different loop that might be broken.'     while True:         #  Doesn't matter what I'm doing here.         _ = None   So, is there any way to really force python to print something immediately?    Thanks!
9533
How do I force Python's print function to output to the screen?
80463
One thing that annoys me when debugging programs in Visual Studio (2005 in my case) is that when I use "step over" (by pressing F10) to execute to the next line of code, I often end up reaching that particular line of code in a totally different thread than the one I was looking at. This means that all the context of what I was doing was lost.  How do I work around this?  If this is possible to do in later versions of Visual Studio, I'd like to hear about it as well.  Setting a breakpoint on the next line of code which has a conditional to only break for this thread is not the answer I'm looking for since it is way too much work to be useful for me :)
75996
In the spirit of questions like :  Which style do you use for an infinite loop, and why?   while (true) { } do { } while (true); for (;;) { } label: ... goto label;
42746
Should I use exit() or just return statements in main()? Personally I favor the return statements because I feel it's like reading any other function and the flow control when I'm reading the code is smooth (in my opinion). And even if I want to refactor the main() function, having return seems like a better choice than exit().  Does exit() do anything special that return doesn't?
24951
I wrote a function in C that converts a string to an integer and returns the integer. When I call the function I also want it to let me know if the string is not a valid number. In the past I returned -1 when this error occurred, because I didn't need to convert strings to negative numbers. But now I want it to convert strings to negative numbers, so what is the best way to report the error?  In case I wasn't clear about this: I don't want this function to report the error to the user, I want it to report the error to the code that called the function. ("Report" might be the wrong word to use...)  Here's the code:  s32 intval(const char *string) {     bool negative = false;     u32 current_char = 0;      if (string[0] == '-') {         negative = true;         current_char = 1;     }      s32 num = 0;     while (string[current_char]) {         if (string[current_char] &lt; '0' || string[current_char] &gt; '9') {             // Return an error here.. but how?         }          num *= 10;         num += string[current_char] - '0';         current_char++;     }      if (negative) {         num = -num;     }      return num; }
9285
When trying to write the stdout from a Python script to a text file (python script.py &gt; log), the text file is created when the command is started, but the actual content isn't written until the Python script finishes. For example:  script.py:  import time for i in range(10):     print('bla')     time.sleep(5)   prints to stdout every 5 seconds when called with python script.py, but when I call python script.py &gt; log, the size of the log file stays zero until the script finishes. Is it possible to directly write to the log file, such that you can follow the progress of the script (e.g. using tail)?   EDIT It turns out that python -u script.py does the trick, I didn't know about the buffering of stdout.
2689
What is the idiomatic Python equivalent of this C/C++ code?  void foo() {     static int counter = 0;     counter++;     printf("counter is %d\n", counter); }   specifically, how does one implement the static member at the function level, as opposed to the class level? And does placing the function into a class change anything?
92186
I'm trying to typeset some python code, and I would like integer literals to be highlighted. I've come up, after about two hours of fighting with the documentation and various other questions here and on SO, with the following:  \lstset{ %     language=Python,     otherkeywords={1, 2, 3, 4, 5, 6, 7, 8, 9, 0},     morekeywords=[2]{1, 2, 3, 4, 5, 6, 7, 8, 9, 0},     keywordstyle=[2]{\color{orange}},     keywordstyle=\color{blue}\bfseries,     stringstyle=\color{red}, }   Unfortunately, that doesn't work. Numbers found in strings are also highlighted, which is rather annoying, and not only are they highlighted: they are highlighted in blue. Numerals in regular program text, on the other hand, are rightly highlighted in red.  Help?  EDIT: Thanks Peter Grill for your very nice solution. Is there a way to not break string colouring, though? When I use you code, the stringstyle=\color{red} doesn't seem to work anymore (strings are just plain black). Similarly, comments can be enclosed in triple quotes in python, and if I adapt your quote to detect """ blocks, then the corresponding  comments are not highlighted anymore.
43330
In python, if I say  print 'h'   I get the letter h and a newline.  If I say   print 'h',   I get the letter h and no newline.  If I say  print 'h', print 'm',   I get the letter h, a space, and the letter m.  How can I prevent Python from printing the space?  The print statements are different iterations of the same loop so I can't just use the + operator.
34951
It's a really basic question but i can't think at the second. How do i set up a loop that asks each time the function inside runs whether to do it again. So it runs it then says something like;  "loop again? y/n"
94709
Is there a method to print multi-line output (single output) on the same line?  For example, if the output is:  abc def qwerty   Is it possible to print:  abcdefqwerty
94278
I have a simple Python script that I want to stop executing if a condition is met.  For example:  done = True if done:     # quit/stop/exit else:     # do other stuff   Essentially, I am looking for something that behaves equivalently to the 'return' keyword in the body of a function which allows the flow of the code to exit the function and not execute the remaining code.
4188
While I was investigating a problem I had with lexical closures in Javascript code, I came along this problem in Python:  flist = []  for i in xrange(3):     def func(x): return x * i     flist.append(func)  for f in flist:     print f(2)   Note that this example mindfully avoids lambda. It prints "4 4 4", which is surprising. I'd expect "0 2 4".   This equivalent Perl code does it right:  my @flist = ();  foreach my $i (0 .. 2) {     push(@flist, sub {$i * $_[0]}); }  foreach my $f (@flist) {     print $f-&gt;(2), "\n"; }   "0 2 4" is printed.  Can you please explain the difference ?    Update:   The problem is not with i being global. This displays the same behavior:  flist = []  def outer():     for i in xrange(3):         def inner(x): return x * i         flist.append(inner)  outer() #~ print i   # commented because it causes an error  for f in flist:     print f(2)   As the commented line shows, i is unknown at that point. Still, it prints "4 4 4".
111183
What is the purpose of the colon before a block in Python?  Example:  if n == 0:     print "The end"
96984
Consider the following script:  #!/bin/bash  set -o pipefail set -o history  trapper() {    func="$1" ; shift    for sig ; do       trap "$func $sig" "$sig"    done }  err_handler () {   case $2 in     INT)        stop_received=1     ;;     TSTP)     ;;     ERR)        if [[ $2 != "INT" ]]; then # for some reason, ERR gets triggered on SIGINT           code=$?           if [ $code -ne 0 ]; then              echo "Failed on line $1"              echo "$BASH_COMMAND returned $?"              echo "Content of variables at the time of failure:"              echo "$(set -o posix; set)"              exit 1           fi        fi     ;;   esac }  main() {    ping -c 5 www.google.com # this is a test to see if INT interrupts main()    # do a bunch of stuff, I mean a real bunch of stuff, like check some    # files, do some processing, connect to a database,    # do more processing, move some files around, you get the drift }  exec &gt; &gt;(tee -a my.log) exec 2&gt;&amp;1  trapper 'err_handler $LINENO' INT TSTP ERR while main do   if [[ "$stop_received" == "1" ]]; then      break   fi   setsid sleep 2 &amp; wait done trap ERR   What I am trying to accomplish is to run the script in an infinite loop until either the function main() returns some non zero value, i.e. some error occurred, or SIGINT is received.  However, I don't want SIGINT to stop main() from executing, in other words, if the script receives a SIGINT, it should wait for main() to finish, then exit nicely. But when I hit CTRL+C, I can see that ping is interrupted. At the moment I commented out everything under main() just to see if this works. Since ping gets interrupted, I am assuming other commands under main() would also get interrupted. When ping is interrupted, the processing jumps to the line where I check if $stop_received=1 and then the loop breaks and the script quits. If I replace the break with just an echo, then the script just continues on to the next iteration of the while main loop.  How can I stop SIGINT from interrupting the currently running command(s)? Since my script does a bunch of stuff, including DML statements in a database, interrupting main() would cause lot of grief.  Secondly, the script does not trap ctrl+z either. Or rather, the script just gets stuck on ctrl+z requiring a kill pid to terminate. I assumed that sleep being a child of bash as opposed to the script itself, ctrl+z would cause the script to pause, leaving sleep in limbo land. Hence the setsid and wait on sleep, but it still hangs.  thanks.
80193
What's a better way to implement print_last_arg?  #!/bin/sh  print_last_arg () {     eval "echo \${$#}"  # this hurts }  print_last_arg foo bar baz # baz   (If this were, say, #!/usr/bin/zsh instead of #!/bin/sh I'd know what to do.  My problem is finding a reasonable way to implement this for #!/bin/sh.)  EDIT: The above is only a silly example.  My goal is not to print the last argument, but rather to have a way to refer to the last argument within a shell function.    EDIT2: I apologize for such an unclearly worded question.  I hope to get it right this time.  If this were /bin/zsh instead of /bin/sh, I could write something like this  #!/bin/zsh  print_last_arg () {     local last_arg=$argv[$#]     echo $last_arg }   The expression $argv[$#] is an example of what I described in my first EDIT as a way to refer to the last argument within a shell function.  Therefore, I really should have written my original example like this:  print_last_arg () {     local last_arg=$(eval "echo \${$#}")   # but this hurts even more     echo $last_arg }   ...to make it clear that what I'm after is a less awful thing to put to the right of the assignment.  Note, however, that in all the examples, the last argument is accessed non-destructively.  IOW, the accessing of the last argument leaves the positional arguments as a whole unaffected.
78827
My brother recently started learning C++. He told me a problem he encountered while trying to validate input in a simple program. He had a text menu where the user entered an integer choice, if they entered an invalid choice, they would be asked to enter it again (do while loop). However, if the user entered a string instead of an int, the code would break. I read various questions on stackoverflow and told him to rewrite his code along the lines of:    #include&lt;iostream&gt; using namespace std;  int main() {     int a;     do     {     cout&lt;&lt;"\nEnter a number:"     cin&gt;&gt;a;         if(cin.fail())         {             //Clear the fail state.             cin.clear();             //Ignore the rest of the wrong user input, till the end of the line.             cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(),\                                                     '\n');         }     }while(true);     return 0; }   While this worked ok, I also tried a few other ideas: 1. Using a try catch block. It didn't work. I think this is because an exception is not raised due to bad input. 2. I tried if(! cin){//Do Something} which didn't work either. I haven't yet figured this one out. 3. Thirdly, I tried inputting a fixed length string and then parsing it. I would use atoi(). Is this standards compliant and portable? Should I write my own parsing function? 4. If write a class that uses cin, but dynamically does this kind of error detection, perhaps by determining the type of the input variable at runtime, would it have too much overhead? Is it even possible?  I would like to know what is the best way to do this kind of checking, what are the best practices?  I would like to add that while I am not new to writing C++ code, I am new to writing good standards compliant code. I am trying to unlearn bad practices and learn the right ones. I would be much obliged if answerers give a detailed explanation.  EDIT: I see that litb has answered one of my previous edits. I'll post that code here for reference.  #include&lt;iostream&gt; using namespace std;  int main() {     int a;     bool inputCompletionFlag = true;     do     {     cout&lt;&lt;"\nEnter a number:"     cin&gt;&gt;a;         if(cin.fail())         {             //Clear the fail state.             cin.clear();             //Ignore the rest of the wrong user input, till the end of the line.             cin.ignore(std::numeric_limits&lt;std::streamsize&gt;::max(),\                                                     '\n');         }         else         {             inputCompletionFlag = false;         }     }while(!inputCompletionFlag);     return 0; }   This code fails on input like "1asdsdf". I didn't know how to fix it but litb has posted a great answer. :)