Category Archives: function definition

STARTING WITH PYTHON3 – The very beginning – part 5

Journal: uffmm.org,
ISSN 2567-6458, July 18-19, 2019
Email: info@uffmm.org
Author: Gerd Doeben-Henisch
Email:
gerd@doeben-henisch.de

CONTEXT

This is the next step in the python3 programming project. The overall context is still the python Co-Learning project.

SUBJECT

After a first clearing of the environment for python programming we have started with the structure of the python programming language, and in this section will continue dealing with the object type sequences and string and more programming elements are shown in a simple example of a creative actor.

Remark: for general help information go directly to the python manuals, which you can find associated with the entry for python 3.7.3 if you press the Windows-Button, look to the list of Apps (= programs), and identify the entry for python 3.7.3. If you open the python entry by clicking you see the sub-entry python 3.7.3 Manuals. If you click on this sub-entry the python documentation will open. In this documentation you can find nearly everything you will need. For Beginners you even find a small tutorial.

SZENARIO

For the further discussion of additional properties of python string and sequence objects I will assume again a simple scenario. I will expand the last scenario with the simple input-output actor by introducing some creativity into the actor. This means that the actor receives again either one word or sequences of words but instead of classifying the word according to some categories or instead of giving back the list of the multiple words as individual entities the actor will change the input creatively.
In case of a single word the actor will re-order the symbols of the string and additionally he can replace one individual symbol by some random symbol out of a finite alphabet.
In case of multiple words the actor will first partition the sequence of words into the individual words in a list, then he will also re-order these items of the list, will then re-order the letters in the words, and finally he can replace in every word one individual symbol by some random symbol out of a finite alphabet. After these operations the list is again concatenated to one sequence of words.
In this version of the program one can repeat in two ways: either (i) input manually new words or (ii) redirect the output into the input that the actor can continue to change the output further.
Interesting feature Cognitive Entropy: If the user selects always the closed world option then the set of available letters will not be expanded during all the repetitions. This reveals then after some repetitions the implicit tendency of all words to become more and more equal until only one type of word ‘survived’. This depends on the random character of the process which increases the chances of the bigger numbers to overrun the smaller ones. The other option is the open world option. This includes that in a repetition a completely new letter can be introduced in a single word. This opposes the implicit tendency of cognitive entropy to enforce the big numbers against the smaller ones.

How can this scenario be realized?

ACTOR STORY

1. There is a user (as executive actor) who can enter single or multiple words into the input interface of an assisting interface.
2. After confirming the input the assisting actor will respond in a creative manner. These creativity is manifested in changed orders of symbols and words as well as by replaced symbols.
3. After the response the user can either repeat the sequence or he can stop. If repeating then he can select between two options: (i) enter manually new words as input or (ii) redirect the output of the system as new input. This allows a continuous creative change of the words.
4. The repeated re-direction offers again two options: (i) Closed world, no real input, or (ii) Open world; some real new input

IMPLEMENTATION

Download here the python source code. This text appears as an HTML-document, because the blog-software does not allow to load a python program file directly.

stringDemo2.py

DEMOS

Single word in a closed world:

PS C:\Users\gerd_2\code> python stringDemo2.py
Single word = ‘1’ or Multiple words = ‘2’
1
New manual input =’1′ or Redirect the last output = ‘2’
1
Closed world =’1′ or Open world =’2′
1
Input a single word
abcde
Your input word is = abcde
New in-word order with worder():
ebaca
STOP = ‘N’, CONTINUE != ‘N’
y
Single word = ‘1’ or Multiple words = ‘2’
1
New manual input =’1′ or Redirect the last output = ‘2’
2
Closed world =’1′ or Open world =’2′
1
The last output was = ebaca
New in-word order with worder():
ccbaa
STOP = ‘N’, CONTINUE != ‘N’
y
Single word = ‘1’ or Multiple words = ‘2’
1
New manual input =’1′ or Redirect the last output = ‘2’
2
Closed world =’1′ or Open world =’2′
1
The last output was = ccbaa
New in-word order with worder():
ccccb
STOP = ‘N’, CONTINUE != ‘N’
y
Single word = ‘1’ or Multiple words = ‘2’
1
New manual input =’1′ or Redirect the last output = ‘2’
2
Closed world =’1′ or Open world =’2′
1
The last output was = ccccb
New in-word order with worder():
ccccc
STOP = ‘N’, CONTINUE != ‘N’

The original word ‘abcde’ has been changed to ‘ccccc’ in a closed world environment. If one introduces an open world scenario then this monotonicity can never happen.

Multiple words in a closed world

PS C:\Users\gerd_2\code> python stringDemo2.py
Single word = ‘1’ or Multiple words = ‘2’
2
New manual input =’1′ or Redirect the last output = ‘2’
1
Closed world =’1′ or Open world =’2′
1
Input multiple words
abc def geh
Your input words are = abc def geh
List version of sqorder input =
[‘abc’, ‘def’, ‘geh’]
New word order in sequence with sqorder():
def geh geh
List version of input in mcworder()=
[‘def’, ‘geh’, ‘geh’]
New in-word order with worder():
fef
New in-word order with worder():
hee
New in-word order with worder():
ege
New word-sequence order :
fef hee ege
STOP = ‘N’, CONTINUE != ‘N’
y
Single word = ‘1’ or Multiple words = ‘2’
2
New manual input =’1′ or Redirect the last output = ‘2’
2
Closed world =’1′ or Open world =’2′
1
The last output was = fef hee ege
List version of sqorder input =
[‘fef’, ‘hee’, ‘ege’]
New word order in sequence with sqorder():
fef fef ege
List version of input in mcworder()=
[‘fef’, ‘fef’, ‘ege’]
New in-word order with worder():
fff
New in-word order with worder():
fee
New in-word order with worder():
eee
New word-sequence order :
fff fee eee
STOP = ‘N’, CONTINUE != ‘N’
y
Single word = ‘1’ or Multiple words = ‘2’
2
New manual input =’1′ or Redirect the last output = ‘2’
2
Closed world =’1′ or Open world =’2′
1
The last output was = fff fee eee
List version of sqorder input =
[‘fff’, ‘fee’, ‘eee’]
New word order in sequence with sqorder():
eee fee fee
List version of input in mcworder()=
[‘eee’, ‘fee’, ‘fee’]
New in-word order with worder():
eee
New in-word order with worder():
eef
New in-word order with worder():
eee
New word-sequence order :
eee eef eee
STOP = ‘N’, CONTINUE != ‘N’
y
Single word = ‘1’ or Multiple words = ‘2’
2
New manual input =’1′ or Redirect the last output = ‘2’
2
Closed world =’1′ or Open world =’2′
1
The last output was = eee eef eee
List version of sqorder input =
[‘eee’, ‘eef’, ‘eee’]
New word order in sequence with sqorder():
eee eee eee
List version of input in mcworder()=
[‘eee’, ‘eee’, ‘eee’]
New in-word order with worder():
eee
New in-word order with worder():
eee
New in-word order with worder():
eee
New word-sequence order :
eee eee eee
STOP = ‘N’, CONTINUE != ‘N’

You can see that the cognitive entropy replicates with the closed world assumption in the multi-word scenario too.

EXERCISES

Here are some details of objects and operations.

Letters and Numbers

With  ord(‘a’) one can get the decimal code of the letter as ’97’ and the other way around one can translate a decimal number ’97’ in a letter with  chr(97) to ‘a’.  For ord(‘z’) one gets ‘122’, and then one can use the numbers to compute characters which has been used in the program to find random characters to be inserted in a word.

Strings and Lists

There are some operations only available for list-objects and others only for string-objects.  Thus to change and re-arrange a string directly is not possible, but translating a string in a list, then apply some operations, and then transfer the changed list back into a string, this works fine. Thus translate a word w into a list wl by wl = list(w) allows the re-order of these elements by appending: wll.append(wl[r]). Afterwords I have translated the list again in a string by constructing a new string wnew by concatenating all letters step by step: wnew=wnew+wl[i]. If yould try to transfer the list directly like in the following example, then you will get as a result again  list:

>> w=’abcd’
>>> wl=list(w)
>>> wl
[‘a’, ‘b’, ‘c’, ‘d’]
>>> wn=str(wl)
>>> wn
“[‘a’, ‘b’, ‘c’, ‘d’]”

Immediate Help

If one needs direct information about the operations which are possible with a certain object like here the string object ‘w’, then one can ask for all possible operation like this:

>> dir(w)
[‘__add__’, ‘__class__’, ‘__contains__’, ‘__delattr__’, ‘__dir__’, ‘__doc__’, ‘__eq__’, ‘__format__’, ‘__ge__’, ‘__getattribute__’, ‘__getitem__’, ‘__getnewargs__’, ‘__gt__’, ‘__hash__’, ‘__init__’, ‘__init_subclass__’, ‘__iter__’, ‘__le__’, ‘__len__’, ‘__lt__’, ‘__mod__’, ‘__mul__’, ‘__ne__’, ‘__new__’, ‘__reduce__’, ‘__reduce_ex__’, ‘__repr__’, ‘__rmod__’, ‘__rmul__’, ‘__setattr__’, ‘__sizeof__’, ‘__str__’, ‘__subclasshook__’, ‘capitalize’, ‘casefold’, ‘center’, ‘count’, ‘encode’, ‘endswith’, ‘expandtabs’, ‘find’, ‘format’, ‘format_map’, ‘index’, ‘isalnum’, ‘isalpha’, ‘isascii’, ‘isdecimal’, ‘isdigit’, ‘isidentifier’, ‘islower’, ‘isnumeric’, ‘isprintable’, ‘isspace’, ‘istitle’, ‘isupper’, ‘join’, ‘ljust’, ‘lower’, ‘lstrip’, ‘maketrans’, ‘partition’, ‘replace’, ‘rfind’, ‘rindex’, ‘rjust’, ‘rpartition’, ‘rsplit’, ‘rstrip’, ‘split’, ‘splitlines’, ‘startswith’, ‘strip’, ‘swapcase’, ‘title’, ‘translate’, ‘upper’, ‘zfill’]
>>>

In the case that ‘w’ is a sequence of strings/ words like w=’abc def’, then does the list operations be of no help, because one gets a list of letters, not of words:

>> wl2=list(w)
>>> wl2
[‘a’, ‘b’, ‘c’, ‘ ‘, ‘d’, ‘e’, ‘f’]

For the program one needs a list of single words. Looking to the possible operations with string objects with Dir() above, one sees the name ‘split’. We can ask, what this ‘split’ is about:

>>> help(str.split)
Help on method_descriptor:

split(self, /, sep=None, maxsplit=-1)
Return a list of the words in the string, using sep as the delimiter string.

sep
The delimiter according which to split the string.
None (the default value) means split according to any whitespace,
and discard empty strings from the result.
maxsplit
Maximum number of splits to do.
-1 (the default value) means no limit.

This sounds as if it could be of help. Indeed, that is the mechanism I have used:

>> w=’abc def’
>>> w
‘abc def’
>>> wl=w.split()
>>> wl
[‘abc’, ‘def’]

Function Definition

As you can see in the program text the minimal structure of a function definition is as follows:

def fname(Input-Arguments):
     some commands
    [return VarNames]

The name is needed for the identification of the command, the input variables to get some values from the outside to work on and finally, but optionally, you can return the values of some variables back to the outside of the function.

The For-Loop

Besides the loop organized with the while-command there is the other command with a fixed number of repetitions indicated by the for-command:

for i in range(n):
commands

The operator ‘range()’ delivers a sequence of numbers from ‘0’ to ‘n-1’ and attaches these to the variable ‘i’. Thus the variable i takes one after the other all the numbers from range(). During one repetition all the commands will be executed which are listed after the for-command.

Random Numbers

In this program very heavily I have used random numbers. To be able to do this one has before this usage to import the random number library. I did this with the call:

import random as rnd

This introduces additionally an abbreviation ‘rnd’. Thus if one wants to call a certain operation from the random object one can write like this:

r=rnd.randrange(0,n)

In this example one uses  the randrange() operation from random with the arguments (0,n) this means that an integer random number will be generated in the intervall [0,n-1].

If-Operator with Combined Conditions

In the program you can find statements like

if opt==’1′ and opt2==’1′ and opt3==’1′:

Following the if-keyword you see three different conditions

opt==’1′
opt2==’1′
opt3==’1′

which are put together to one expression by the logical operator ‘and’. This means that all three conditions must simultaneously be true, otherwise this combined condition will not work.

Introduce the Import Module Mechanism

See for this the two files:

stringDemo2b.py
stringDemos.py

StringDemo2b.py is the same as stringDemo2.py discussed above but all the supporting functions are now removed from the main file and stored in an extra file called ‘stringDemos.py’ which works for the main file stringDemo2b.py as a module file. That this works there must be a special

import stringDemos as sd

command and at each occurence of a function call with functions from the imported module in the main module stringDemo2b.py one has to add the prefix ‘sd.’ indicating, that these functions are now located in a special place.

This import call does work only if the special path for the import module ‘stringDemos.py’ is visible to the python modulecall mechanisms. In this case the Path with the modul stringDemos.py is given as C:\Users\gerd_2\code. If one wants know what the actual path names are which are known to the python system one can use a system call:

>> import sys
>>> sys.path
>>> …

If the wanted path is not yet part of these given paths one can append the new path like this:

>> sys.path.append(‘C:\\Users\\gerd_2\\code’)

If this has all done rightly one can work with the program like before. The main advantage of this splitting of the main program and of the supporting functions is (i) a greater transparency of the main code and (ii) the supporting functions can now easily be used from other programs too if needed.

A next possible continuation you can find HERE.

 

Example python3: pop0 – simple population program

eJournal: uffmm.org,
ISSN 2567-6458, 2-3.April 2019
Email: info@uffmm.org
Author: Gerd Doeben-Henisch
Email: gerd@doeben-henisch.de

CONTEXT

This is a possible 2nd step in the overall topic ‘Co-Learning python3′. After downloading WinPython and activating the integrated editor ‘spyder’ (see here),  one can edit a first simple program dealing with population dynamics in a most simple way (see the source code below under the title ‘EXAMPLE: pop0.py’.

BASIC PROGRAMMING ELEMENTS

SOURCE FILE

The source code is stored under the name ‘pop0.py’. It is a ‘stand alone’ program not making use of any kind of a library except the built in functions of python3. The external libraries can be included by the ‘import command’.

FUNCTION DEFINITION

If one wants to use the built-in functions in some new way one can do this by telling the computer the keyword ‘def‘ which states that the following text defines a new function.

A function has always a name, some input arguments between rounded brackets followed by a colon marking the beginning of the function-body.  After the colon follows a list of built-in commands or some already defined functions. With defined functions one can make life much easier. Instead of repeating all the commands of the function-body again and again one can limit the writing to the call of the function name with its input arguments.

In the example file we have the following function definition:

def pop0(p,br,dr):
       p=p+(p*br)-(p*dr)
       return p

The name is pop0, the input arguments are (p,br,dr), the used built-in functions are +, -, *, return as well as the =-sign, and the new composition is p=p+(p*br)-(p*dr). This new composition combines known function names with new variable names to compute a certain mathematical mapping. The result of this simple mapping is stored in the variable ‘p’ and it is delivered to the outside of the function pop0 by the return-statement.

NECESSARY INPUT VALUES

To run the program one has to call the defined new function. But because the called function will need some values for the input variables one has first to enable the user to interact with the program by some input commands.

The input commands are informing the user which kind of information is asked for and the answers of the users will be stored in the variables p, br, and dr. The input values can also be ‘casted‘ into different value types like int — for integer — and float — for floating point –.

Here is the protocol of a possible input:

Number of citizens in the start year? 1000

Birthrate %? 0.82

Deathrate in %? 0.92

CALLING A DEFINED FUNCTION

After these preparations one can call the defined new function with the statement pnew = pop0(p,br,dr). Because the input variables have values received from the user the new function can start it’s mapping and can compute the follow up value for the population.

SHOW RESULTS

To show the user this new value explicitly on the screen  one has to use the print function, the counterpart to the input function:  print(‘New population number:\n’,int(pnew)). The print function prints the new value for the population number on the screen.  If you look closer to the print function you can detect some inherent structure: print() is the main structure with the function name ‘print’ and the brackets () as the placeholder for possible input arguments. In the used example the input arguments have two ‘parts’: (‘…’,v). The ‘…’-part allows some text which will be shown to the user, in our case New population number: followed by a line break caused by the symbols \n. The v-part allows the names of variables which have some values which can be printed. In the used example we have the expression int(pnew). pnew is the name of a variable with a value delivered by the pop0() function enabled by the return p function of the pop0() function. (Attention: the ‘return’ function works without ()-brackets to receive input arguments! The variable ‘p’ is an input argument) The value delivered by ‘return p’ is a floating point value. But because we have only ‘whole citizens’ we cast the non-integer parts of the float value away by making the variable ‘pnew’ an argument of another function int(). The int() function translates a floating point value into an integer value. This is the reason that we do not see ‘999.0’ but ‘999’:

New population number:
999

REMARK: Global and Local Variables

This simple example tells already something about the difference between global and local values. If one enters the variable names ‘p’ and ‘pnew’ in the python console of the spyder editor then one can see the following:

p
Out[5]: 1000

pnew
Out[6]: 999.0

After the function call to pop0() the original value of ‘p’ is unchanged, and the new value ‘pnew’ is different. That means the new value of ‘p internal in the function’ and the ‘old value of p external to the function’ are separated. The name of a variable has therefore to be distinguished with regard to the actual context: The same name  in different contexts (inside a function definition or outside) does represents different memory spaces.   The variable names inside a function definition are called local variables and the variable names external to a function definition are called global variables.

A continuation of this post you can find here.

SOURCE CODE: EXAMPLE: pop0.py

pop0.py as pop0.pdf