Page 1 of 2

Structuring Programs

Posted: Tue Aug 28, 2012 7:48 pm
by Ovalman
Hi all, I haven't done any programming in 25 years since my days of programming on my ZX81/ Spectrum.

Since my return, I initially tried to learn myself first C++ and Android but things seem so alien to me. Since I got my Raspberry Pi, I've tried to learn Python but again I'm getting stuck at a very early stage of the programming language.

How should I be structuring programs? How do I access sub-routines? Should I name all my variables at the start of a program? What are classes and objects? If I import something is that basically a sub-routine?

Sorry if these are totally noob guestions but on the Sinclair machines if I wanted to access a sub-routine all I had to do was type

10 gosub 100; it ran through the sub-routine and then went back to the line after 10.

I'm also curious about arrays, any good links on how to define them and tips on a dynamic array?

Maybe I'm trying to run before I can walk but I like to dive straight into playing with the code and I have a few idea's that I want to try but it's structured somewhat differently to what I was used to on the Sinclair machines.

Re: Structuring Programs

Posted: Tue Aug 28, 2012 8:19 pm
by scruss
Have you looked at The Python Tutorial? It explains all of the concepts you're asking. It starts from simple commands in direct mode, so you can see what's happening immediately.

Re: Structuring Programs

Posted: Tue Aug 28, 2012 9:01 pm
by Ovalman
scruss wrote:Have you looked at The Python Tutorial? It explains all of the concepts you're asking. It starts from simple commands in direct mode, so you can see what's happening immediately.
Thanks for the reply. I've maybe asked for too much info in the one question.

I've went through the start of several Python tutorials including one which I found the best for teaching a noob like myself. I do understand many parts of it but I'm still not sure how programs are structured. I've looked at examples of completed programs and there's too much info to take in to understand.

How do I handle sub-routines for instance on Python? Say I want a load of variables only specific to one small part of a program? Should I name everything at the start of a program?

I've come from Sinclair BASIC that was structured like:

10 let a=100
20 let a=a+1
30 if a=15 then gosub 100
40 print a
50 goto 20

100 print "Hello"
110 return

Python programs are structured different than this. If say I want a sub-routine like above how should I run it in Python? How do I call a sub-routine every time I need it?

I'm a bit overwhelmed atm with how to program. I know this is pretty basic but I'm very rusty and maybe my programming on a Spectrum has thrown me when I've came back to learning a new language.

Re: Structuring Programs

Posted: Tue Aug 28, 2012 9:23 pm
by jmacey
There are (as is usual with python) quite a few ways of doing things, here are some examples

Code: Select all


# to define a function use def, it needs to be before the first use
# as python is
def foo(_value) :
	print _value
# this passes two values and returns a 3rd
def add(_v1,_v2) :
	return _v1+_v2

def multReturn(_v1,_v2) :
	return _v1,_v2,_v1+_v2

# test functions
#  as python is typeless we can pass in any type here
# however this can cause problems if we want to have specific types
foo("a string")

print sum
# this will work
string=add("hello"," python")
print string
# this will fail (comment out with  # to try next ones)

print a,b,sum
# or using a tuple
print tuple
#or list
print list
Main thing to remember is that to define a function you use the def [name](param list...) : structure and anything tabbed in after is part of the function body.

You can return multiple values or lists / tuples as there is no pass by reference like C/C++


Re: Structuring Programs

Posted: Tue Aug 28, 2012 9:25 pm
by jmacey
Just read the 2nd part about variables, this is a harder topic to approach as python is typless. I usually define variables when I need them and make sure they are not global (unless it's a quick hacked script for myself). I have some basic python lectures here if it helps ... index.html

Re: Structuring Programs

Posted: Tue Aug 28, 2012 9:35 pm
by jackokring
The structure has not changed too much, just the words which do the structuring, and there are many, so you can make lots of structure.

Gosub 100 and so on has been replaced by def: labelForFancySubroutine on next line<TAB>stuff..... RETURN <possible returned thing>

Don't forget the <TAB> indent. ------>>> as this indent groups things as inside that which is not indented as much.

"Import" is a way of having multiple "programs" (as it were) which may do different things. Importing one allows you to use all the named subroutines or definitions of the "imported program" (known as a library or module).

A class is like a miniature program. It has its own contained variables and functions. It can be used many times within the main program. An example of a class would be maybe a mini program which drew a tiny man doffing his hat. Using this class in the main program could allow you to draw many men doffing their hats at maybe different rates, or even with different styles of hat if you use a technique called "inheritance" or "sub-classing".

I hope this made some things clearer.

Re: Structuring Programs

Posted: Tue Aug 28, 2012 9:39 pm
by Ovalman
Thanks JM, I'll have a read through your material.

Are you saying that to define a sub-routine we create a function? After the sub-routine has completed it just goes back to the next line of your main code? Do we define functions at the start/ middle/ end of every program? Does it matter where the function goes?

Is an import basically just a function that someone else has created?

Many thanks for the help BTW.


I had the above typed when you made your final post. You have made some things clearer btw.

Re: Structuring Programs

Posted: Tue Aug 28, 2012 9:55 pm
by jmacey
The functions need to be defined before they are invoked so I usually put them before the functions as shown above to make it neater.

If you want to put the functions in a different module you would do something like this

First create a file called (the name is important as we will import it in another file later)

Code: Select all

def foo(_value) :
  print "in foo",_value

def bar() :
  print "bar func called"
This has created a module called which we can import into another python file. The first example will do this

Code: Select all

# import the foo module
import foo
# as the function foo is part of the module foo we need to access it with the . 
# this is basically saying from the foo module use the function foo
# we can also run bar
In the next example I will only import a single function from the foo module

Code: Select all

# import the foo function from the module foo
from foo import foo
# now I don't need to qualify the function name from the module as I've explicitly imported it
Finally you can blanket import all the code from a single module (this can get messy due to name clashes etc in more complicated systems)

Code: Select all

# import the foo module
from foo import * 

One thing to notice if you do an ls in your directory you should see a file called foo.pyc this is a compiled python module that get created first time you import the foo module. Sometimes you may get issues when editing your main file and re-importing it as this will not get updates, this is rare but has caught me out sometime (usually due to embedded python in animation packages such as Maya) so it is safe to delete these if you need to or run into problems.

Re: Structuring Programs

Posted: Tue Aug 28, 2012 10:23 pm
by Ovalman
Many thanks, again you're making things clearer for me.

I'll have a read all of this thread again and also the material on your link and get back tomorrow. I've made more progress tonight than for many weeks.

I've checked many sites but things seem to move too quick for me. I think if I understand how programs are structured then that's half the battle won. I can always learn the coding terms as I come across or need them in the future.

Re: Structuring Programs

Posted: Tue Aug 28, 2012 11:43 pm
by simplesi

Code: Select all

def PrintHello():
    print "Hello"
    #need to put all "subroutines" before main code so that main code knows about them
    #no need for a return as the next line is not indented and python notices that

while (a > 0):        # just looping while a is great than zero
    a=a-1             #note you can still use = here to change variables
    if a == 15:       #note use of == as you need to use == if checking variable value
        PrintHello()  #equivalent to gosub 100
    print a           # daft way Python makes you print simple variables
Does what your basic code does (with slight adjustment - your basic prog would never get to gosub 100 :)
Hope this helps to keep things simple:

Re: Structuring Programs

Posted: Wed Aug 29, 2012 11:16 am
by BlackJack
@Ovalman: The variable naming by jmacey with underscores in front is very unusual. If done at all, most Python programmers use this for names that are never used but have to be there for some reasons.

Names should not be defined unless they are needed. If you define them all at the top of the source file or at the top of a function or method you will have to come up with never to be used dummy values for some of them. And when the reader comes to the place where the name is first used he may have to look up and search back in the code where the name was bound to which value. It is easier to read if this definition is closer to the code that actually uses it.

Your array question really is a sign that you should work through the tutorial in the Python documentation. What you used arrays for in BASIC is a job for lists in Python. Learning the basic data structures like tuples, lists, dictionaries, and maybe sets should come before structuring larger programs.

A structuring advice: Don't have code on module level that does more than defining „constants”, i.e. constant values, functions, and classes. The main program part goes into a function conventionally called `main()` and there is this idiom to call it:

Code: Select all

if __name__ == '__main__':
The name `__name__` is set by Python to the name of the module — except when the module is the one that is executed as a program or skript. Then it is bound to the string '__main__'.

So your BASIC program might become this Python code (without the alterations/corrections of simplesi):

Code: Select all

def print_hello():
    print 'Hello'

def main():
    a = 100
    while True:
        a += 1
        if a == 15:
        print a

if __name__ == '__main__':
Besides the tutorial in the Python documentation Learn Python The Hard Way is a good tutorial/book. With a slightly misleading name. :-) The HTML version is free.

PEP 8 -- Style Guide for Python Code might be a good read for naming conventions and style.

@jmacey: Python is not typeless, it is even a strictly typed language. It is just not statically typed and the type is attached to values and not names.

Re: Structuring Programs

Posted: Wed Aug 29, 2012 11:22 am
by jmacey
sorry I use _var in C++ all the time as it's part of our coding standard, I forget when using python I shouldn't do it!

And by typeless I meant not statically typed, I'm so used to teaching python to non programmers (animators) I usually fudge over the details as they are not interested

Re: Structuring Programs

Posted: Wed Aug 29, 2012 5:57 pm
by Ovalman
Again many thanks for the extra input from simplesi, Blackjack as well as Jon.

I'm making some headway on this and as Jon said in his opening statement, there is no one way of doing things in Python. I altered Simplesi's piece of coding to get the same result and it's the first true coding I've created myself (without a c/p).

Code: Select all

def PrintHello():
    print ("Hello")
for a in range (1,100,1):
    print (a)
    if a==15:
So to create our program we define everything at the start of the program, importing whatever is needed and creating our def:s etc?

We then run our main bit of coding ?

I'm sure I'll come back to this soon as I get stuck again.

I'll come back to the array question in a new thread on the Python forum when I get around to it. (I created this in General Programming as I'd like to learn Android and or C at some point)

Re: Structuring Programs

Posted: Sat May 31, 2014 4:16 pm
by Ovalman
I took a break (a long break :) ) and came back to this.

I want to learn Android/ Java as I've a few ideas floating around that would suit the mobile platform. Stackoverflow seems very condescending but this forum seems great for asking even the dumbest questions as I did above. We all have to start somewhere!

It seems what I was looking for is Object Orientated Programming (OOP).

In my ZX Spectrum days everything was structured linearly but now everything is structured into classes and functions. Although it's meant to make programming neater, it certainly doesn't make it simpler! As always there is no right way to solve many problems but usually a wrong way. Getting to know the nuances is a lot harder, I never had else or while statements to deal with in BASIC :)

Sincerely many thanks for all your inputs. I've written a few small programs/ functions in Python but have moved back to Android where I'm find the going tough but I'll get there (eventually).


Re: Structuring Programs

Posted: Sat May 31, 2014 5:28 pm
by DougieLawson
You describing the difference between procedural and object oriented programming.

Procedural has all of the "working storage" defined in one place and statements, functions and subroutines operate on that single variable pool. Any line of code can update or destroy any variable.

Object oriented stores the data with the methods that work on that data, there's no single, public "working storage" pool so things become simpler, you remove the risk of reading unexpected data, you can remove the data to a private data pool (which exists when an object is instantiated and garbage collected when it is destroyed). Every class has a strictly defined set of methods.

In terms of eliminating the layers of spaghetti it's a massive improvement. In terms of failure isolation it's a massive improvement. But the cost of that is that it can be difficult to read.

The OO languages also includes inheritance, polymorphism and extensibility. That's the stuff that allows you to take a "bicycle" class and extend that to a new "mountainBicycle" or "roadBicycle" which are based on a basic "bicycle" but with extra methods.

There's a free education course at: ... ns_using_a

Re: Structuring Programs

Posted: Sat May 31, 2014 6:28 pm
by Ovalman
I find procedural programming so much easier to understand and implement. What I need I could almost but not quite do in ZX BASIC. I'm never suggesting to move back to procedural but that's what I understand and it's difficult for me to move beyond that. I guess I'm an old f*rt stuck in his ways.

For a new programmer it's probably a lot easier to grasp but for me it's been a struggle (and still a struggle.) I just wish I had have known about OOP 2 years ago when I first asked this question. Even with searching elsewhere and following courses online I was unaware of this, courses touched upon it but it was well into the course when it was implemented. I think for a newb this is THE most important aspect about programming that I've found so far.

Syntax and different methods will probably pickle my brain even further in the months/ years to come but I'll get there.

Re: Structuring Programs

Posted: Sat May 31, 2014 6:54 pm
by DougieLawson
The problem gets orders of magnitude worse when you get from 100 lines to 1000 lines to 10000 lines and then add some modules into the mix. With something like Java each class can be built and unit tested on it's own before the main routine glues everything together, each class moves back to the 100 to 1000 lines.

I've seen some ugly COBOL in my time (I've written ugly COBOL although mostly as a demonstration of how to use some special function or as a test case for a broken SQL statement).

ZX BASIC was self limiting due to the minuscule amount of RAM on those Sinclair machines. But it was still possible to write seriously ugly ZX BASIC.

Re: Structuring Programs

Posted: Sat May 31, 2014 7:12 pm
by Ovalman
I remember programming 48k BASIC and running out of memory in a few hundred lines of code :oops:

It taught me some bad habits that are hard to get rid of but I must complain about teaching methods that are skewed towards newbies that old f*rts can't grasp. OOP is totally new to me. I can get the variables and loops but structuring is new to me and why I asked my original question.

I've dipped in and out of programming in 3 years, my mind isn't fully committed but I'd like to learn so I can program the few ideas I have .

Re: Structuring Programs

Posted: Sat May 31, 2014 7:22 pm
by DougieLawson
Go with python, PHP or Perl. They can be written as procedural or OO.

It was quite a long way into my thirty three years of systems programming when OO started to get popular. I still think Java is a wordy language but at least it's not C++ (which is an abomination).

Given a free choice I'd always go for IBM's S/360, S/370 or zSeries assembler, although the downside of any (every) assembler language is that you have to write lots of lines to get very little done (but it is blindingly fast). I must look at the ARM6 assembler some time.

Re: Structuring Programs

Posted: Sun Jun 01, 2014 9:48 am
by Ovalman
My main problem is I want to write 3 programs that suit a mobile device.

One is a Fixture List Widget for the football club I support. I think this will be easy enough although I'm struggling linking Id's to clickable links.

2nd is a database for a cleaning company that schedules jobs and marks payments. I'm using Sqlite for the database which seems easy enough. I've actually made some headway on Python but it really needs to be on a mobile device for portability.

3rd is a game that uses the tilt ability of a phone. Again I could do this in Pygame but for full integration it has to be on a phone.

I've followed a few courses on Youtube for Android but they dive in too quick. The syntax of Android/ Java is pretty complicated and I've probably picked one of the harder languages to learn.

My Aha moment came when I started watching This is a much more generalised programming course that starts in the C# language but has now moved to Python. It explains OOP very well and early into the course, something that has never been pushed upon anywhere else.

I updated this thread mainly to help anyone who's in a similar position to myself who just doesn't get it. It's taken me 18 months on and off to get to this stage but I'm determined to get my 3 idea's on the go. I just hope this post saves someone else that amount of time.

Re: Structuring Programs

Posted: Sun Jun 01, 2014 11:07 am
by DougieLawson appears to be a good starting point for Android.

My first Hello World app runs to about 73 lines of Java and a bunch of XML to define the buttons and text that it displays. Of those 73 lines I wrote less than half because the ADK generates lots of the glue code for you.

Re: Structuring Programs

Posted: Sun Oct 08, 2017 4:05 pm
by Ovalman
I'm back again!

I know I'm not a regular on this forum but I've came back to this thread again to show that persistence works even for someone who's nearly half a century old.

I just released my first app on the Play Store, the fixture list widget for my football club ... listwidget. It's not complicated but it serves a purpose, something which another app doesn't achieve but the main thing is I created the app by understanding the code. It was also to understand the steps for releasing the app on the Play Store as I've several other apps in development including the database app which is well under development and I'm using it in a real world situation. I've several things to add but the core of the app is complete.

The thing that made it all click for Android was the free Udacity course which broke the whole Android programming into small bitesize chunks that were so basic almost anyone could understand it.

Most of the apps I'm building are suited for a mobile device so it was why I chose Android but I should have maybe learned Python before Android because to learn Android you need to learn xml, Java, Sqlite, html, Android Studio and a host of other things to get a program to work. Not really the easiest way to do things!

I've a load of other ideas including adapting my fixture list to use json data instead of me manually updating the fixture list every time there is a change. This way I could add results and also adapt the widget to other clubs and maybe include a few ads when I get a wide userbase (I've only 50+ installs atm)

I've now an idea for a Poker Tournament Organiser for my local Friday game. I've a Raspberry Pi Bluetooth version and I think it's a great project to start on. I think with my "expertise" (lol) I could create such an app. Again I'd need Sqlite which I'm familiar with and need a GUI for the user. If I do start the project, expect me to pick your brains at times!

Re: Structuring Programs

Posted: Mon Oct 09, 2017 7:01 am
by jahboater
jmacey wrote:
Wed Aug 29, 2012 11:22 am
sorry I use _var in C++ all the time as it's part of our coding standard, I forget when using python I shouldn't do it!
You shouldn't do it in C or C++ either.

Re: Structuring Programs

Posted: Mon Oct 09, 2017 9:38 am
by Heater
Oh my God, somebody was using _var in C++ five years ago!

Mind you I agree. Adding _var to a variable name is a useless and ugly wart on ones source code. It probably indicates that the variable is not named clearly enough. Seems to be part of a coding standard designed to make code worse!

Re: Structuring Programs

Posted: Mon Oct 09, 2017 9:42 am
by jahboater

See the answers to ... c-programs

and others. Apart from rendering the code unreadable, I don't think its even standards compliant.