weird python behavior (aka why doesn't it work)

For the discussion of Perl, Python, Ruby, and PHP and other interpreted languages.

weird python behavior (aka why doesn't it work)

Post by caracarn001 on Fri Mar 25, 2011 1:39 pm
([msg=55534]see weird python behavior (aka why doesn't it work)[/msg])

First of all: I'm new to python (this is my first project) so what I'm asking might be some basic python knowledge.

I'm writing a backup script. It gathers all files with predefined extentions, splits them up in categories and copies them to new folders (if the user wants it). Part of my code is asking the user if he/she wants to copy these items. I've written a function for it.
Code: Select all
def AskPrint(type, action):
   inp=input(action+" "+type+"?(y/n)")
   while not (inp.lower() == 'y' or inp.lower() == 'n') :
      AskPrint(type, action)
   if inp=='y' :
      return True
   else :
      return False

As long as I start the script within IDLE(python GUI) everything works fine. However, if I run this script from the command line(python <scriptnamehere>), I go into an endless loop. Now I'm wondering why. Is there a difference between input in IdLE and input from cmd?

if you're interested in the complete script, let me know, I'll post it.
User avatar
caracarn001
New User
New User
 
Posts: 42
Joined: Thu Nov 04, 2010 5:23 am
Blog: View Blog (0)


Re: weird python behavior (aka why doesn't it work)

Post by thetan on Fri Mar 25, 2011 8:46 pm
([msg=55545]see Re: weird python behavior (aka why doesn't it work)[/msg])

by calling AskPrint() at the _head_ of the function in a while loop that will run indefinitely if the user inputs anything other then y or n, you create infinite head recursion if and only if the user enters something other then y or n.

This is classic broken code and should be refactored.

working psuedo code is as follows:
Code: Select all
function askPrint(type, action)
{
    writeToStdout("%s %s?(y/n)", action, type);
    in = getInput();
    while(in != 'y' || in != 'n')
    {
        in = getInput();
    }
    if (in == y)
    {
        return true;
    }
    else
    {
        return false;
    }
}


This avoids infinite head recursion.

As for the difference between IO in IDLE vs Cpython .... doesn't make a difference in the presence of broken code.
"If art interprets our dreams, the computer executes them in the guise of programs!" - SICP

Image

“If at first, the idea is not absurd, then there is no hope for it” - Albert Einstein
User avatar
thetan
Contributor
Contributor
 
Posts: 657
Joined: Thu Dec 17, 2009 6:58 pm
Location: Various Bay Area Cities, California
Blog: View Blog (0)



Return to Interpreted Languages

Who is online

Users browsing this forum: No registered users and 0 guests