Python 3 Without Prior Knowledge_ Learn How to Program a Neural Network Within 7 Days
Python 3 Without Prior Knowledge_ Learn How to Program a Neural Network Within 7 Days
Imprint:
Email: Benjamin-Spahic@web.de
Before we get to the first programme, we must first download the package
that contains a graphical user interface and the interpreter. The tool is made
available by various third-party providers, but it is also advisable here to
download Anaconda from the official website.
2. Installation of Anaconda
The current version of Anaconda can be downloaded from
https://www.anaconda.com/products/individual.
For this, we can select the version suitable for our operating
system. Since Windows systems are the most common, the installation is
shown using Windows. The procedure is analogous for the other
platforms.
Figure 2 Anaconda Setup
The programme code is written in the left-hand window, the console, the
interface between the user and the computer, can be found in the lower
right-hand window. Error messages, for example, are output in the console.
1. Comments
Comments serve the clarity and structure of a programme. If we write a
programme and then do not use it for years, it will take us a very long time
later to understand the functions again.
Therefore, comments are enormously important for a quick understanding
of the function of a programme.
Comments serve as memory aids, structural elements and to explain the
code.
2. Docstrings
For better clarity, it is advisable to provide a description of the programme
in addition to the comments. These descriptions are called docstrings and
make it easier for the programmer to understand the background and
functioning of the programme. Docstrings can also be read out with special
functions without having to access the source code.
As seen in the example above, the comment section of the doc string is
opened and closed with three single ''' or three double quotes "'''. The
function is exactly the same.
“““ Everything inside the inverted commas is interpreted as a heading/description.
“““
3. Instructions
Instructions form the core of a programme. "Instruction" is an umbrella
term for, for example, arithmetic operations or input or output commands at
the console. Defining variables, calling functions or breaking a loop is also
an instruction. With instructions, it is advisable to append a comment again.
If you want to output the double inverted commas as well, you can put
single inverted commas in front of them.
As already mentioned, we can not
print('"Hello World"') #puts out "Hello World
only output pure text, but also numbers or whole calculations.
Unlike text, the inverted commas are omitted when outputting a calculation.
Thus, the result of the mathematical operation is output and not the text
characters of the calculation. An example illustrates this: print("3+4") #The
output is 3+4
print(3+4) #7 is output
5. Variables
Variables are indispensable for almost every Python programme. They are
numbers, characters or whole texts that can be changed during the runtime
of a programme. They are used to store values. By naming the variables, we
can retrieve the value during the course of the programme, for example to
use it in a calculation.
A variable consists of a name and a value. We can imagine the variable as a
box on which the name of the variable is written. The content is the value of
the variable. This understanding will be important later.
temp2 = 30
…
The variable temp1 (for example, indoors) is assigned the value 20. The
variable temp2 (for example, outdoors) is assigned the value 30.
The variables must be given unique names; a name may not be
The text is
simply added to the variable by placing it in inverted commas.
But what happens when we want to save or output a quote?
For this, the interpreter must be informed that the inverted commas are to
be regarded as text. To do this, we write a backslash (\) in front of the
inverted comma.
This can be called up with the key combination AltGr+ß. This procedure is
also called masking.
The inverted comma is masked as follows: variable = 'This inverted comma \'
has been masked'.
print(variable)
6. Data types
In every programming language, there are different types of variables that
differ in terms of their height (memory requirements) or content.
This is referred to as data types. Different data are classified according to
their type and function. A number, for example, has a different type than a
word. But why do we need this distinction at all?
For example, if a variable can only contain the values 0 or 1, a single
memory cell (bit) is sufficient to map the information. As an example, a
coin toss can be chosen whose result can only take 1 (number) or 0 (heads).
It therefore makes no sense to provide the variable with 2, 3 or 10 memory
cells. Therefore, the variable is assigned a data type that only occupies one
memory cell and can only accept two values.
Besides housekeeping with storage units, there are other reasons why it
makes sense to store data in different types.
For example, numbers can be calculated with the help of operators.
is known and logically familiar to everyone. There is therefore
a separate type for the data type "integers".
In other programming languages, you have to tell the compiler which data
type a variable is assigned to.
Not so with Python. The advantage of Python lies above all in the simple
assignment of data types. Python recognises by means of the variables
themselves which data type is to be used. A data type is automatically
assigned by the content or the way the content is written, without having to
specify it separately.
x = 5 Variable is saved as an integer x = 5.00 Variable is saved as a floating point
number (float).
With Spyder you can display the variables and their contents
as well as the data type. This is especially helpful when searching
for errors. Under the item Variable Explorer in the upper right
field, the variable name, the data type as well as the length and
content of the variables are displayed.
Figure 12 Displaying data types in Spyder In the example shown, the data type is
integer (int).
It is advisable to consider a few things about the data types. What type
results when we calculate 6 divided by 3? What type when we divide 7 by
3?
7. User input via input()
We have already learned how to output data to the console. Next, we will
look at how we can request data from the user.
The function eval() saves the read-in data under the correct
data type. Because we remember that we cannot calculate with
string variables.
Now it gets a bit more complicated: We pass the complete input() function
as an argument to the eval() function. We nest the functions inside each
other.
If we want to store an entered value in a variable with the appropriate data
type, the complete command is: x= eval(input("Please enter a number between 0
and 10")) This will output the prompt, then read in the number and convert it
to the appropriate data type (integer) and store it in the variable x.
10. Operators
We have already learned about variables and data types and can not only
output the stored values with the print() function, but can also calculate
with them or compare different variables with each other.
Various operators are used for this purpose that can be divided into
different classes. Some of the operators are logically understandable, such
as the plus and minus signs.
= Allocation x=3
+ Addition x=y+2
- Subtraction x=y-2
* Multiplication x=y*2
/ Division x=y/2
In addition to the arithmetic operators, which are used for calculation, there
are other operators, such as the comparison operators.
Comparison operators
Operator Meaning Example Result
< Smaller? 3<5 True
<= Smaller equal? 5<=3 False
> Bigger? 5>3 True
>= Bigger equal? 5>=3 True
== In a moment? 5==4 False
!= Unequal? 4!=5 True
x==5 # It is checked whether x contains the value 5. The result is True or False The
command print(3<4) returns "True" as the result.
11. Functions
Some functions have already been introduced, for example the print()
function, which outputs data to the console. Most people remember
functions from school lessons: is an example of a function.
The basic idea is that we pass a number x to the function and then get a
number y back.
The example creates a list with the three elements and saves the list in the
variable dataset. The variable now has the data type list. Tom stands for the
name, 26 for the age and 1.84 for the height.
Normally we would have had to create three separate variables. So, the
advantage of lists is obvious.
Using the example, we can also derive other properties.
As you can quickly see, a list can contain different data types,
here string/str, int and float. Each element of the list automatically
receives an index, starting at zero.
If you want to query individual elements of a list, the index must be written
in brackets.
How can we interpret the index -1 and -2? There is no negative list element,
is there?
Well, the lists can quickly have many hundreds of items or new items can be
added all the time.
If we want to access the last elements, we can enter the last index. However,
sometimes the index is not known or it is very large. Therefore, in Python,
negative indexes can be used to select the last elements appended.
list = [0,1,....,9999999]
#We want to read out the 999,999,999th element list[9999999]# works list [-1]
#better Calculating with lists: Lists can contain elements with different
types. However, we can also calculate with the whole list, i.e. the complete
"data set" at once. For example, we can add any elements to a list, overwrite
them or delete them. As an example, let's take our list with the name, age
and height of a person: dataset = [ "Tom", 26, 1.84]
Through the command dataset[1] = 27
If one wants to query an element of a sub-list, for example Kevin, first the
index of the sub-list and then the index of the element is given.
In the example, the element Kevin is in the third sub-list (index 2) and is in
the list again the first element (index 0).
Creating a list with range() The function range(x) creates a list with
the values zero to x. The command list = range(10) assigns the values
[0,1,2,3,4,5,6,7,8,9] to the list.
It must be noted that no element with the data type list is created, but an
element of the data type range. In the context of this book, this is equivalent
in its use.
For a console output, a type conversion can take place so that the individual
elements are output.
list = range(10) # type range print("Output as range element:",list) list2=list(list)
#Type conversion to list print("Output as list element:",list2)
Figure 18 Comparison of range and list A look at the variable explorer confirms the
type conversion.
2. Edit lists
You can do more than just calculate with lists. There are also functions that
simplify the editing of lists considerably.
As lists are a very common and simple tool for data storage, there are many
tools to simplify their use, such as methods.
Methods are special functions that cannot be used for all data. The exact
difference is explained in the chapter Classes, as this is not necessary for the
present understanding and application.
With the del command for deleting a list, a method has already been
introduced, but not marked as such.
In addition, there are many other methods for editing a list. For this it is
important to know the method names.
.sort()
Sorts the list by value, either in ascending order
(numbers) or alphabetically (strings).
reverse()
Mirrors all values of a list, the last value becomes the
first, and vice versa.
Furthermore, there are operators that can be applied to lists. We can compare
these operators with the +,-* and / operators that we can apply to numbers.
The following table shows the calls and function of the operators
x in list Returns True if the element x occurs in the list.
Otherwise False
x not in list Returns "False" if the element x occurs in the list,
otherwise "True".
len(list) Outputs the length (number of elements) of the
list.
min(list) Returns the smallest element.
max(list) Returns the largest element.
sum(list) Returns the sum of the list.
Lists are a simple and widespread way to store related, variable data. Lists
make it easy to calculate and use different methods. Tuples are a similar way
of storing data.
3. Tuple
Lists always contain variable data, which makes working with them very
convenient, but this variable data also occupies additional memory. In
addition, more memory must always be kept free than is initially needed if
the variable changes and becomes larger.
However, if we only have unchanging values, we use so-called tuples
instead of lists. Tuples behave very similarly to lists. However, the values of
the elements cannot be changed. To create a tuple, the square brackets of the
list are omitted. The commas still separate the elements from each other.
tuple = "Tom", 26, 1.84
4. Dictionaries
After the handling of lists and tuples has been explained, another very
similar variant for data structuring is discussed below: dictionaries.
We are now familiar with lists. The big disadvantage of lists is that the user
has to know what each index stands for.
In the example of our data set of Tom, it was determined that index 0 stands
for the name, index 1 for the age and index 2 for the height.
dataset1 = ['Tom',26,1.84]
Here, name, age and height are the keys and Tom, 26 and 1.84 are the
values.
Instead of specifying the index (as with lists), the desired value
can be retrieved via the key.
print(person1['name']) print(person1['age'])
print('The temperature is 20 °C') elif temp1 == 25: #If temp1 has the value 25
print('The temperature is 25 °C') elif temp1 == 30: #If temp1 has the value 30
print('The temperature is 30 °C') else: #In all other cases print('The temperature is
neither 20, nor 25, nor 30 °C') The if-condition can also be used in conjunction
with a string.
x='hello if x == 'hello': print(" Hello World") # if the var. x contains the character
string "Hello".
Check for yourself: When is the if-condition fulfilled and when is it not?
If 3 > 5 : if 3 < 5 : if 3 : if 0 : if not 3 : if 2==2 : if (4>2) && (3<1) : Solution:
1. Not fulfilled. Since 3 is less than 5, the if statement is not executed.
2. Met. 3 is less than 5, therefore the if statement is executed.
3. Met. 3 is a non-zero number, so it is interpreted as "true" and the if statement is executed.
4. Not fulfilled. The number zero is interpreted as "false" and the if statement is not executed.
5. Not fulfilled. The number three is interpreted as true but negated, therefore the if statement
is not executed.
6. Fulfilled, because 2==2 is a true result.
car_brands = ['VW','Audi','Porsche','BMW','Skoda']
11. Solution
As with most programming tasks, there is no model solution here. Every
programmer has his or her preferences. One prefers to work with lists,
another with dictionaries. One programmer prefers for-loops, another while-
loops.
Therefore, besides the following code, there are many different possible
solutions for the described task. If the programme gives the desired result
with the execution, the code is correct.
First, we create the list. Then the user is asked to enter the fruit he is looking
for. Since the list only works with indexes, the fruit must be converted to the
appropriate index. An if-query is used for this.
The same task becomes much easier when using dictionaries.
'''WITH DICTIONARIES'''
stock = {'banana':501,'apples':112,'mango':52,'kiwi':96 }
print("Please enter the desired fruit") # The fruit corresponds to the index and does
The last print() command is a little more complex. First, the string ("There
are still") is output.
The element then appears with the index that was previously defined.
After that, the previously queried fruit, which was stored in x or index, is
output. At last, the string present is displayed. In sum, the execution of the
programme looks like this:
If a
def xsquare(x): return x*x# x*x is calculated, then the value is returned
function returns values with the help of the return command, the function is
also automatically terminated. Therefore, the return command must always
be the last command of the function.
Several return commands are also possible, for example within an if
statement.
For this, let's look at another example where the return command is used.
A temperature value is passed to the following function.
def weather(temp): # temp is transferred if temp > 30: return "It's too warm"
elif temp < 15: return "It's too cold"
else: return "It is pleasant"
''' Main Programme'''
x= eval(input("How many degrees is it? \n")) #User input y = weather(x) # The return
string is stored in y print(y) # And then output We see that return values are not
limited to numbers. Strings are also possible. However, the return value
depends on whether the if statement is fulfilled or not.
Depending on which case occurs, different strings are returned.
When you create a function, you can assign default values to the
arguments. If no value is passed when the function is called, the
default value is taken. If a value is passed, the default value is
overwritten.
As an example, we extend the function xsquare() so that every power can be
calculated. The function thus calculates the term x to the power of n
The function requires two arguments, the base x and the exponent n.
Next, we want to set n to 2 by default, i.e.
def x_power_n(x,n): y = x**n return y
if you only pass x, n will get the value 2. For this, we set n=2 when defining
the function.
def x_power_n(x,n=2): y = x**n return yWe call the function, passing only one
value. This is assigned to the local variable x in the function.
The function call print(x_poower_n(3)) # x=3 n=2 (default) consequently
outputs 9, since
On the other hand, if the value for n is also passed, the default value of 2 is
overwritten.
print(x_power_n(3,3)) # x=3 , n=3
spends 27, as
We have to make sure that all arguments with default values are at the end
of the input.
Why this is so can be easily explained with the example: def
x_power_n(x=5,n): Here x is set as 5. Now it would be assumed that if we only
pass a number, the number will automatically be assigned to the variable n.
However, this is not always the case.
The call
print(x_power_n(3)) # x =3 , n = undefined overwrites the variable x to 3, as this
comes before the n.
Since no further value for n was specified afterwards, an error message
appears that too few arguments have been passed.
SyntaxError: non-default argument follows default argument.
'Argument without default value follows an argument with default value'.
To avoid this, this error is automatically detected and the error message
appears even before the function is executed.
15. Libraries
Libraries are an advantage of the open-source concept that Python follows.
We also find the familiar functions like input(), eval(), print() or range()
here again.
The standard Python libraries also consist for the most part of normal
modules, as explained in the previous chapter. If possible, one should
always use these libraries, as this can save a lot of work.
In addition to built-in libraries, Python also uses built-in constants such as
True/False or built-in types such as lists and dictionaries.
These built-in elements simplify programming and the
introduction to Python, even for newcomers.
The standard libraries or the functions they contain are listed under
https://docs.python.org/3/library/index.html. It is advisable to always look
up a project first to see if a suitable function or entire modules are already
available.
Alternatively, you can usually find the right function for your project within
a short time using the search function within the Python page or via the
search engines.
The marks for the exercise are already listed in the following table.
Maths_s corresponds to the written maths mark, Maths_m to the oral mark.
Subject Maths_s Math_m German_s German_m English_s English_m
Mark
- Addendum: Save the functions in a separate file and include them via
an import command.
17. Solution
As always, there are several possible solutions. The following programme
shows only one possible way.
First, we save the grades from the table in a dictionary. The keys of the
dictionary are the names of the subjects.
notes = {'ma_f':1.3,'ma_m':2, 'de_f':2.5,'de_m':2, 'en_f':3,'en_m':2.5
Then we create a function that calculates and returns the average grade of
each subject.
def noteSubject(font,mouth): return (2*font+mouth)/3
Two values are passed to the function. The return value is the average grade
of the subject.
For example, if we want to determine the maths grade, we call the
noteFach() function and pass the corresponding grades from the dictionary.
To obtain the value of the written maths grade (1.3), the key is specified
notes['ma_f']
Similarly, the value noten['ma_m'] is called for the oral maths grade (2.0).
It makes sense to round the
ma_tot= noteSubject(notes['ma_f'],notes['ma_m'])
grade to a maximum of two decimal places. The function call is thereby
extended to:
ma_tot=round(noteSubject(notes['ma_f'],notes['ma_m']),2) Similarly, we call up
the function for all subjects.
de_tot=round(noteSubject(notes['de_f'],notes['de_m']),2)
Thus we have stored
en_tot=round(noteSubject(notes['en_f'],notes['en_m']),2)
the three grades of the subjects in the variables ma_tot, de_tot and en_tot.
Then the function for determining the average grade of the three subjects
can be created.
The function is named noteGes() and three subjects are generally passed to
it.
def noteTot(subject1,subject2,subject3): return (subject1+subject2+subject3)/3
After the definition, the function is called. To do this, we pass it the three
previously calculated average grades of the subjects. At the same time, we
round the grade to two decimal places.
n_tot=round(noteTot(ma_tot,de_tot,en_tot),2) The last thing we do is output all
the values to the console.
print("The overall grade in maths is:",ma_tot) print("The overall mark in German
is:",de_tot) print("The overall grade in English is:",en_tot) print("The total score
is:",n_tot) Addition:
The two functions noteSubject() and noteTot() are saved in a module called
modul_noten.py. The file is in the same folder as the main programme.
In order to be able to use the functions again, we have to use the module
in the main programme.
import module_notes
Then we have to adapt the function calls. The module is
written in front of each function.
ma_tot= module_notes.noteSubject(notes['ma_s'],notes['ma_m']) We remember
that there is a better alternative than specifying the whole path for each
function call. Instead, we reassign the function after importing.
import module_notes
1. Classes
Classifying objects from the real world helps our brain to work more
effectively. Within fractions of a second, it recognises similarities and
differences.
Unlike functions, the class does not (yet) need any transfer values.
Accordingly, the round brackets, as we know them from functions, are
omitted.
def __init__(self,name,age,height,):
self.height=height
class human:
'''Creation of the human Object'''
def __init__(self,name,age,height,):
'''The arguments of the human being are defined
(string) name: name of the person
(int) age: age of the person
(float) Height: Height of the human being
'''
self.name=name
self.age=age
self.height=height
Thus, the first object of the human class has been created. We can read out
the individual attributes of the object by naming the object and the desired
property.
print(human1.name)
print(human1.age)
print(human1.height)
Tom
26
1.84
In the example, the name was changed from Tom to Tim. From a
programming point of view, this is not a problem, but logically it is.
Because renaming a person does not make sense (except in individual
cases). Since an object represents a real object, we have to address this
problem.
Python also offers a method for protecting certain attributes of a class. For
this we look at the division of attributes into public, protected and private.
This is particularly useful for security reasons, so that sensitive data cannot
be read out by a simple command.
To protect variables from the outside world, you can set them
to "public", "protected" or "private".
But how do we implement this correctly? The previous definition of
attributes, where only the variable name is given, shows a public property
of the object.
self. name=name# this attribute is freely accessible/public
outputs an error.
In the example, it does not make sense to change the name, but access is
also no longer possible, so that it cannot be issued or read out for other
purposes. You have gained security, but you have lost functionality. That
was not the original idea why we encapsulated variables.
As always, there is a solution in Python.
You can introduce so-called methods within a class. With methods,
encapsulated attributes can also be processed or output, as we will learn in
the following subchapter.
3. Methods
Methods are very similar to functions in terms of structure. However,
methods are defined within a class and are also bound to it. This means that
you cannot use a method outside the class, for example in the main
programme, with other variables. Methods can only be called with an object
of the class.
The constructor __init__() was our first method that we got to know.
Since it is an internal function, the method is created with the signal word
def. Then we assign an individual name to the function. In our case, the
class human is to receive the method Greet.
Again, arguments can be passed to the method in round brackets.
Here, too, the signal word self must be passed as the first value. This shows
the interpreter that this is an internal function, a method.
def greet(self):
class human:
'''Creation of the human Object'''
def __init__(self, name, age, height):
'''The arguments of the human being are defined
self.__height=height
def greet(self):
human1.greet()
The method setAlter requires the new age as a further transfer variable.
The function is again called by the object.
human1=human("Tom", 26, 1.84) #Creates the object human1
print("Age:",human1.getAge()) # Returns the age
Methods can also have a much more complex structure. Just like functions,
they are not limited by code.
Another standard method is the del method.
5. __del__ method
We already know the del function from lists and variables. It can be used to
delete not only variables but also objects.
del human1
The object is removed from the memory. The method is integrated in the
interpreter, similar to a standard function, and was automatically inserted
during installation. This means that the method can be applied to any class
and does not have to be defined in the class.
We can extend the del method within a class, for example, to trigger further
actions when an object is deleted.
For this purpose, a function with the name __del__ is created within the
method.
Figure 36 Output when deleting the object via the del method
This explains the most important properties of classes and methods. Now
it's time for the next exercise, in which we will train the encapsulation of
variables and the creation of methods.
6. Exercise - Password protection
As already mentioned, object-oriented programming is one of the core
elements of Python. Therefore, we want to practise dealing with these
elements.
For this purpose, the human class is to be extended by the attribute
Password. All data such as name, age and height are to be set to private, so
the attributes cannot simply be read out or changed.
Then create a method that outputs all encapsulated attributes after entering
(passing) the password. If the password was entered incorrectly, an error
message appears.
The distinction whether the password is correct or incorrect is to be realised
with an if-query.
7. Solution
First, we create the familiar class human. Then we create the constructor
and pass the attributes of the class to it. In addition, we add the new
attribute password.
class human:
'''Creation of the human Object'''
'''
self.__name=name #Save the passed variables
self.__age=age
self.__height=height
self.__password=password
Since the class has been extended to include the attribute password, one
more argument must also be passed. In the example, all attributes are
private. It is only necessary for the password attribute.
The method for querying the password must be passed a variable password.
'''
if password==self.__password:
else:
print('The password was not correct')
With the help of the if-query, it is checked whether the passed variable
matches the internal password. In the positive case, the data is output,
otherwise the error message appears.
To test the method, we create an object human1 of the class human. The
attribute password is set with Python3.
Then we ask the user to enter the password. We store this in the variable
pass_in.
pass_in = str(input("Enter the password \n ",))
human1.checkPassword(pass_in)
class human:
'''Creation of the human Object'''
self.__name=name
self.__age=age
self.__height=height
self.__password=password
def checkPassword(self,password):
'''Checks an entered password
if password==self.__password:
print('The password was correct')
8. Class variables
All variables or attributes of a class were previously defined in the __init__
method. This means that they apply specifically to each object created. This
is also logical, after all, each object has its own individual attributes.
However, there are also properties that affect an entire class as a unit. In
our example of a human being, this would be the number of persons
created. The number of existing people is a variable that is not object-
dependent but applies to the whole class.
In Python, a count variable can be created in the main programme that is
incremented each time a new object is created.
However, it is also possible to have the counter variables incremented
automatically when an object is created. To do this, a global class variable
is defined within the class. This is placed directly after the class call, before
the constructor.
class human:
...
The variable number is also available for each object created without
having to pass it separately.
human1=human("Tom", 26, 1.84, "Python3")
print(human1.number)
The global variable number is still the same for each object -
namely 0! The variable is not yet changed and therefore does not
show the current number of created objects/data sets.
Likewise, the value of the class variable can be accessed directly via the
class. For this, no object must be created beforehand. To do this, the name
of the class is written, followed by a dot and the variable.
print(human.number) # Also outputs 0
Class variables become interesting when they are combined with methods.
For example, the __init__ and __del__ method can be extended so that the
count variable is counted up or down when an object is created or deleted.
human.number =human.number +1
For the expression x=x+1 one can also write x+=1 in
abbreviated form and analogously for x=x-1 the expression x-=1
This shortens the command to
human.number +=1
Each time an object is initialised, this message with the new number is also
output.
The human class was extended with the methods and the class variable.
class human:
'''
human.number+=1 # Increase class variable by 1
print('A new human being has been born, they now exist',human.number,
"humans")
self.__name=name #Save the passed variables
self.__age=age
self.__height=height
self.__password=password
def __del__(self):
human.number-=1 # Decrease class variable by 1
print("The object was successfully deleted")
print('A human has died, they now exist',human.number, "humans")
Three objects are created for illustration.
human1=human("Tom", 26, 1.84, "Python3")
del human1
del human2
del human3
Class variables are a tool to define a common attribute of all objects. This is
exactly what the next programming exercise is about: extending the human
class.
The calculation can take place in the constructor after an object has been
created.
Furthermore, the same calculation must be performed after an object has
been deleted.
10. Solution
First, the class variables are created and assigned the value zero. The
variables were abbreviated in a meaningful way:
class human:
'''Creation of the human Object'''
self.__name=name
self.__age=age
self.__height=height
self.__password=password
To calculate the total height of all objects, we use the passed variable
height. Alternatively, self.__height is also suitable, as the variable was
assigned the same value two lines earlier.
The values are summed up and then the value hgt_avg is calculated. We see
that by calling human._hgt_avg we can access the desired value.
Optionally, we can add an output. Here, the average height is again rounded
to two decimal places.
print('The average height is now', round(human.hgt_avg,2),)
Then we perform the same procedure for the __del__ method. This is
completed with the same commands. First, the total height is calculated and
then the average height.
def __del__(self):
human.number-=1 # Decrease class variable by 1
del human1
Classes, objects, object and class variables are now known. Next, we will
look at another major topic of object-optimised programming, the
inheritance of classes.
11. Inheritance
The division of objects from the real world into classes is clear and easy to
understand. When we see a new object, for example a new person, the brain
looks for similarities and differences to objects we already know and have
memorised. These similarities are compared with empirical values, whereby
a classification, better known as "the first impression" of a person, is made
within a few seconds.
Our world is a huge, complex system in which many classes influence each
other. That is why our brain arranges objects not only into individual
classes, but various subclasses and superclasses.
As an example, there are different subclasses in the superclass human. The
classification can be based on geographical origin (Asians, Europeans,
Africans, ...), age (babies, children, adolescents, adults, ...) or other aspects
such as profession (artists, engineers, programmers, ...). One also speaks of
child classes and parent classes.
The individual child classes all have the same attributes as the superclass,
but can also have additional, individual class attributes.
If one transfers this connection to object-oriented programming, one speaks
of inheritance.
The subclasses inherit attributes and methods of the parent
class. Before creating a subordinate class, the superordinate class
must first be created.
The creation of the subclass is identical in structure to the creation of the
parent class. However, the name of the superclass must be specified after
the class name of the subclass.
As an example, we create a subclass of the class human. This contains
enthusiastic Python fans, so an appropriate name for the child class is
programmer.
class programmer(human):
After the subclass has been created, the constructor of the class is listed
again. In this, the arguments of the superclass and optionally others for the
subclass are passed. In the example, the subclass programmer receives an
additional attribute. The attribute prog_lang stands for a programming
language of the programmer.
def __init__(self, name, age, height, prog_lang):
After the object has been initialised, the attribute prog_lang can be defined.
self.prog_lang=prog_lang
'''
def __init__(self, name, age, height):
self.__height=height
class programmer(human):
self.prog_lang=prog_lang
def getProg_lang(self):
'''
Sets new programming language
'''
self.Prog_lang=prog_lang_new
def __del__(self):
print('Unfortunately we have lost a programmer')
programmer1=programmer('Tom',26,1.84,'Python')
print(programmer1.getProg_lang())
del programmer1
This solution works, but the look is still unattractive with multiple classes
and many user interfaces do not support this function.
The entire module is imported. In order to access the classes, the path must
be specified. This is also familiar to us from procedures such as outsourcing
functions to modules.
# Access via module name.class name
human1= module_classes.human("Tom", 26, 1.84)
This notation is very cumbersome, so there are still alternative variants for
importing the classes, which can also be applied to modules with functions.
The command from module name import class name can be used to import
a single class.
from module_classes import human
The big advantage here is that we don't have to specify the path. We can use
the class as if it were in the same programme.
human1= human("Tom", 26, 1.84)
Here, too, we can use the classes without specifying module names
# Access via module name.class name
human1= module_classes.human("Tom", 26, 1.84)
The disadvantage with this variant is that one must specify each class
individually. If one wants to use several classes and child classes, all of
them must be listed.
A shortcut for specifying all classes is provided by the asterisk operator.
Through the command
from module_classes import*
all classes of the module module_classes are loaded and can be used
without specifying the module.
The disadvantage of using this method is that when importing several
modules, one does not know in which module the class used is located. In
addition, it is confusing for the understanding of the programme code if an
object with a class is suddenly created in a line, which was previously
nowhere to be seen concretely. This can be counteracted with detailed
documentation. Nevertheless, if only a few classes are needed, it is
advisable to import them by naming them specifically.
from module_classes import human, programmer
This command makes it clear that the classes human and programmer come
from the module module_classes. In addition, our programming
environment Spyder warns us (no error) that we have used the star operator.
The outsourcing of classes is largely identical to that of functions. In the
next exercise, we will once again focus on classes and subclasses. A well-
known game of chance will be used.
class lottery_player:
'''
'''
def __init__(self,name,numbers):
'''
The player's arguments are defined
'''
def check_win(self,win_figures):
'''
lotto_numbers =range(1,50)
win_figures = random.sample(......)
14. Solution
First we import the module random so that the function sample() can be
used. The module was automatically downloaded when we downloaded
Anaconda. Since it is not part of the built-in libraries, we have to import it.
import random
class lottery_player:
'''
Class variables
'''
def __init__(self,name,numbers):
'''
'''
self.name=name
self.numbers=numbers
Thus, the class has been created, but the method check_gewinn is still
missing.
The winning numbers are passed to the method in a list with six elements.
Each element of our own list Numbers is matched with the winning
numbers. A for loop is used for this. If the element is the same, the count
variable hit is increased by one.
def check_win(self,win_figures):
'''
The player's lottery numbers are
After the winning numbers/lotto numbers have been "drawn", three lottery
players are created.
These receive six individual lucky numbers, which we can determine
ourselves. In the example, six consecutive numbers were chosen for
simplification.
'''Generating the Players'''
lottery_player1=lottery_player('Tom',[1,2,3,4,5,6])
lottery_player2=lottery_player('Lisa',[7,8,9,10,11,12])
lottery_player3=lottery_player('Kevin',[13,14,15,16,17,18])
accessed the name of the player and the number of hits of his numbers by
the method call
lottery_player1.check_win(win_numbers)
checked. All this is output in a print command for all players equally.
'''Issue of the Winners'''
print("Winning numbers are:",win_numbers)
print(lottery_player1.name, "has",lottery_player1.check_win(win_numbers),
"correct numbers")
print(lottery_player3.name, "has",lottery_player3.check_win(win_numbers),
"correct numbers")
Remark:
In general, it makes more sense to abbreviate variable names, for example
lt_pl1 instead of lottery_player1. However, the names of the variables were
chosen to be very detailed so that the programme code is easier to
understand. Especially at the beginning, this is more important than the
compactness of the programme.
This brings us to the end of all the important elements and building blocks
of Python programming. Variables, lists, loops, classes, inheritance - we
have covered all the topics and programmed small examples.
Everything that follows now is simply importing and applying already
existing functions. This is also the focus of Python. We can use existing
modules to solve almost any problem.
After we have covered the basics, we will deal with the visual design of the
programme, for example by means of graphical user interfaces. To do this,
we only need to be able to use the existing functions or methods correctly.
There are many different possibilities and libraries available for this. In the
following chapter, we will use the most frequently used library, which is
also the most suitable for beginners.
6. Create graphic surfaces
Until now, communication with the user of a programme was only realised
via the console. The advantages of this are that one can start programming
quickly and work in a very code-oriented way. However, the display is not
up to date and the input and output options are very limited. If, for example,
you forget to enter an inverted comma or write a variable in lower case
instead of upper case, such an error can mess up the whole programme. It
makes more sense to create windows where the user can select predefined
answers by simply clicking a button.
Therefore, in this chapter we deal with a library that can create a graphical
user interface.
button3=Button(window,text='Button3',width=10) button3.grid(row=1,column=0)
button4=Button(window,text='Button4',width=10) button4.grid(row=1,column=1)
window.mainloop()
The buttons are laid out in a total of two rows and two columns.
If we use the grid manager, it places the objects in the desired positions.
This means we no longer need the pack() function.
We must never use the grid() and pack() functions in the same
window. Otherwise an error will be displayed.
To load the picture, a variable img is created. The photo is passed to it. This
is possible with the function PhotoImage(). We have to set file=r (read) and
specify the path of the image to be loaded.
img = PhotoImage(file = r "C:\Python_Exercises\python.png") To adjust the
height of the image, the command
img1 = img.subsample(2,2)
is used.
This reduces the resolution and thus the height of the image. If
we use a different image, this command must be adapted
accordingly.
Trial and error usually helps. The command is not necessary for the
example. The image is stored in the variable img1. To display it on the
window, we use the Label() class. We pass the variable to it.
label_img=Label(window, image = img) Label_img.grid()
We then combine the individual code parts into one overall code.
from tkinter import *
window = Tk()
window.title("Python without prior knowledge") img = PhotoImage(file =
r"C:\Python_examples\Chapter 6 - Tkinter\python.png") label=Label(window, image
= img) label.grid()
mainloop()
With the importing of images, some colour has literally come into the
display for the first time. This is exactly where we want to continue by
highlighting objects such as text fields in colour.
The attributes for fg and bg are passed as a string. Font requires the font as
a string and the height as a number.
As an example, three
window,text='Large',fg='white',bg='red',font=('Arial',48)
different text fields are created, each with a different background colour,
font colour, font height and font style.
from tkinter import*
The top field has a red background with white lettering. The font is Arial
and the font height is 48 points.
The second box has a green background with pink lettering. The font style
is Roman and the font height is 32 points.
The last field has a yellow background with black lettering. The font style is
Bold and the font height is 16 points.
Figure 52 Displaying different font heights, colours and fonts
The appropriate attributes, such as the colours and fonts that can be used,
can be found on the official tkinter page:
https://docs.python.org/3/library/tk.html
For existing objects, the attributes can also be read out or overwritten.
The method cget is used to read out an attribute. Overwriting a value is
done with the method config.
print(label1.cget('font')) #Font values are read and output label1.config(font=
('Roman',32)) #Font is overwritten print(label1.cget('font')) #Font values are read
and output
With this, we have gone through the most important building blocks for the
presentation of a GUI. In the following exercise, we will apply what we
have learned to create a visually appealing GUI.
7. Exercise-Calculator
In the following, the graphical representation is to be practised on the basis
of the creation of a pocket calculator. The task for this is as follows: 1.
create a heading "Calculator"
2. create two input fields, each with a number entered.
Create four check boxes with the names plus, minus, times and divided. The
choice of checkbox determines the operator to be used.
Create an input/output field for the result.
Create a button that calculates the result and inserts it into the input field.
6. Optional: Set font heights, background colours and other attributes for all
elements. In addition, incorrect entries can be intercepted if more than one
or no checkbox is selected.
The result could look like this:
Figure 54 Example solution graphical representation of a calculator
8. Solution
First, we create the basic framework. The libraries are imported.
window= Tk() #Creates the object window.geometry('570x280') # H=280, W=570
If only one checkbox is active, the values in the input fields are read in.
Since they are stored as strings, a type conversion to integer must still take
place.
else:
output='Select: +,-,*,/'
output1.insert(0,output)
The last step is to place all objects. The grid manager was used for this. The
place manager works in the same way. The entire programme code
develops as follows:
from tkinter import* #imports all functions of the module def output():
else:
number1=int(input1.get()) #Adapt data type of string number2=int(input2.get()) if
check1.get(): output = number1+number2
elif check2.get(): output = number1-number2
elif check3.get(): output = number1*number2
label1.grid(row=0,column=1,padx=10,pady=10,columnspan=2)
input1.grid(row=1,column=1,padx=10,pady=10)
input2.grid(row=1,column=2,padx=10,pady=10)
checkbutton1.grid(row=2,column=0,padx=10,pady=10)
checkbutton2.grid(row=2,column=1,padx=10,pady=10)
checkbutton3.grid(row=2,column=2,padx=10,pady=10)
checkbutton4.grid(row=2,column=3,padx=10,pady=10)
button1.grid(row=3,column=1,columnspan=2,pady=10)
output1.grid(row=4,column=1,columnspan=2,pady=10) window.mainloop()
That was not only the end of the exercise, but also of this book - almost!
Because a chapter that is becoming more and more important should not
remain unmentioned. It shows the possibilities that can easily be
implemented with Python. We are talking about artificial intelligence and
neural networks. Most companies already use Python as an industry
standard for neural networks and machine learning.
7. Artificial intelligence and neural networks
One of the topics that has been on everyone's lips for years is artificial
intelligence, or AI for short. In connection with the buzzword AI, terms
such as neural networks, machine learning or deep learning are often
thrown into the room.
It therefore makes sense to first explain the different terms.
If we fed an AI all the data that has ever existed and trained it
infinitely, the AI would be able to predict everything that would
ever happen. It would be omniscient. It could predict share prices,
when and where a person would be born or how long we would all
live.
Admittedly, this is an absurd example that will probably never become real.
A computer could never process so much data and training would take an
infinitely long time. But this example shows us where the journey is
heading. More and more information, more and more computing power. It
is not for nothing that Google, Amazon and others are collecting more and
more user data and expanding their data centres.
The idea of an
all-knowing
artificial
intelligence
seems a little
scary at first, but
we should not
only see the
negative. AI is an
opportunity. We
could achieve
breakthroughs in
science,
autonomous
driving is on the horizon and maybe the next super-computer will find a
cure for cancer. In any case, artificial intelligence is an area where there is a
lot of potential. It is worthwhile getting to grips with it. So we now know
what an AI is capable of and what advantages it offers. Let's now take a
look at how an AI or a neural network is built.
The connection between the two series should be clear to everyone right
away. Each element of the second row is three times the matching element
of the first row. However, an AI does not know this at the beginning.
The AI first tries to find random correlations
Figure 59 First training run of an AI
between the data sets. To do this, it takes an element from the input data
series and predicts an output value for this value. Then the AI compares the
calculated result with the correct result from the output list and adjusts its
links so that the result is closer to the desired result in the next run. This is
tried for all data from the data sets so that in the end all calculated data are
as close as possible to the output data set.
Output_list=[3,6,9,12,15]
model.add(layers.Dense(units=3,input_shape=[1])) #Interlayer
model.add(layers.Dense(units=2,input_shape=[1])) #Outputlayer units must be 1
model.add(layers.Dense(units=1,input_shape=[1])) input_list=[1,2,3,4,5]
output_list=[3,6,9,12,15]
#Creating the network ("adam "alternatively to "sgd")
model.compile(loss='mean_squared_error',optimizer='sgd') #Training the net 1000
runs model.fit(x=input_list,y=output_list,epochs=1000) #Predicting the numbers
print(model.predict([6])) print(model.predict([7])) print(model.predict([8])) Then
we start the programme. The neural network is trained and after a short time
the data to be predicted is output.
Figure 64 Improvement of estimated values due to higher number of cycles Depending on the
18 2 0 0 2100
32 4 10 0 3400
44 2 20 0 3200
60 6 34 0 5500
20 2 2 1 2300
24 4 0 1 2700
44 5 21 1 3200
52 2 32 1 3200
The table only contains random samples. Moreover, important
factors such as occupational field are not represented!
Nevertheless, the data is perfectly suitable as an example. After all,
in reality we can only research samples.
In Python, we first create the data as a two-dimensional list.
dataset1=[
[18, 2, 0, 0, 2100], [32, 4, 10, 0, 3400], [44, 2, 20, 0, 3200], [60, 6, 34, 0, 5500],
[20, 2, 2, 1, 2300], [24, 4, 0, 1, 2700], [44, 5, 21, 1, 3200], [52, 2, 32, 1, 3200]
]
Next, we use the array() function to form an array from the list.
data_array=array(dataset1) In Spyder, we open the Variable Explorer.
We indicate in square brackets our desired rows and our desired columns,
each with a comma as separator. With the help of the colons, all elements
are used excluding the index.
model.add(layers.Dense(units=16,input_shape=[4])) #Interlayer
model.add(layers.Dense(units=64)) model.add(layers.Dense(units=64))
#Outputlayer units must be 1
Figure 68 Estimated salary of Tom and Lisa The estimated monthly salary for Tim is
1920€ and for Lisa 4838 €.
Our neural network evaluated the four factors and estimated a
potential salary based on this data.
The AI can also evaluate the individual influences of the input data.
Does the data set show unequal pay based on gender? To test this thesis, we
again create two individuals, Niklas and Jennifer. Both are 30 years old,
have three years of education and seven years of work experience. The only
difference we set in the data is gender.
niklas=array([[30,3,7,0]]) jennifer=array([[30,3,7,1]]) print(model.predict(niklas))
print(model.predict(jennifer)) Again, we run the neural network and get a
monthly salary for Niklas of €3059 and for Jennifer of €2570.
All non-mentioned contents were created by the author himself. He is therefore the author of the
graphics and has the rights of use and distribution.
*: https://docs.python.org/3/library/functions.html
*: https://www.python.org/community/logos/
**: https://en.wikipedia.org/wiki/File:Datove_centrum_TCP.jpg **:
https://pixabay.com/de/vectors/schaltungen-gehirn-netzwerk-chip-5076888/
* This file is made available under the GNU Free Documentation License.
https://commons.wikimedia.org/wiki/Commons:GNU_Free_Documentation_License,_version_1.2Es
may have been modified.
** This file is made available under the Creative Commons licence "CC0 1.0 waiver of copyright".