I know, you did not ask, but the program should be more tight (compact).

Something like this:

import random
def main() :
    tie_message="It's a draw. You both threw %s."
    win_message="You win! Your opponent threw %s."
    lose_message="You lost. Your opponent threw %s."
    values=("rock","paper","scissors") # must be in increasing beating order
    while True:
        print "1)rock 2)paper 3)scissors 4)quit" 
        pick = raw_input ("What do you pick?: ").lower()
        rand = random.choice(values)
        if pick == "quit":
        if pick not in values:
            print "Invalid choice!"
        if pick == rand:
            print tie_message % rand
            if (pick_index,rand_index) in ((0,1),(1,2),(2,0)):
                print lose_message % rand
                print win_message % rand

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...

Good luck!

from random import randint
def guess():
    if int(input("Guess the number (1-10):"))==randint(1,10):
        print("Got it") 

You did not mention any reason that justifies creating a new tkinter mainloop. So take a look at these:

You can make FirstScreen a modal toplevel window.

If you want to keep the functionality to run the FirstScreen separately, then you can put it in a module (separate file), that behaves like a self contained program when run.

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]

Well. I would gladly demonstrate, what I am talking about.
Please, show me a working code!
If you have difficulties posting here, use pastebin.com.

First try to make a version of it, that actually can be run by others.
If I copy-paste your code into notepad, then save it, it does not run.

I would recommend the following improvements after that:

  • Place imports at the top
  • Remove global variables, get rid of import *
  • Make it shorter. First preferably under 100 then under 50 LOC
  • Create a bubble class, ship class and move everything possible into them
  • Separate gui from game logic.

Why are there so many main game loops? There can be only one.... :)

I/ if you import everything from turtle, like this:
from turtle import *

Then you cannot make statements like this:
point = turtle.Point(x,y)

You should do: import turtle

II/ allTriMedian function is never called. So it is never executed.
You should call it like: allTriMedian()

III/ There is no Point and Polygon in turtle. You are calling something, that is not there.

IV/ triangle is a local variable in function allTriMedian. It is not visible outside of it.
The whole program just does not make sense. There are several typos, too.

Thats why you do not get an answer on stackoverflow

V/ Here is something that draws a random triangle:

import turtle
import random


def gen_triangle_points():
    for i in range (3):
        x = random.randint(0,300)
        y = random.randint(0,300)
    return vertices

def draw_shape_from_points(vertices):
    for point in vertices[1:]:



  • 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

Google is your friend.


First hit:

Which sais:
[ EDIT: Gmail made some security change change recently. You now have to allow “less secure apps” on your account. Otherwise, you won’t be able to connect to it with your python script. ]

I do not understand.

  • Do you want to draw the maritime flag images using turtle graphics or you want to put the downloaded flag images on a canvas?
  • What is the expected output of the function?


import tkinter as tk
master = tk.Tk()
for row, (key, value) in enumerate(menu.items()):
    tk.Checkbutton(master, text=key, variable=menuvars[key]).grid(row=row, sticky=tk.W)

How to make panel in tkinter or which widget will be used to hide and show checkbox?

I am not sure, I understand this sentence.

Something about the keywords "widget" and "hide"


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?

Yes. There is a way to convert it to a GUI based program.

Before you do that, I would recommend:

  • Make a self containained version, so others can run it. That helps you to get help.
  • Make the program shorter. At first glance the program can be reduced at least to half size without hurting readability and functionality.
  • Write function documentation. The aim of the documentation is to tell the reader what the function is intended to do. Not how it is intended to accomplish it. If you cannot formulate the purpose of the function in one sentence, then something is wrong.
  • Also meaningless naming is burden to understandability. array, database1, a, b, c.
  • Try to get rid of global immutable changing variables. Document and name the globals as if they were functions.

Why is there a python tag?

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 whathaveyoutried.com , 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 www.whathaveyoutried.com 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 = infile.read()
        self.editing_window.insert(INSERT, contents)

def main():
    onager = Scratchpad()

if __name__=='__main__':

I think the most used layout for tkinter is grid.

So grid paper and pen.

I know, this is not software. Others recommend that, too.

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,self.day)

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

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 my python implementation in this thread as an answer. Nobody bothered to read it ...

I hope nobody thinks these algos are used in the real world. There are much better algos to determine if a number is prime. Since the beginning of the 20th century.

These functions are good to understand how to program, and how to program in python. They are hardly usable for anything real. Harder euler problems cannot be solved with them.

Gribouillis commented: Indeed +14

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....

[mylist[i:i+3] for i in range(0,len(mylist),3)]