Python Programming Cookbook For Absolute Beginners - A Complete Crash Course and Tutorial For Everyone Including Dummies
Python Programming Cookbook For Absolute Beginners - A Complete Crash Course and Tutorial For Everyone Including Dummies
Absolute Beginners
TABLE OF CONTENTS
Table of Contents
CHAPTER 1
What is Python?
CHAPTER 2
Data types and variables
CHAPTER 3
Operators and Deep/Flat Copying
CHAPTER 4
Conditional Statements
CHAPTER 5
Inputs and Loops
CHAPTER 6
Print and Output
CHAPTER 7
Sequential data types
CHAPTER 8
LISTS
CHAPTER 9
Sets in python
CHAPTER 10
Functions and Modules
CHAPTER 11
Class and types
CHAPTER 1
WHAT IS PYTHON?
ython is a coding language which means that can be used for other types
P of programming and software development besides web
development.Python can be used for things like: Back end (or server-side)
web and mobile app development.
So back in 2008, the creator of Python, Guido van Rossum was a bit unhappy
with some of the really important architectural decisions that were made early
on in Python and he wanted to change them so he decided to overhaul Python
and release Python 3.People were supposed to adopt it pretty quickly and
stick with it But as you can probably tell by the fact that I have to subtitle this
video it was more complicated than that and the reason for all the trouble all
the controversy is that Python 3 is not backwards compatible.So usually
when you have a programming language and changes are made it's made
incrementally and it's made in a way that old code can still run.So old
javascripts written five years ago if you tried to run it now there won't be any
problems It won't be using some of the new features and It might not look as
nice but it will still work.
But with Python 3 the opposite was true.Python 2 was definitely the best
choice early on.But things have changed it's just been really slowly very
incrementally but almost 10 years later Python 3 is absolutely the way to
go.So, what makes me say that well first of all it's just easier in general to
learn the most up to date current standards to learn Python 3 and then go back
if you need to work in Python to for some reason.You can figure out the key
differences in the quirks rather than going the other way but more
importantly most of the main criticisms of things people didn't like just don't
matter anymore.It used to be that all the popular packages all the tools that
people would use the utilities that were written for Python were only written
in Python too.So, if you upgraded to Python 3 you were in this frontier land
where you couldn't rely on common packages it is no longer the case
now,throughout this book we would be working with the upgraded python 3.
INSTALLING PYTHON 3
Before we begin our python journey,let us look at how we can install python
on both Mac and Windows devices
MAC
STEP 1 - OPEN THE TERMINAL
We will complete most of our installation and set it up from the command
line. This is a non-graphical way to interact with your computer. That is,
instead of clicking buttons, type text and also get text feedback from your
computer. The command line, also known as a shell, can help you change and
automate many of the tasks you do on a computer every day. It is an
indispensable tool for software developers.
The macOS terminal is an application that allows you to access the command
line interface. As with any other application, you can find it by navigating to
the Applications folder in Finder, and then to the Utilities folder. From here,
as with any other application, double-click the terminal to open it.
Alternatively, you can use Spotlight by holding down the "" and "Spacebar"
keys to find Terminal by typing it in the box that appears.
STEP 2 - INSTALL XCODE
When the file is open in the terminal window, write the following:
export PATH=/usr/local/bin:$PATH
To save your changes, hold down the "" key and the letter "o" and press the
"" key when prompted. Now you can quit Nano by holding the "" key and the
letter "x".To activate these changes, enter the following in the terminal
window:
source ~/.bash_profile
Once you do this, the changes you make to the "+ PATH" environment
variable take effect.We can ensure that homebrew has been successfully
installed by entering:
brew doctor
If no updates are required at this point, the output from the terminal is:
OutputYour system is ready to brew.
Otherwise, you may receive a warning to run another command such as "+
brew update +" to ensure that your Homebrew installation is up to date.Once
Homebrew is done, you can install Python 3.
STEP 4 - INSTALL PYTHON 3
You can use homebrew to search for anything you can install using the "+
brew search +" command. However, to provide us with a shorter list, we're
just looking for the available Python-related packages or modules instead:
brew search python
The terminal outputs a list of the components that can be installed:
Outputapp-engine-python micropython python3
boost-python python wxpython
gst-python python-markdown zpython
homebrew/apache/mod_python homebrew/versions/gst-python010
homebrew/python/python-dbusCaskroom/cask/kk7ds-python-runtime
homebrew/python/vpythonCaskroom/cask/mysql-connector-python
Python 3 will be one of the items on the list. Let's go ahead and install it:
brew install python3
The Terminal window gives you feedback on the Python 3 installation
process. It may take a few minutes for the installation to complete.
Together with Python 3, Homebrew installs * pip *, * setuptools * and *
wheel *.
As a tool for use with Python, we will use * pip * to install and manage
programming packages that we may want to use in our development
projects. You can install Python packages by typing:
pip3 install
Here can ++refer to any Python package or library, e.g. B. Django for web
development or NumPy for scientific computing. If you want to install
NumPy, you can do this with the command + pip3 install numpy +.
python3 --version
This will output the currently installed version of Python. By default, this is
the latest stable version of Python 3 available.To update your version of
Python 3, you can first update Homebrew and then Python:
brew update
brew upgrade python3
It is recommended to make sure that your version of Python is up to date.
STEP 5 - CREATE A VIRTUAL ENVIRONMENT
After installing Xcode, Homebrew and Python, we can create our
programming environment.In virtual environments, you can set up an isolated
area for Python projects on your computer. This ensures that each of your
projects has its own dependencies that do not interfere with any of your other
projects.Setting up a programming environment gives us more control over
our Python projects and how different versions of packages are handled. This
is especially important if you are working with third-party packages.You can
set up as many Python programming environments as you want. Each
environment is basically a directory or folder on your computer that contains
some scripts to act as an environment.Select the directory in which you want
to insert your Python programming environments, or create a new directory
with + mkdir +, as in:
mkdir
cd
Once you are in the directory where you want to save the environments, you
can create an environment by running the following command:
python3.7 -m venv
Essentially, this command creates a new directory (named in this case) that
contains some elements:
1. The file "+ pyvenv.cfg +" refers to the Python installation with which
you executed the command.
2. The subdirectory + lib +contains a copy of the Python version and
contains a subdirectory + site-packages +that is initially empty, but
eventually contains the third-party modules you have installed.
3. The subdirectory + include +compiles packages.
4. The "+ bin +" subdirectory contains a copy of the Python binary along
with the " ACTIVATE " shell script that is used to set up the
environment.
Together, these files ensure that your projects are isolated from the general
context of your local computer so that system files and project files are not
mixed. This is a good way to do version control and to ensure that each of
your projects has access to the specific packages it needs.To use this
environment, you must activate it. To do this, enter the following command
that calls the activation script:
source /bin/activate
Your prompt is now preceded by the name of your environment, in this case
it is called:
With this prefix we know that the environment is currently active. When we
create programs here, only the settings and packages of this particular
environment are used.
After you complete these steps, your virtual environment is ready to use.
STEP 6 - CREATE A SAMPLE PROGRAM
After we set up our virtual environment, we create a traditional "Hello,
World!" - program. This ensures that our environment works and gives us the
opportunity to get to know Python better if it has not already been done.To do
this, we open a command line text editor like nano and create a new file:
nano hello.py
As soon as the text file opens in Terminal, we enter our program:
print("Hello, World!")
Exit nano by pressing the "" and "x" buttons. When prompted to save the file,
press "y +".Once you exit nano and return to your shell, run the program:
python hello.py
The hello.py program you just created should cause Terminal to produce the
following output:
Output Hello, World!
To leave the environment, simply enter the command "+ deactivate +" and
you will return to your original directory.
WINDOWS
As with almost every application under Windows, Python is installed using
an installer that guides you through the setup process. By default, the Python
installer stores .exe files under Windows in the app data directory of the
respective user - so that no administrator rights are required for the
installation.
FIND THE RIGHT PYTHON INSTALLER FOR WINDOWS
Python.org provides several different Windows installers. In addition to the
32-bit (x86) and the 64-bit version (x86-64) also an embeddable zip file, an
.exe file and a web-based installer. These differ as follows:
1. The .exe installer is just an executable file that starts the Python
installation process - this is the most common and simplest solution.
2. The web-based installer is basically identical to its .exe counterpart,
with the difference that it downloads the files necessary for the
installation separately. This drastically reduces the size of the installer,
but a network connection is absolutely necessary.
3. The embeddable Zip File is a self-contained, minimalist copy of the
Python run time environment. This is useful if you want to distribute a
Python application manually or if you want to test something quickly.
However, this installer does not contain any of the useful tools that the
other versions have on board.
INSTALL PYTHON WITH A PACKAGE MANAGER ON WINDOWS
Another option under Windows is to use the NuGet operating system package
management system. The Package Manager for .NET also offers Python, but
as a component for .NET applications and not to be used as an installer for a
standalone version of Python. Managing your Python instance should
therefore be easier with a regular installation.The Windows Package
Management System Chocolatey also provides Python . This is usually the
better option compared to NuGet because it checks your system for an
existing Python runtime environment. However, you should avoid mixing
regular and Chocolatey installations on one system.
Now That we have installed python 3 let us learn some concepts!
CHAPTER 2
2. long integer
3. Floating point
4. complex numbers
e.g. 1.2 + 3j
STRINGS
A string, or string, can be seen as a sequence of individual characters.
''' String in triple quotes can also span multiple lines and contain 'single' and
'double' quotes. '''
can be specified
This function is used to connect two strings to a new string using the "+"
operator:
"Hello" + "World" ->"HelloWorld"
2. REPETITION
You cut a "slice" out of a string. In the following expression, [2: 4] means
that we cut out a substring from the string "Python", which begins with the
character of index 2 (inclusive) and goes up to index 4 (exclusive):
"Python" [2: 4 ] ->"th"
5. LENGTH OF A STRING
IMMUTABLE STRINGS
As in Java but not as in C or C ++, strings cannot be changed in Python. If
you try to change an indexed position, an error message is generated:
>>> s = "Some things are immutable!"
>>> s [-1] = "."
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment
>>>
ESCAPE OR ESCAPE CHARACTERS
There are strings that control the flow of text, such as a newline (line feed) or
tab. They cannot be displayed as individual characters on the screen. Such
characters are represented within string literals using special character strings,
so-called escape sequences. An escape sequence is initiated by a backslash \
followed by the identifier of the desired special character. Overview of the
escape characters:
1. \ Line continuation
2. \\ backslash
3. \ 'Single quotation mark
4. \ "Double quotes
5. \ a bell
6. \ b regression
7. Mask out
8. \ 0 zero
9. \ n line feed (LF)
10. \ v Vertical tab
11. \ t Horizontal tab
12. \ r Carriage return (CR)
13. \ f form feed
14. \ 0XX Octal value
15. \ xXX hexadecimal value
The evaluation of escape characters can be prevented by placing an r or R in
front of a string.
Example:
r "\ n causes a line feed"
But how does it look if the string used is longer? In the following we use the
longest place name in the world as a string. A parish with just over 3000
inhabitants in the south of the island of Anglesey in the county of the same
name in northwest Wales:
>>> a =
"Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch"
>>> b =
"Llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch"
>>> a is b
True
But caution is advised, because what works for a community in Wales, for
example, fails for Baden-Württemberg:
>>> a = "Baden-Württemberg"
>>> b = "Baden-Württemberg"
>>> a is b
False
>>> a == b
True
So it cannot be because of the geographical location, as you can see in the
following example. It looks like there are no special characters or blanks in
the string.
>>> a = "Bathing!"
>>> b = "Bathing!"
>>> a is b
False
>>> a = "Baden1"
>>> b = "Baden1"
>>> a is b
True
CHAPTER 3
OPERATORS
operator D e s i g n a t i o n e x a m p l e
+, - A d d i t i o n , s u b t r a c t i on 1 0 -3
~ x B i t b y b i t e m e r g e n cy ~ 3 - 4
Result: -8
* * E x p o n e n t i a t i o n 1 0 * * 3
result: 1000
or, and, not Boolean or, boolean and, boolean not (a or b) and c
i n " E l e m e n t o f" 1 i n [ 3 , 2 , 1]
CONDITIONAL STATEMENTS
t certain times, certain decisions are inevitable, as you can see in the
A photo. So, you can hardly write a meaningful program that works without
any branching. So far, we have been able to write programs in which one
instruction follows the other and these are also executed in this order. But
only a few problems can be controlled by a linear program flow. For
example, you only want to execute a certain part of the program if certain
conditions apply or another part should possibly be executed several times.
Each programming language offers control structures that can be divided into
two categories: branches and loops.
In a programming language, a conditional statement, as it is called a branch,
is a piece of code that is executed under certain conditions. If the condition is
not met, this code is not executed. In other words: a branch determines which
of two (or more) program parts (alternatives) is executed depending on one
(or more) conditions. Conditional instructions and branches are assigned to
the control structures in programming languages (just like the loops), because
with their help a program can react to various states that result from inputs
and calculations.
The final example in this chapter is about taxes. We are writing a python
script that can be used to calculate the taxes for 2010 from the taxable
income.
THE IF STATEMENT
TRUE OR FALSE
Unfortunately, it is not so easy to distinguish between true and false in all
things in life as in Python: to be
considered "false"
numeric zero values (0, 0L, 0.0, 0.0 + 0.0j),
the boolean value false,
empty strings,
empty lists, empty tuples,
empty dictionaries.
and the special value None.
Python considers all other values "true".
ABBREVIATED IF
C programmers know the following abbreviation for the if construct:
max = (a> b)? a: b;
as an abbreviation for:
if (a> b)
max = a;
else
max = b;
In Python, C programmers have to get used to this spelling. In Python the
previous example is formulated as follows:
max = a if (a> b) else b;
CONTROL CALCULATOR IN PYTHON
The taxable income (zvE) is initially assigned to a tariff zone. Then the tax
amount (StB) can be calculated according to the corresponding formula for
individual assessment. 1
Unlike input, raw_input does not interpret the input. This means that
raw_input always returns a string, ie the input string of the user is passed on
unchanged. If you want a certain data type, you can convert the input using
the corresponding casting function or you can use the eval function. We
demonstrate this again with some examples in the interactive Python shell:
>>> x = raw_input ("your name?")
Your name? John
>>> print (x)
John
>>> x = raw_input ("your salary?")
Your salary? 2877.03
>>> print (x)
2877.03
>>> type (x)
<type 'str'>
>>> x = float (raw_input ("your salary?"))
Your salary? 2877.03
>>> type (x)
<type 'float'>
>>> x = eval (raw_input ("your favorite languages?"))
Your favorite languages? ["Java", "Perl", "C ++"]
>>> print (x)
['Java', 'Perl', 'C ++']
>>> type (x)
<type 'list'>
>>>
LOOPS
GENERAL STRUCTURE OF A LOOP
Loops are required to repeatedly execute a block of code, which is also called
a loop body. There are two types of loops in Python: the while loop and the
for loop.Most loops contain a counter or, more generally, variables that
change their values as the calculations inside the loop body. Outside, ie
before the start of the loop, these variables are initialized. Before each loop it
is checked whether an expression in which these variables or variables occur
is true. This expression determines the end criterion of the loop. As long as
the calculation of this expression returns "True", the body of the loop is
executed. After all instructions of the loop body have been carried out, the
program control automatically jumps back to the beginning of the loop, i.e. to
check the end criterion, and checks again whether this has been fulfilled
again.If so, it continues as described above, otherwise the loop body is no
longer executed and the rest of the script is continued. The diagram opposite
shows this schematically.
SIMPLE EXAMPLE OF A LOOP
We would now like to illustrate this with a small Python script, which forms
the sum of the numbers from 1 to 100. In the next chapter on for loops we
will learn about a far more elegant way to do this.
n = 100
s=0
i=1
while i<= n:
s=s+i
i=i+1
print "The total is:", p
READ STANDARD INPUT
Before we continue with the while loop, we need to clarify a few basic things
about standard input and standard output. The keyboard is normally the
standard input. Most shell programs write their output to standard output, ie
the terminal window or the text console. Error messages are output in the
standard error output, which usually also corresponds to the current terminal
window or the text console.
The Python interpreter also provides three standard file objects:
1. Standard input
2. Standard edition
3. Standard error output
They are in the sys module as
1. sys.stdin
2. sys.stdout
3. sys.stderror
to disposal.
The following example script now shows how to read in character by
character from the standard input (keyboard) using a while loop. The required
sys module is read in with the import command.
import sys
text = ""
while 1:
c = sys.stdin.read (1)
text = text + c
if c == '\ n':
break
print "Entry:% s"% text
Of course, you can read any input line from standard input more elegantly
with the function raw_input (prompt).
>>> name = raw_input ("What's your name? \ n")
What's your name?
Tux
>>> print name
Tux
>>>
THE ELSE PART
Like the conditional if statement, the while loop in Python, unlike other
programming languages, has an optional else branch, which many
programmers need to get used to.
The instructions in the else part are executed as soon as the condition is no
longer met. Certainly some are wondering what is the difference to a normal
while loop. If you hadn't put the statements in the else part but simply put
them behind the while loop, they would have been executed exactly the same
way. It only makes sense with a break command, which we will get to know
later.
In general, a while loop with else part looks like this in Python:
while condition:
Instruction 1
...
Instructions
else:
Instruction 1
...
Instructions
PREMATURE TERMINATION OF A WHILE LOOP
A loop is normally only ended when the condition in the loop head is no
longer fulfilled. With break you can leave a loop prematurely and end a run
with continue.
In the following example, a simple number guessing game, mam can see that
in combination with a break the else branch can make sense. Only when the
while loop ends regularly, ie the player has guessed the number, is there a
congratulation. If the player gives up, ie break, the else branch of the while
loop is not executed.
import random
n = 20
to_be_guessed = int (n * random.random ()) + 1
guess = 0
while guess! = to_be_guessed:
guess = input ("New number:")
if guess> 0:
if guess>to_be_guessed:
print "Number too large"
elif guess <to_be_guessed:
print "Number too small"
else:
print "Too bad you give up!"
break
else:
print "Congratulations! That's it!"
FOR LOOP SYNTAX
Notes:
In Python3, print is no longer a statement, but a function.
STRINGS
str
This type stores byte strings, also pure ASCII strings
unicode
This data type stores strings in Unicode.
LISTS
A sequence of arbitrary instances can be saved in a list. A list can be changed
at any time while the program is running.
TUPLE
in a tuple is like a list stored in a sequence believer instances, but these can
then no longer be changed during the further course of the program.
The operations discussed below apply to all sequential data types
INDEXING
Let's look at the string "Hello World":
You can see that the characters in a string are numbered from left to right,
starting with 0. From the back (right) you start counting with -1. Each
character of a string can be addressed so clearly, they can be indexed with
square brackets, as can be seen in the following example:
>>> txt = "Hello World"
>>> txt [0]
'H'
>>> txt [4]
'O'
Instead of from the front, you can also determine the indices from behind:
>>> txt [-1]
'd'
>>> txt [-5]
'W'
This works the same for lists and tuples, but first we have to take a look at
what lists and tuples look like in Python:
lists can contain any Python objects. In the following example, "colors"
contains 3 strings and list a contains 4 objects, namely the strings "Swen" and
"Basel", the integer 45 and the floating point number 3.54. If you now access
a list element with an index analogously to the procedure for strings, you get
the respective element. For example, colors [0] returns the string 'red' as the
result.
>>> colors = ['red', 'green', 'blue']
>>> colors [0]
'red'
>>> colors
['red', 'green', 'blue']
>>>
>>>
>>> a = ["Swen", 45, 3.54, "Basel"]
>>> a [3]
'Basel'
>>>
SLICING
You can also cut out parts of a sequential data type. In the case of a string,
you get a sub string or a list again for lists. In English this cutting is called
"slicing". As with indexing, the slicing operator uses square brackets, but
now at least two values are expected instead of a value: start value and end
value
This is best understood using an example:
>>> txt = "Hello World"
>>> txt [1: 5]
'ello'
>>> txt [0: 5]
'Hello'
>>> txt = "Hello World"
>>> txt [0: 5]
'Hello'
If you omit the initial value (eg [: 5]), the cut begins at the beginning of the
string (or the list). Similarly, you can also omit the end value to apply
everything to the end (eg [6:])
If you omit the start and end values, you get the whole string (or the entire list
or tuple):
'Hello'
>>> txt [0: -6]
'Hello'
>>> txt [: 5]
'Hello'
>>> txt [6:]
'World'
>>> txt [:]
'Hello World'
The following example shows how this affects lists:
>>> colors = ['red', 'green', 'blue']
>>> colors [1: 3]
['green', 'blue']
>>> colors [2:]
['blue']
>>> colors [: 2]
['red', 'green']
>>>
>>> colors [-1]
'blue'
The above slicing operator also works with three arguments. The third
argument then specifies how many arguments should be taken each time, ie s
[begin, end, step].
The following elements of s are then output: s [begin], s [begin + 1 * step], ...
s [begin + i * step] as long as (begin + i * step) <end.
txt [:: 3] prints every third letter of a string.
Example:
>>> txt = "Python is really great"
>>> txt [2: 15: 3]
'tnsgz'
>>> txt [:: 3]
'Ph ta l'
SUB-LISTS
LISTS CAN ALSO CONTAIN OTHER LISTS AS ELEMENTS:
REPETITIONS
A product is also defined for sequences in Python. The product of a sequence
s with an integer value n (s * n or n * s) is defined as n-times concatenation
of s with itself.
>>> 3 * "xyz-"
'xyz-xyz-xyz-'
>>>"xyz-" * 3
'xyz-xyz-xyz-'
>>> 3 * ["a", "b", "c"]
['a', 'b', 'c', 'a', 'b', 'c', 'a', 'b', 'c']
s * = n is (as usual) the short form for s = s * n.
THE PITFALLS OF REPETITIONS
In the previous examples, we only used the repeat operator on strings and flat
lists. But we can also apply it to nested lists:
>>> x = ["a", "b", "c"]
>>> y = [x] * 4
>>> y
[['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b', 'c'], ['a', 'b ',' c ']]
>>> y [0] [0] = "p"
>>> y
[['p', 'b', 'c'], ['p', 'b', 'c'], ['p', 'b', 'c'], ['p', 'b ',' c ']]
>>>
The result is very amazing for beginners of Python programming. We have
assigned a new value to the first element of the first sub-list (i.e. y [0] [0])
and at the same time we have automatically changed the respective first
element of all other sub-lists, i.e. y [1] [0], y [2] [0], y [3] [0]
The reason for this apparently strange behavior is that the repeat operator "*
4" creates four references to the list x.
CHAPTER 8
LISTS
n this chapter, we want to cover other aspects of lists. The main thing is to
I add, insert and delete elements.
A list can be viewed as a stack. In computer science, a stack (or stack) -
sometimes also called a cellar - describes a data structure with at least two
operations: one that can be used to put data on the stack and one to remove
the top element of the stack . Think of it as a stack of books to read. You
want to read the books in the stack from top to bottom. If you buy a new
book in between, it will appear on top of it and is the next book to be read.
The following operations are usually provided in the programming
languages:
PUSH
This method is used to put a new object on the stack. Depending on the point
of view, the object "top" or "right" is added.
POP
This method returns the top object of a stack.
PEEK
This method is used to check what is on the top of the stack. However, the
object is not removed as with pop. There is no such method in Python. With
lists or tuples, however, you can simulate them with index access. If "list" is a
list, then list [-1] behaves like a method list.peek (), which is not available in
the list class.
2. s.pop (i)
Returns the i-th element of s, removing it from the list. Usually, in other
languages, pop only returns the "top" or the rightmost element.
3. s.pop ()
If i is not specified, the last element is taken, which corresponds to the usual
pop of other programming languages.
>>> l = [42,98,77]
>>>l.append (103)
>>> l
[42, 98, 77, 103]
>>> x = l.pop ()
>>> x
103
>>>l.pop ()
77
>>>
You quickly find yourself in the situation where you want to add more than
one element to a list. For example, you want to append the elements to a
list. If you try this with append, you experience an unpleasant surprise:
>>> l = [42,98,77]
>>> l2 = [8.69]
>>>l.append (l2)
>>> l
[42, 98, 77, [8, 69]]
>>>
We actually "expected" this result:
[42, 98, 77, 8, 69]
EXTEND
For these cases there is the extend method for lists. It is used to add several
elements to a list:
>>> l = [42,98,77]
>>> l2 = [8.69]
>>>l.extend (l2)
>>> l
[42, 98, 77, 8, 69]
>>>
The extend argument must be an iterable object. For example, extend can also
be used on tuples and strings:
>>> l = [42,98,77]
>>>l.extend ("hello")
>>> l
[42, 98, 77, 'h', 'e', 'l', 'l', 'o']
>>>
>>> l = [42,98,77]
>>>l.extend ((3,4,5))
>>> l
[42, 98, 77, 3, 4, 5]
>>>
The index method can be used to determine the position of an element within
a list.
s.index (x [, i [, j]])
The index for the x is determined. If the optional parameter i is given, the
search only starts from this position and ends at position j if j is given. An
error message is issued if x does not occur in s.
>>> colors = ["red", "green", "blue", "green", "yellow"]
>>>colours.index ("green")
1
>>>colours.index ("green", 2)
3rd
>>>colours.index ("green", 3.4)
3rd
>>>colours.index ("black")
Traceback (most recent call last):
File "", line 1, in
ValueError: 'black' is not in list
>>>
CHAPTER 9
SETS IN PYTHON
he data type "set", which is a so-called "collection" type, has been in
T Python since version 2.4. contain. A set contains an un ordered collection
of unique and immutable elements. In other words, an element cannot
appear more than once in a set object, which is possible with lists and tuples.
The data type set is the Python implementation of sets as they are known
from mathematics.
CREATE SETS
If you want to create a lot, this is very easy in Python3. The usual
mathematical notation is used.
>>>staedte = {'Hamburg', 'München', 'Frankfurt', 'Berlin'}
>>> print (cities)
{'Munich', 'Berlin', 'Frankfurt', 'Hamburg'}
>>>'Berlin' in cities
True
>>>'Cologne' in cities
False
If you look closely at the example of a set above, you will surely be surprised
that the order of the cities is printed differently from print than the cities in
the definition of the set. This is because sets in general, and also in the
Python programming language, contain an unordered collection of different
objects. So there is no order for quantities, and therefore the print output can
be arbitrary. You can find more on this in the last section of this chapter.
In Python, however, the elements can only be immutable types, ie they
cannot be lists, for example. We demonstrate this in the following example,
in which we try to create a set that should contain lists of two with cities and
their population (as of 2013):
>>>staedte = {['Berlin', 3.42], ['Hamburg', 1.75], ['München', 1.41],
['Köln', 1.03], ['Frankfurt', 0.70], ['Stuttgart' , 0.60]}
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
If you use tuples (unchangeable) instead of lists (changeable) as elements,
then it works:
>>>staedte = {('Frankfurt', 0.7), ('Stuttgart', 0.6), ('Hamburg', 1.75),
('Berlin', 3.42), ('Köln', 1.03), ('München' , 1.41)}
One more note: Those who are already familiar with dictionaries or who have
already worked through our chapter on dictionaries may be surprised that we
also use the braces for sets.
In addition to the "set" data type, there is also a "set ()" function. With the
function set () you can convert sequential data types, e.g. lists, into sets. In
the following small example, we define a list of words that we convert into a
set using the set () function:
>>>liste_von_woertern = ["good", "helpful", "better", "optimal"]
>>>quantity_of_woertern = set (list_of_woertern)
>>>crowd_of_worthers
{'helpful', 'better', 'optimal', 'good'}
>>>
The set function is often used to remove multiple occurrences from lists or
other sequential data types. We want to show this in an example with a list of
cities from Switzerland, Austria and Germany. The city of Zurich appears
twice in this list. As expected, it only appears once in the generated quantity,
since there cannot be multiple occurrences in a quantity:
>>>liste_von_staedten = ["Frankfurt", "Zürich", "Bern", "Stuttgart",
"Freiburg", "Ulm", "Hamburg", "Munich", "Nürnberg", "Zürich",
"Bregenz", "Salzburg", "Vienna"]
>>>list_of_states
['Frankfurt', 'Zürich', 'Bern', 'Stuttgart', 'Freiburg', 'Ulm', 'Hamburg',
'München', 'Nürnberg', 'Zürich', 'Bregenz', 'Salzburg', ' Vienna']
>>>quantity_of_states = set (list_of_states)
>>>crowd_of_states
{'Vienna', 'Bern', 'Hamburg', 'Nuremberg', 'Frankfurt', 'Bregenz', 'Zurich',
'Munich', 'Ulm', 'Stuttgart', 'Freiburg', 'Salzburg'}
>>>
You can then convert the quantity back into a list if you need a list as a data
type:
>>>liste_von_staedten = list (quantity_of_staedten)
>>>list_of_states
['Vienna', 'Bern', 'Hamburg', 'Nuremberg', 'Frankfurt', 'Bregenz', 'Zurich',
'Munich', 'Ulm', 'Stuttgart', 'Freiburg', 'Salzburg']
>>>
As we can see, this approach has a minor flaw. Multiple occurrences are no
longer included in the results list, but the original order is usually no longer
available.
We now come to another application of the set function. In the following
example, we use them to separate a string into its characters:
>>> x = set ("A good Python tutorial")
>>> x
{'t', 'y', 'h', 'o', 's',' P ',' a ',' l ',' e ',' E ',' r ',' n ',' - ','i',' g ',' u ',' T ',''}
>>> type (x)
<class 'set'>
>>>
FROZEN SETS
Even if sets cannot contain changeable elements, they are changeable
themselves. For example, we can add new elements:
>>> cities = {"Frankfurt", "Basel", "Freiburg"}
>>>cities.add ("Strasbourg")
>>> cities
{'Freiburg', 'Frankfurt', 'Basel', 'Strasbourg'}
Frozen sets are like sets, but they cannot be changed. So they are immutable:
>>> cities = frozenset (["Frankfurt", "Basel", "Freiburg"])
>>>cities.add ("Strasbourg")
Traceback (most recent call last):
File "<stdin & module>", line 1, in <module>
AttributeError: 'frozenset' object has no attribute 'add'
>>>
clear method
All elements of a set are removed. The quantity is then empty, as
we can see in the following example:
>>> cities = {"Stuttgart", "Konstanz", "Freiburg"}
>>>cities.clear ()
>>> cities
set()
>>>
copy method
copy creates a flat copy of a quantity that is returned. We demonstrate the use
of an example:
>>>more_cities = {"Winterthur", "Schaffhausen", "St. Gallen"}
>>>cities_backup = more_cities.copy ()
>>>more_cities.clear ()
>>>cities_backup
{'St. Gallen ',' Winterthur ',' Schaffhausen '}
>>>
Only for those who believe that a simple assignment could also be enough:
>>>more_cities = {"Winterthur", "Schaffhausen", "St. Gallen"}
>>>cities_backup = more_cities
>>>more_cities.clear ()
>>>cities_backup
set()
>>>
The assignment "cities_backup = more_cities" creates only one pointer, ie
another name for the same object.
difference method
This method returns the difference between two or more quantities. As
always, we illustrate this with an example:
>>> x = {"a", "b", "c", "d", "e"}
>>> y = {"b", "c"}
>>> z = {"c", "d"}
>>>x.difference (y)
{'e', 'd', 'a'}
>>>x.difference (y) .difference (z)
{'e', 'a'}
>>>
Instead of using the "difference" method, we could have used the "-"
operator:
>>> x - y
{'e', 'd', 'a'}
>>> x - y - z
{'e', 'a'}
>>>
difference_update method
The method "difference_update" removes all elements of a different set from
a set. "x.difference_update (y)" is synonymous with "x = x - y"
>>> x = {"a", "b", "c", "d", "e"}
>>> y = {"b", "c"}
>>>x.difference_update (y)
>>>
>>> x = {"a", "b", "c", "d", "e"}
>>> y = {"b", "c"}
>>> x = x - y
>>> x
{'e', 'd', 'a'}
>>>
discard method
When discard (el) is called, the el element is removed from a set if it is
included. If el is not included in the set, nothing happens.
>>> x = {"a", "b", "c", "d", "e"}
>>>x.discard ("a")
>>> x
{'e', 'c', 'b', 'd'}
>>>x.discard ("z")
>>> x
{'e', 'c', 'b', 'd'}
>>>
remove method
The "remove" method works like discard (), but if el is not included in the
set, an error is generated, ie a KeyError:
>>> x = {"a", "b", "c", "d", "e"}
>>>x.remove ("a")
>>> x
{'e', 'c', 'b', 'd'}
>>>x.remove ("z")
Traceback (most recent call last):
File "<stdin & module>", line 1, in <module>
KeyError: 'z'
>>>
union method
The "union" method returns the union of two sets as a new set, ie all elements
that occur in both sets.
>>> x = {"a", "b", "c", "d", "e"}
>>> y = {"c", "d", "e", "f", "g"}
>>>x.union (y)
{'d', 'a', 'g', 'c', 'f', 'b', 'e'}
To form the unions you can also use the pipe character "|" use as operator:
>>> x = {"a", "b", "c", "d", "e"}
>>> y = {"c", "d", "e", "f", "g"}
>>> x | y
{'d', 'a', 'g', 'c', 'f', 'b', 'e'}
>>>
intersection method
The intersection method can be used to intersect two sets, as we can see in
the following example.
>>> x = {"a", "b", "c", "d", "e"}
>>> y = {"c", "d", "e", "f", "g"}
>>>x.intersection (y)
{'e', 'c', 'd'}
This can also be formulated with the "&" sign:
>>> x = {"a", "b", "c", "d", "e"}
>>> y = {"c", "d", "e", "f", "g"}
>>> x & y
{'e', 'c', 'd'}
>>>
isdisjoint method
This method returns True if two sets have an empty intersection.
>>> x = {"a", "b", "c"}
>>> y = {"c", "d", "e"}
>>>x.isdisjoint (y)
False
>>>
>>> x = {"a", "b", "c"}
>>> y = {"d", "e", "f"}
>>>x.isdisjoint (y)
True
>>>
issubset method
x.issubset (y) returns True if x is a subset of y. "<=" can be used instead of
calling the method. "<" checks whether it is a real subset: If x <y, then y
contains at least one element that is not contained in x.
>>> x = {"a", "b", "c", "d", "e"}
>>> y = {"c", "d"}
>>>x.issubset (y)
False
>>>y.issubset (x)
True
>>> x <y
False
>>> y <x # y is a real subset of x
True
>>> x <x # a set can never be a real subset of itself.
False
>>> x <= x
True
>>>
issuperset method
x.issuperset (y) returns True if x is a superset of y. "> =" can be used instead
of calling the method. ">" checks whether it is a real superset: If x> y, then x
contains at least one element that is not contained in y.
>>> x = {"a", "b", "c", "d", "e"}
>>> y = {"c", "d"}
>>>x.issuperset (y)
True
>>> x> y
True
>>> x> = y
True
>>> x> = x
True
>>> x> x
False
>>>x.issuperset (x)
True
>>>
pop
pop () returns any element of the set. This element is removed from the
set. The method generates a KeyError if the quantity is empty.
>>> x = {"a", "b", "c", "d", "e"}
>>> x
{'e', 'c', 'b', 'd', 'a'}
>>>x.pop ()
'e'
>>>x.pop ()
'c'
>>>x.pop ()
'b'
>>>x.pop ()
'd'
>>>x.pop ()
'a'
>>>
Even if "pop" returns the elements in the order of the internal representation
of the set, the phrase "pop () returns any element of the set." The amount we
have in the "head" is in the example above {"a", "b", "c", "d", "e"} and the
order in which pop () returns the elements is' e ',' c ',' b ',' d ',' a '.
That this order is not always the same for this set can be seen in the following
new interactive Python session:
>>> x = {"a", "b", "c", "d", "e"}
>>>x.pop ()
'a'
>>>x.pop ()
'b'
>>>x.pop ()
'e'
>>>x.pop ()
'd'
>>>x.pop ()
'c'
>>>
PYTHON SYNTAX
DOCSTRING
The first statement of a function body is usually a character string that can be
queried as a function name .__ doc__.
This instruction is called docstring .
Example:
def Hello (name = "everybody"):
"""Greets a person"""
print ("Hello" + name + "!")
print ("The docstring of the function Hello:" + Hello .__ doc__)
The edition:
The docstring of the function Hello: Greets a person
KEYWORD PARAMETERS
This is an alternative way of calling a function. The function definition itself
does not change.
An example:
def sumsub (a, b, c = 0, d = 0):
return a - b + c - d
print (sumsub (12.4))
print (sumsub (42.15, d = 10))
Only keywords that have not already been used as position arguments may be
used as keyword parameters. We can see the advantage in the example. If we
had no keyword parameters, we would have to give all arguments in the
second function call, although c only has to have the default value:
print (sumsub (42,15,0,10))
RETURN VALUES
In our previous examples, we used return statements in the sumsub function
but not in Hello. So you can see that it is not absolutely necessary to have a
return statement in a function. But what will be returned if we don't have an
explicit return instruction. Let's take a look at an example:
def no_return (x, y):
c=x+y
res = no_return (4.5)
print (res)
When we start the small script above, None is printed, ie the special value
None is returned by the no_return function. This shows that a function that
ends without a return statement returns None. However, this value is also
returned if a return statement ends a function without a subsequent
expression, as we can see in the following example:
def empty_return (x, y):
c=x+y
return
res = empty_return (4,5)
print (res)
Otherwise, the value of the expression is returned after the return. In the next
example 9 is returned:
def return_sum (x, y):
c=x+y
return c
res = return_sum (4,5)
print (res)
while True:
x = int (input ("Your number:"))
if x <= 0:
break
(lub, sup) = fib_intervall (x)
print ("Largest Fibonacci Number smaller than x:" + str (lub))
print ("Smallest Fibonacci Number larger than x:" + str (sup))
CHAPTER 11
1. "classname" is the string that specifies the class name and becomes
the name attribute
2. "superclasses" is a list or a tuple with the upper classes of our classes.
The list or tuple becomes the bases attribute.
3. "attributes_dict" is a dictionary that acts as the namespace of our
class. It contains the definitions of the class body and becomes the dict
attribute.
Let's look at a simple class definition:
class A:
passport
x = A ()
print (type (x))
We get the following output:
<class '__main __. A'>
We can also use type () for the class definition described above:
A = type ("A", (), {})
x = A ()
print (type (x))
We also get the following output:
<class '__main __. A'>
Generally this means that we have classes with
type (classname, superclasses, attributedict)
can define.
When we call type (), the call method of type is called. The call method calls
two other methods: new and init .
type .__ new __ (typeclass, classname, superclasses, attributedict)
type .__ init __ (cls, classname, superclasses, attributedict)
The new method creates and returns the new class object. Then the init
method initializes the created object.
class robot:
counter = 0
def __init __ (self, name):
self.name = name
def sayHello (self):
return "Hi, I am" + self.name
def Rob_init (self, name):
self.name = name
Robot2 = type ("Robot2",
(),
{"counter": 0,
"__init__": Rob_init,
"sayHello": lambda self: "Hi, I am" + self.name})
x = Robot2 ("Marvin")
print (x.name)
print (x.sayHello ())
y = Robot ("Marvin")
print (y.name)
print (y.sayHello ())
print (x .__ dict__)
print (y .__ dict__)
After executing the code, we get the following output:
Marvin
Hi, I am Marvin
Marvin
Hi, I am Marvin
{'name': 'Marvin'}
{'name': 'Marvin'}
The class definitions of Robot and Robot2 are completely different
syntactically. But logically speaking, both implement exactly the same
thing.What Python does in the first example is that all methods and attributes
of the Robot class are collected and then passed as parameters to the
attributes_dict argument when the type is called. So, Python does the same
thing we did with the Robot2 class.
ENCAPSULATION OF DATA
Another key advantage of OOP is the encapsulation of data. Properties can
only be accessed using access methods. These methods can include
plausibility tests, data type conversions or any kind of calculations, and they
(or "only" them) have "information" about the actual implementation. Robot
and account In the next section we will write a robot class in Python. This
will contain information about the year of construction and the name of a
robot, for example. This information is also referred to as the properties or
attributes of an instance. For example, it is useful to save the name of a robot
as a string in an attribute. Encapsulation now means that we cannot access
this string directly. For example, we need to call a method called "GetNamen
()" to get the name of a robot. The principle of data encapsulation can also be
seen in the model of the account class. The method of setting the date of birth
can, for example, check whether the date is correct: This is how you can
intercept if someone enters a date in the future due to a typing error. You
could also generally check whether the information is within a certain range.
For example, a current account for children under 14 should not be possible
or investments by new customers over 100 years old are considered
extremely unlikely.
INHERITANCE
Based on a general robot class that only knows a name and a year of
construction, we could define other robot classes such as "industrial robots"
that can be used stationary on an assembly line, moving robots with wheels,
legs or caterpillars and so on. Each of these classes then inherits the
possibility to have a name and a year of construction from the base class.
print (f.counter)
One more detail, which is not so important at the moment. So you are
welcome to continue with the next subsection "Methods".
The objects of most classes have an attribute dictionary __dict__, in which
the attributes are stored with their values, as we see in the next example.
>>> class Robot:
... passport
...
>>> x = Robot ()
>>> x.name = "Marvin"
>>>x.age = 5
>>>
>>>x .__ dict__
{'name': 'Marvin', 'age': 5}
>>>
METHODS
In the following we want to show how to define methods in a class. We will
add a SageHallo method to our empty robot class. A method differs
externally from a function only in two aspects:
Note: In principle, you could choose any name instead of "self", including
"this", which Java or C ++ programmers might like more. "self" is just a
convention.
We are now expanding our robot class with a SageHallo method that simply
writes "Hello" when it is called:
class robot:
def SageHallo (self):
print ("hello")
if __name__ == "__main__":
x = robot ()
x.SageHallo ()
We see in the code that the parameter "self" only appears when a method is
defined. It is not specified when called. In comparison to function calls, this
is strange at first, ie we define a method with a parameter "self" and call it up
apparently without parameters. But if we take a closer look at the call, we see
that we are not just calling SageHallo (), but that the instance x appears
before the point. Herein lies the secret: It is as if we had called SageHallo
(x). In other words, we pass a reference to the instance x to self. For further
understanding: One should actually call the method of a class via the class
name. In this case, the instance is passed as an argument, i.e.
Robot.SageHallo (x).
INSTANCE VARIABLES
We now want to change our SageHallo method so that it says "Hello, my
name is Marvin" when the robot is called "Marvin". This brings us back to
the instance attributes. Because an instance must be able to remember its
name. In our initial example, we defined attributes outside of the class
definition with instructions of the type x.name = "Marvin", x.baujahr = 1979
and y.name = "Caliban". In a way, we can do the same thing within a class
definition in the methods. However, of course we have no idea of the instance
name, i.e. x or y. However, we do not need to know this name, since the
formal parameter self is a reference to the current instance. With this
knowledge, we are now writing further functions
class robot:
def SageHallo (self):
print ("Hello, my name is" + self.name)
def SetNames (self, name):
self.name = name
Def Set year of construction (self, year of construction):
self.baujahr = year of construction
if __name__ == "__main__":
x = robot ()
x.SetzeNamen ("Marvin")
x.SetzeBaujahr (1979)
y = robot ()
y.SetNames ("Caliban")
y.SetzeBaujahr (1993)
x.SageHallo ()
y.SageHallo ()
There is the following to say about the SetNames method, which also
answers two frequently asked questions:
Yes, you can use any name instead of self, including this
one. However, you shouldn't do this because it violates a
Python convention. In addition, other programmers may have
difficulty understanding the code. Some development
environments, such as eclipse, also give a warning if you do not
adhere to this convention.
The attribute name does not have to be the same as the name of
the formal parameter. However, it often has the same name. We
could also have called the parameter, for example, "n".
if __name__ == "__main__":
x = robot ()
x.SetzeNamen ("Marvin")
x.SetzeBaujahr (1979)
y = robot ()
y.SetNames ("Caliban")
y.SetzeBaujahr (1993)
x.SageHallo ()
y.SageHallo ()
What is particularly ugly about the code above is that we used this once and
self once, so that we were not consistent in our naming.There is also
something to say about style: According to PEP8, the official "Style Guide",
the following applies: "Method definitions within a class are separated by a
single blank line." a class are separated by a single blank line. '') However,
this is not adhered to in many cases. Even the official Python documentation
at python.org is not unique here! We will not always adhere to this
convention below, above all to save space.Butbesides style and naming for
the first parameter, there is a much more serious problem. When we create a
new robot, we have to follow three instructions each time. In our example
these are, instantiation using x = robot (), naming x.SetzeNamen ("Marvin")
and setting the year of construction x.SetzeBaujahr (1979). This procedure is
cumbersome, prone to errors and, above all, it does not correspond to the
usual procedure in the OOP.
The __init __ method
We want to define the attributes immediately after creating an
instance. __init__ is a method that is called immediately and automatically
after the creation of an instance. This name is fixed and cannot be chosen
freely! __init__ is one of the so-called magic methods, of which we will learn
more in the following chapters. The __init __ method is used to initialize an
instance. Python does not have an explicit constructor or destructor as you
know it in Java or C ++. The actual constructor is implicitly started by Python
and __init__ serves, as the name suggests, to initialize the
attributes. However, the __init __ method is started immediately after the
actual constructor, and this creates the impression that it is a constructor.
>>> class A:
... def __init __ (self):
... print ("__ init__ was executed!")
...
>>> x = A ()
__init__ has been executed!
>>>
We are now writing an initialization method __init__ for our example class in
order to be able to set or transfer the name and the year of manufacture
during instantiation, ie x = robot ("Marvin", 1979).
class robot:
def __init __ (self, name, year of construction):
self.name = name
self.baujahr = year of construction
def SageHallo (self):
print ("Hello, my name is" + self.name)
def NewName (self, name):
self.name = name
def new year of construction (self, year of construction):
self.baujahr = year of construction
if __name__ == "__main__":
x = robot ("Marvin", 1979)
y = robot ("Caliban", 1993)
x.SageHallo ()
y.SageHallo ()
If you write x = robot ("Marvin", 1979), then logically speaking it behaves as
if you would instantiate an instance x first, i.e. x = robot (), - which of course
no longer works because of our __init __ method, which requires two
arguments when calling! -, and then call the __init __ method with x .__ init
__ ("Marvin", 1979). (However, the __init __ method cannot be called from
outside, since it begins with a double underscore and is therefore a private
method.)Using the class now looks much more "tidy" and clearer, but we are
hurting nor the principle of data encapsulation or data abstraction, which we
will discuss below.
In the following we want to demonstrate an error message that often raises
questions for beginners. We try to create a robot in the following interactive
Python shell. Instead of the correct instantiation x = robot ("Marvin", 1979)
we call robots without parameters:
>>> from robots2 import robots
>>> x = robot ()
Traceback (most recent call last):
File "", line 1, in
TypeError: __init __ () takes exactly 3 arguments (1 given)
>>>