Ovalman
Posts: 17
Joined: Tue Aug 21, 2012 7:27 pm

Structuring Programs

Tue Aug 28, 2012 7:48 pm

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.

User avatar
scruss
Posts: 3398
Joined: Sat Jun 09, 2012 12:25 pm
Location: Toronto, ON
Contact: Website

Re: Structuring Programs

Tue Aug 28, 2012 8:19 pm

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.
‘Remember the Golden Rule of Selling: “Do not resort to violence.”’ — McGlashan.
Pronouns: he/him

Ovalman
Posts: 17
Joined: Tue Aug 21, 2012 7:27 pm

Re: Structuring Programs

Tue Aug 28, 2012 9:01 pm

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

jmacey
Posts: 135
Joined: Thu May 31, 2012 1:05 pm

Re: Structuring Programs

Tue Aug 28, 2012 9:23 pm

There are (as is usual with python) quite a few ways of doing things, here are some examples

Code: Select all

#!/usr/bin/python

# 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")
foo(1)
foo(2.5)

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

a,b,sum=multReturn(1,2)
print a,b,sum
# or using a tuple
tuple=[]
tuple=multReturn(1,2)
print tuple
#or list
list=()
list=multReturn(1,2)
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++

Jon

jmacey
Posts: 135
Joined: Thu May 31, 2012 1:05 pm

Re: Structuring Programs

Tue Aug 28, 2012 9:25 pm

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

http://nccastaff.bournemouth.ac.uk/jmac ... index.html

User avatar
jackokring
Posts: 816
Joined: Tue Jul 31, 2012 8:27 am
Location: London, UK
Contact: ICQ

Re: Structuring Programs

Tue Aug 28, 2012 9:35 pm

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.
Pi[NFA]=B256R0USB CL4SD8GB Raspbian Stock.
Pi[Work]=A+256 CL4SD8GB Raspbian Stock.
My favourite constant 1.65056745028

Ovalman
Posts: 17
Joined: Tue Aug 21, 2012 7:27 pm

Re: Structuring Programs

Tue Aug 28, 2012 9:39 pm

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.

jmacey
Posts: 135
Joined: Thu May 31, 2012 1:05 pm

Re: Structuring Programs

Tue Aug 28, 2012 9:55 pm

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 foo.py (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 foo.py which we can import into another python file. The first example will do this

Code: Select all

#!/usr/bin/python
# 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
foo.foo(10)
# we can also run bar
foo.bar()
In the next example I will only import a single function from the foo module

Code: Select all

#!/usr/bin/python
# 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
foo(10)
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

#!/usr/bin/python
# import the foo module
from foo import * 

foo(10)
bar()
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 foo.py 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.

Ovalman
Posts: 17
Joined: Tue Aug 21, 2012 7:27 pm

Re: Structuring Programs

Tue Aug 28, 2012 10:23 pm

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.

simplesi
Posts: 2327
Joined: Fri Feb 24, 2012 6:19 pm
Location: Euxton, Lancashire, UK
Contact: Website

Re: Structuring Programs

Tue Aug 28, 2012 11:43 pm

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

a=100
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:
Simon
Seeking help with Scratch and I/O stuff for Primary age children
http://cymplecy.wordpress.com/ @cymplecy on twitter

BlackJack
Posts: 288
Joined: Sat Aug 04, 2012 8:28 am
Contact: Website

Re: Structuring Programs

Wed Aug 29, 2012 11:16 am

@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__':
    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_hello()
        print a


if __name__ == '__main__':
    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.

Code: Select all

while not self.asleep():
    sheep += 1

jmacey
Posts: 135
Joined: Thu May 31, 2012 1:05 pm

Re: Structuring Programs

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!

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

Ovalman
Posts: 17
Joined: Tue Aug 21, 2012 7:27 pm

Re: Structuring Programs

Wed Aug 29, 2012 5:57 pm

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:
        PrintHello()
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)

Ovalman
Posts: 17
Joined: Tue Aug 21, 2012 7:27 pm

Re: Structuring Programs

Sat May 31, 2014 4:16 pm

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

Mark

User avatar
DougieLawson
Posts: 39843
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK
Contact: Website Twitter

Re: Structuring Programs

Sat May 31, 2014 5:28 pm

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: https://blogs.oracle.com/java/entry/dev ... ns_using_a
Note: Any requirement to use a crystal ball or mind reading will result in me ignoring your question.

Criticising any questions is banned on this forum.

Any DMs sent on Twitter will be answered next month.
All fake doctors are on my foes list.

Ovalman
Posts: 17
Joined: Tue Aug 21, 2012 7:27 pm

Re: Structuring Programs

Sat May 31, 2014 6:28 pm

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.

User avatar
DougieLawson
Posts: 39843
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK
Contact: Website Twitter

Re: Structuring Programs

Sat May 31, 2014 6:54 pm

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.
Note: Any requirement to use a crystal ball or mind reading will result in me ignoring your question.

Criticising any questions is banned on this forum.

Any DMs sent on Twitter will be answered next month.
All fake doctors are on my foes list.

Ovalman
Posts: 17
Joined: Tue Aug 21, 2012 7:27 pm

Re: Structuring Programs

Sat May 31, 2014 7:12 pm

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 .

User avatar
DougieLawson
Posts: 39843
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK
Contact: Website Twitter

Re: Structuring Programs

Sat May 31, 2014 7:22 pm

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.
Note: Any requirement to use a crystal ball or mind reading will result in me ignoring your question.

Criticising any questions is banned on this forum.

Any DMs sent on Twitter will be answered next month.
All fake doctors are on my foes list.

Ovalman
Posts: 17
Joined: Tue Aug 21, 2012 7:27 pm

Re: Structuring Programs

Sun Jun 01, 2014 9:48 am

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 http://twit.tv/show/coding-101 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.

User avatar
DougieLawson
Posts: 39843
Joined: Sun Jun 16, 2013 11:19 pm
Location: A small cave in deepest darkest Basingstoke, UK
Contact: Website Twitter

Re: Structuring Programs

Sun Jun 01, 2014 11:07 am

http://developer.android.com/training/index.html 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.
Note: Any requirement to use a crystal ball or mind reading will result in me ignoring your question.

Criticising any questions is banned on this forum.

Any DMs sent on Twitter will be answered next month.
All fake doctors are on my foes list.

Ovalman
Posts: 17
Joined: Tue Aug 21, 2012 7:27 pm

Re: Structuring Programs

Sun Oct 08, 2017 4:05 pm

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 https://play.google.com/store/apps/deta ... 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!

User avatar
jahboater
Posts: 6105
Joined: Wed Feb 04, 2015 6:38 pm
Location: West Dorset

Re: Structuring Programs

Mon Oct 09, 2017 7:01 am

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.

Heater
Posts: 16545
Joined: Tue Jul 17, 2012 3:02 pm

Re: Structuring Programs

Mon Oct 09, 2017 9:38 am

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!
Memory in C++ is a leaky abstraction .

User avatar
jahboater
Posts: 6105
Joined: Wed Feb 04, 2015 6:38 pm
Location: West Dorset

Re: Structuring Programs

Mon Oct 09, 2017 9:42 am

Yes,

See the answers to https://stackoverflow.com/questions/250 ... c-programs

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

Return to “General programming discussion”