Beside Gribouillis' explanation.

Although, sounds simple but still not able to understand the concept behind.

Core concepts are the most hard things.

I would like to know how they picked up the module sys or how we gonna decide from where we need to import.

The author picked it, because the desired object - the argv variable - is in this module. Period, end of discussion.

Why this functionality is in this module is because the author of python interpreter - beeing a built in module - decided to put it into this module.

How an author of a module decides about a module name, and the functionality of the module is up to his judgement.

However, module names are considered good, if a user (a programmer) can safely guess the functionality of a module by its name, and can find a module name by knowing the functionality he expects.

Based on my exprience on programming I would look for "command line argument", if I did not know python:

  • In builtins or globals, as in C or perl
  • in some operationg system specific module, because its os specific
  • in some system specific module, because it is global to a program
  • in something called shell, because shell is the first to process it

Anyway a lasy programmer usually types into the google: Command line arguments python
And gets the answer...

I am not very clear about what does this mean, my original understanding is that x will keep data's first two dimensions, and take a slice from data on the third and fouth dimension.

It keeps the first and fourth dimension and slices the two inbetween.


The first dimension is unchanged. If c=d=0, then the second and third dimension is between 0 and 0-1=-1. So no item is selected.
The last one is not mentioned, so it stays unchanged.

The same behaviour on a one dimensional python array (list):

>>> data=list(range(10))
>>> c=0
>>> data[c:-c]
>>> c=2
>>> data[c:-c]
[2, 3, 4, 5, 6, 7]
  • You are not adding up the even cubes. You are adding up all cubes of numbers between 0 and natn-1.Look up range documentation, how to generate even numbers.
  • Average is sum divided by count. You can count the numbers by (python3):

    add = 0
    for i in range (natn):
    add = add + i**3
    counter = counter +1

  • The whole problem can be solved in the end by:

Cannot copy paste code, because code tag does not work here on daniweb...

tinstaafl commented: FYI - you can copy and paste code. To get it to format properly select all code after you've pasted it and hit tab.Make empty line before & after +13

Maybe I was not clear enough.

If you give a variable to a control object in tkinter, then the control reads its state from this variable. If you do not keep track of this variable, then you loose the state of the control.

Unfortunately (?) the the control's binding to the variable seems to be weak. So if you loose reference to the control's variable in your code, then the control is loosing it too. So something undefined happens....

So instead of
Line 46:
v = IntVar()

Do this:
and update all occurences.

Line 46:
v = IntVar()

v goes out of scope.

If you bind v to something persistent (self), then it works.

How did you plan to read that variable anyway?

Hello there!

Short version: I do not understand the question.

Long version:
My eagle eye detected you posting the second question about the same project.

This should be a very secret project. If you would tell us what this is about, we could provide much more help.

However your code seems to do the following:

  • You have a set of members with attributes
  • You have a set of rules. Each rule combines the member attributes into a logical statement.
  • You want to apply the rules on the members and store the result

If that is the case here, then there are far better solutions.

Just a remark:
This is a semantic error:

        rule= rulesArray[i].split(",")
        rule= rulesArray[i].split(" ")
Gribouillis commented: same short version +14

Please post a working code, to help others. Try to copy-paste your own posted code into a .py file and see, that it does not work. There is a syntax error, not just intendation problems. The mainloop call is missing, too.

I have corrected the code, and hopefully solved your problem:

import tkinter

class MPG: 
    def __init__(self):
    #create window
        self.main_window = tkinter.Tk()

        #create 4 frames
        self.gallons_frame = tkinter.Frame(self.main_window)
        self.miles_frame = tkinter.Frame(self.main_window)
        self.mpg_frame = tkinter.Frame(self.main_window)
        self.button_frame = tkinter.Frame(self.main_window)
        self.error_frame = tkinter.Frame(self.main_window)

        self.gallons_label = tkinter.Label(self.gallons_frame, \
                                        text= "Enter the number of gallons:")
        self.gallons_entry = tkinter.Entry(self.gallons_frame, \
        self.miles_label = tkinter.Label(self.miles_frame, \
                                        text= "Enter the number of miles:")
        self.miles_entry = tkinter.Entry(self.miles_frame, \
        self.result_label = tkinter.Label(self.mpg_frame, \
                                        text="Miles Per Gallon")
        self.mpg = tkinter.StringVar()
        self.mpg_label = tkinter.Label(self.mpg_frame, \
        self.calc_button = tkinter.Button(self.button_frame, \
                                            text="Calculate MPG" , \
        self.quit_button = tkinter.Button(self.button_frame, \
                                            text="Quit", \

        self.error_label=tkinter.Label(self.error_frame, textvariable=self.error)


    #check gallons and miles numbers. If it can be converted, then return it, if not set the errorlabel.
    def checknumber(self, stringvalue, numbername):
            self.error.set(numbername+" is not a number")
            return None
        if to_return<0:
            self.error.set(numbername+" is negative")
            return None
        return to_return

    #the calc_mpg is the callback function for the calc_button    
    def calc_mpg(self):

        gallons = self.checknumber(self.gallons_entry.get(),"Gallons")
        if gallons is None: return

        miles = self.checknumber(self.miles_entry.get(), "Miles")
        if miles is None: return

    #calculate the MPG
        miles_per_gallon = round((miles / gallons),2)

    #update mpg_label

carmpg = MPG()

grand_78 commented: Sorry for the errors, I was in a rush when typing it. Thank you, this did fix my problem. Much appreciated. +0

Besides from , I can only say:

values=[int(input("Give the number(%s): " % i)) for i in range(1,6)]
print("Highest: {} \n Lowest: {} \n Average: {}".format(max(values),min(values), sum(values)/len(values)))

But beleve me. You should try something.

rproffitt commented: Excellent reference. Upsetting to some which is excellent. +9

You use global imported variables locally.

There is no need to pass ScrolledText and Tk to the Scratchpad class's dunder init. This is redundant.

This is the same, but cleaned up:

from tkinter import Tk, END, INSERT
from tkinter.scrolledtext import ScrolledText
from tkinter.filedialog import asksaveasfilename, askopenfilename

class Scratchpad:

    def __init__(self):
        self.display = Tk()
        self.display.title("Onager Text Editor")
        self.display.bind('<F7>', self.save_file)
        self.display.bind('<F5>', self.open_file)

    def create_editor(self):
        self.editing_window = ScrolledText(self.display)
        self.editing_window.configure(fg='gold', bg='blue', insertbackground='cyan',
            height='25', width='70', padx='12', pady='12',
            wrap='word', tabs='48', font='serif 12')

    def save_file(self, event=None):
        name = asksaveasfilename()
        outfile = open(name, 'w')
        contents = self.editing_window.get(0.0, END)

    def open_file(self, event=None):
        name = askopenfilename()
        infile = open(name, 'r')
        contents =
        self.editing_window.insert(INSERT, contents)

def main():
    onager = Scratchpad()

if __name__=='__main__':

Here you are. I hope, this makes you a really good programmer.

states=sorted([(f[i].strip(),f[i+1].strip(),int(f[i+2])) for i in range(0,len(f)-3,3)],key=lambda x:x[2])
print("minimum population:",states[0])
print("maximum population:",states[-1])
j.parkerrrr commented: Thank u very much, I really appreciate it. +0
class Date(object):

    def __init__(self, year, month, day):

    def __add__(self, other):
        if not isinstance(other,Delta):
            raise Exception("can only add Delta object")
        #FIXME handle the calendar 
        return Date(year,month,

    def __str__(self):
        return "("+",".join(map(str,(self.year,self.month,")"

class Delta(object):

    def __init__(self, year, month):
        if not (1<=month<=12) or year<0 or \
        not isinstance(year,int) or not isinstance(month, int):
            raise Exception("invalid Delta parameters")

    def __add__(self, other):
        return other+self

print Delta(year=5, month=6) + Date(2019,5,2)

There is no question.
So I have solved it.


nums=[(int(input("Give me the number numero {}: ".format(i+1)))) for i in range(20)]
print("Lowest: {}\nHighest: {}\nTotal: {}\nAverage: {}".format(min(nums),max(nums),sum(nums),sum(nums)/len(nums)))

I hope that makes you smarter.

I suggest to calculate it in a spreadsheet (excel) before you program it. The first x rows will be the conditions, then every row is a date where a payment is due. The columns will be the variables you are using in the program.

Let me inform you, that this calculation is far from the real world loan calculation. Bicycle-car comparison comes to my mind. Both are vehicles. But this may not matter for you....

This is a horrible post, you have made here.

  1. Your code does not run. Bad indent.
  2. Are you sure, we need all the data from the database to answer your question?
  3. You did not give us the python version you are using.
  4. You did not give us the structure of the table(s) and indices you are using. You are asking how to use an index, we do not know anything about.
  5. Your select statement : "SELECT channel, title, start_date, stop_date FROM programs WHERE channel" is semantically and probably sytaxtically incorrect. This is not a python problem.

No wonder no one answers....

There is a script in the python distribution:


Maybe itt will help you if you look at it.

Gribouillis commented: great info! +14

I would create a decorator, that decorates the function.

Something like:

@menu_item(Name="Save", enabled=True)
def save_menu():
    function body

The decorators would add a dictionary (for example with the name menu_data) to the decorated function with the arguments.

The program code would scan the functions and if a function has menu_data attribute, then it would use it. Or better the decorator would register it into an application wide user menu list.

Gribouillis commented: I was faster! +14

You probably have to open the file in binary mode ("wb"). I do not think you have to convert the_page to anything before writing.

Otherwise use urlretrieve, as you already found out.

I would call this system administration with python and would search for those terms.

In my not informed opinion, the shells are more suitable for that job. The problem arrives with them, when you have to write real programs in them.
I think, if you have a python program with a small part doing sysadmin stuff, use python's sysadmin modules.

* We create a list of one character strings, which are the button labels and numbers or operations at the same time. 
line 6-11
* We start a loop on button label elements. We interpret an index of a button label element as a row, column index. row= index//4+1 column=index%4
line 13-15, line 19-21, 
* In this loop for each element **begin**
* We create a button, with the following attributes 
    * the actual label element as text 
line 17 text=buttons
    * a function call with the actual label element as a parameter (function not explained here)
line 16 and line 17 'command=cmd '
    * we set the button's grid, to place the button to row and column
line 17 '.grid(row=r, column=c)'
* In this loop for each element **end**
* We create an entry widget  on the first (0th) row and make it span 4 column.
line 22-23

That's why.

An example:


for i in range(10):

print somelist



def process_somelist():
    for i in range(10):


print somelist

I have python2 so I changed tkinter to Tkinter. I am not a big tkinter expert.

Firstly the code does not work. root.mainloop() or similar is missing. If I put it in, it works.

Secondly. If you have created the code, then there was something on your mind, or not?

Thirdly: I tried to do what I understand you want.

* We create a list of one character strings, which are the button labels and numbers or operations at the same time. 
* We start a loop on button label elements. We interpret an index of a button label element as a row, column index. row= index//4+1 column=index%4
* In this loop for each element **begin**
* We create a button, with the following attributes 
    * the actual label element as text 
    * a function call with the actual label element as a parameter (function not explained here)
    * we set the button's grid, to place the button to row and column
* In this loop for each element **end**
* We create an entry widget  on the first (0th) row and make it span 4 column.

I do not know a standard for pseudo code. I have read this, and became not smarter.

For a natural language pseaudo code I would write:

asktext = Which sided dice would you like to roll? You can choose a 4-sided dice, a 6-sided dice or a 12-sided dice. Type 0 to exit the loop.
printouttext="The %s-sided dice has rolled to %s"
infinite loop:
    ask the user which dice to roll with asktext
    convert the aswer to integer, store it in sides
    if sides is 0, then exit the loop
    if sides not one of 4,6,12, then continue the loop
    make a random integer between 1 and sides, store it in rolled.
    print out printouttext with sides and rolled substituted

Your 7th line has an error. You need to convert the output of the input function to int. Not the input function itself.
It is an over kill to calculate all the diceroll for all the possible inputs. It is enough to calculate it after the input.
No need for so much elifs...
Randrange is overkill for this...

I fixed this for you:

import random
while True:
    sides = int(input("Which sided dice would you like to roll? You can choose a 4-sided dice, a 6-sided dice or a 12-sided dice. Type 0 to exit the loop."))
    if sides==0:
    if sides not in (4,6,12):
        print("Please input a number 4, 6 or 12")
    rolled = random.randint(1,sides)
    print ("The %s-sided dice has rolled to %s" % (sides,rolled))

Hello Zahra!

I would make a Game class that holds the characters. Then I would make the characters that generates the attributes. The attributes are generated by rolling a dice.

Something like this:

# python 2 code

import random
class Dice(object):
    def __init__(self,sides):
    def roll(self):
        return random.randint(1,self.sides)

class Charachter(object):
    def __init__(self, name):
        self.attributes={"strength":0, "skill":0}

    def reset_attributes(self):
        for k in self.attributes.keys():

    def __str__(self):
         for k,v in self.attributes.iteritems():
              ret+="%s : %s\n" % (k,v)
         return ret

class Game(object):
    def __init__(self):

    def generate_charachters(self):

if __name__ == "__main__":
    for ch,attrs in g.charachters.iteritems():
         print ch
         print attrs

Next I would make a method in the charachter class that outputs the character data in some standardized way, possible a dictionary containing name and a dictionary of attributes. Then I would make the game class generate the two characters and save the data of the characters into a file.

The next move is to load the characters from this file...

Some remarks...

I would say that a function is auxiliary if it is called and used by a limited set of functions (methods, other callables) and does not provide functionality(meaning) on its own.

If you write some date arithmetic module, then isleapyear appears not to be an auxiliary function. It has functionality, that can be understood and possibly used by the user (caller) of the module.

Here is an example of an auxiliary function:

Your original question was to determine if a date is valid:

def throws(t, f, *a, **k):
    '''Return True iff f(*a, **k) raises an exception whose type is t
      (or, one of the items of _tuple_ t, if t is a tuple).'''
        f(*a, **k)
    except t:
        return True
        return False

def is_valid_date(date_string):
    import datetime
    return not throws(ValueError,datetime.datetime.strptime,date_string, '%Y-%m-%d')

print is_valid_date('2014-02-28')
print is_valid_date('2014-02-29')
Gribouillis commented: interesting method +14

Yes, it is worse then the infamous:

not re.match(r"^1?$|^(11+?)\1+$", "1" * number_to_test)

There is nothing wrong with this algo. But computers (more precisely: functions using stack in the operating system) are not built the way, they can process this program efficiently. It is a leaking abstraction. Google it.

Gribouillis commented: ugly code :) +14

I think this is the wrong question.
Allow me to be philosofical.

I advise you to consider the following wisdom:
A good programmer is smart and gets things done.

Consider this as a buddhist quote.

Smart means to be brutally honest to yourself about whether you understand something or not. Many cultures promote self esteem, grades, social status or wealth about real knowledge. Don't fool yourself.
Smart means, you always keep yourself busy with something you don't know. So, to be smart means to be stupid.
If you repeat yourself, if you make the same thing again and again without improvement, you are a code monkey.
Smart means creativity. You have to have idees to improve, new aspects.

Getting things done is the reality check. If you do not accomplish something with your knowledge, then you are similar to a body builder who trains by imagining doing exercises and reading books.
Whatever you do, finish it. Make little goals that lead to bigger ones.
Do not try to be perfect. Nothing is perfect, what man does. Be clear what the goal is and achieve it. Good enough is good enough.
If you build something that keeps working for years, then good enough can become deficient. Next time you will will be smarter and change what good enough is.

iamthwee commented: excellent +14

Then the only thing is missing now is the "below".

Turtle is designed to be easy. If you can draw the image by hand on a square paper, then you can do the same with turtle.

Or better:

class Importedvalues(object): 
    def __init__(self,inputstring):
        for statement in inputstring.split("&"):


print i.variable1
print i.varible2
print i.varible4