Kyoto University Python Version2023 - 10!19!01e
Kyoto University Python Version2023 - 10!19!01e
These are reserved Python keywords. Faded words will not be covered in this book.
Version 2023/10/19
1
Table of Content Next Chapter Table of Contents
Table of Content
Table of Content ······································································ 2
0. Foreword ········································································ 16
0.1 Learning goals of this chapter ......................................................................... 16
0.2 Reasons for writing an entirely new textbook ................................................. 16
0.3 Humanities majors: you can do it! ................................................................... 17
0.4 Regarding the organization of this text ........................................................... 17
0.5 Notation ........................................................................................................... 17
0.6 Warning regarding copying and pasting ......................................................... 17
0.7 Edits for later versions (2023 and later) .......................................................... 18
Notes for English Version ............................................................................................ 18
Acknowledgements ..................................................................................................... 18
2
Table of Content Next Chapter Table of Contents
5. Lists ·············································································· 64
5.1 Learning goals of this chapter ......................................................................... 64
5.2 Learning with the Python shell ........................................................................ 64
5.3 What is a list? .................................................................................................. 64
5.4 Generating lists ............................................................................................... 65
5.5 Methods........................................................................................................... 66
5.6 Accessing elements in a list ............................................................................ 67
5.7 Negative indices and slicing............................................................................ 67
5.8 Adding to and combining lists ......................................................................... 68
5.9 List assignment and duplication ...................................................................... 69
5.10 Mutable and immutable objects ...................................................................... 71
5.11 Shallow and deep copying .............................................................................. 72
5.12 Visualizing lists ................................................................................................ 73
5.13 Keeping Calculation Results in a List ............................................................. 74
5.14 Tuples and dictionaries ................................................................................... 75
3
Table of Content Next Chapter Table of Contents
4
Table of Content Next Chapter Table of Contents
5
Table of Figures Next Chapter Table of Contents
Table of Figures
Figure 1-1 Jacquard machine and Analytical Engine ............................................................ 20
Figure 2-5 Note the differences between IDLE Editor and the Python shell .......................... 40
Figure 2-9 Using the -i option to stay in interactive mode once the program is finished running
............................................................................................................................... 45
Figure 2-11 Python online manual (the right side is after selecting Japanese) ...................... 46
Figure 3-3 Python variables contain information on data (object) location ............................ 56
6
Table of Figures Next Chapter Table of Contents
Figure 5-3 Checking how lists behave with Python Tutor ..................................................... 74
Figure 8-1 Comprehensive diagram of Heian-kyō (generated by the writer from Reference
[14]図一 1 (Figure 1-1)) ......................................................................................... 105
Figure 10-3 Former Toyosato Elementary School building and banister (10/16/2016 Kita
Photography) ........................................................................................................ 125
Figure 10-6 Keys used to take a schreen shot in Windows ................................................ 129
Figure 11-5 Behavior carried out by the widgets, call back functions, and global variables . 138
Figure 12-2 The analog clock you will create ..................................................................... 156
Figure 12-3 Calculation of the position of the hands of the clock ....................................... 156
Figure 14-1 Approximation of a sawtooth wave by summing trigonometric functions .......... 176
7
Table of Figures Next Chapter Table of Contents
Figure 14-3 Approximation of a square wave by summing trigonometric functions .............. 180
Figure 14-4 Using a “list of data at different time points” ................................................... 181
Figure 15-2 Determining victory for the turn in question ..................................................... 189
Figure 16-1 The relationship between NumPy, Matplotlib and pandas ................................ 208
8
Table of Tables Next Chapter Table of Contents
Table of Tables
Table 1-1 Symbols used in programming and their pronunciations ....................................... 32
9
Table of Programs Next Chapter Table of Contents
Table of Programs
Program 2-1 (p2-1.py) ......................................................................................................... 40
Program 4-1 Program that solves for square roots (ver. 1, p4-1.py) ..................................... 62
Program 6-1 Program that solves for square roots (ver. 2, p6-1.py) ..................................... 79
Program 6-2 Program that solves for square roots (ver. 2, p6-2.py) ..................................... 80
Program 6-6 Program that solves for square roots (ver. 3, p6-6.py) ..................................... 86
Program 6-7 Program that solves for square roots (infinite loop method, p6-7.py) ................ 87
Program 9-2 Example of an absolute value function (p9-2.py, returns when possible) ........ 108
Program 10-1 Turtle usage example (p10-1.py, Do not save this program as turtle.py)........ 119
Program 10-2 Program that draws polygons with n faces (incomplete, to be saved as p10-2.py)
............................................................................................................................. 120
Program 10-4 Responding to mouse clicks in turtle graphics (p8-4.py) .............................. 123
10
Table of Programs Next Chapter Table of Contents
Program 11-3 Setting up a callback function with arguments using a lambda notation
(tkdemo_2term_lambda.py) ................................................................................... 144
Program 11-5 Program that displays card images: tkdemo-show_cards.py ......................... 152
Program 12-1 Analog clock with tkinter (without a date button, tkdemo_simple_clock.py) ... 157
Program 12-2 Analog clock with tkinter (with a date button, tkdemo_clock_with_button.py)
............................................................................................................................. 159
Program 13-2 Class variables and instance variables (p13-2.py) ....................................... 168
Program 14-3 A simple text editor using tkinter (p14-3.py) ................................................. 181
Program 15-1 Tic-tac-toe program example (Part 1: Global variables) ............................... 193
Program 15-2 Tic-tac-toe program example (Part 2: Turn-related functions) ....................... 194
Program 15-3 Tic-tac-toe program, example (Part 3: Board-related functions part 1) ......... 195
Program 15-4 Tic-tac-toe program, example (Part 4: Board-related functions part 2) ......... 197
Program 15-5 Tic-tac-toe program, example (Part 5: Board testing functions 1) ................. 199
Program 15-6 Tic-tac-toe program, example (Part 6: Board testing functions 2) ................. 201
Program 15-7 Tic-tac-toe program example (Part 7: Game record-related functions) .......... 203
Program 15-8 Tic-tac-toe program, example (Part 8: The play() function and the main program)
............................................................................................................................. 204
11
Table of Programs Next Chapter Table of Contents
12
Table of Exercises Next Chapter Table of Contents
Table of Exercises
Exercise 2-2 Differences between the Python shell and IDLE Editor .................................... 40
Exercise 2-3 Confirmation of thr result after execution of Program 2-1 ................................ 41
Exercise 2-4 Prepare your own Python learning environment and report it. .......................... 45
Exercise 2-5 Redo today’s exercise in your personal learning environment. ......................... 45
Exercise 4-1 Creation and execution of a program to obtain square root .............................. 61
Exercise 4-3 Solve for the square root of some other numbers. ........................................... 63
Exercise 6-1 Apply 'for' statement to the program of solving square root .............................. 78
13
Table of Exercises Next Chapter Table of Contents
Exercise 8-1 Fine tuning the square root calculation ......................................................... 102
Exercise 10-2 How can you draw a 5-pointed star? ........................................................... 120
Exercise 10-3 Draw regular 7- and 9-sided polygons, and their star equivalents ................ 121
Exercise 10-4 Categorize the above functions following the usages shown in Section 9.9. . 121
Exercise 11-3 Extending the Calculator to Four Arithmetic Operations (Skill Test) .............. 147
Exercise 11-4 Management of Widgets with List (Skill Test) ............................................... 148
14
Table of Exercises Next Chapter Table of Contents
Exercise 13-3 User Calculator Class in the Tkinter Program .............................................. 167
Exercise 16-1 Modify it to draw a approximation of a saw wave with sum of trigonometric
functions. .............................................................................................................. 228
15
0 Foreword Next Chapter Table of Contents
0. Foreword
This textbook was written for a (Python) programming exercises course as part of Kyoto
University’s Liberal Arts and Sciences courses.
Objectives
Python is a programming language that has many practical uses and is easy for beginners to learn. In
recent years, its use in academic research has steadily increased. In this course aimed at beginners,
students will learn to program using Python through various exercises.
Goals
Students will learn the fundamentals of how to use Python to execute programs.
After learning about the functions and formats of the fundamental components of a Python
program, students will be able to use the examples to put together their own programs.
Students will be able to design, implement, and test their own simple Python programs.
16
0 Foreword Next Chapter Table of Contents
0.5 Notation
It is most effective for students to learn using a two-pronged approach. One side of this approach will
see students learning by testing simple commands line by line in an interactive environment known
as the Python shell. The other side will have students write larger programs (scripts) in an editor and
execute them as a batch.
Features that students are to try out in the Python shell are represented in the text using the red
K2PFE font seen here:
a = 1 + 2
The results obtained from executing these commands are shown in blue as seen here:
3
Please try these out for yourself as you learn.
On the other hand, larger programs will be shown using the table format with three (or two) columns
seen below. Input the source code into the editor and execute the program to see the results. In this
representation, a character '␣' is placed instead of space ' ' so as to make them visible.
Row Source code Notes
1 a␣=␣1␣+␣2 '␣' is used instead of
2 print(a) space ' ',
Notices in typing actual programs referring the source code lists:
Spaces in the source code are replaced with '␣' so as to make them visible.
Ordinally fonts in Windows, a glyph of yen (¥) is used for backslash code (\). K2PFE font
uses a glyph of backslash (\) instead.
format. In the PDF document, spaces are not saved, and there are instances in which the characters
will be automatically changed. As such, please be aware that there are instances in which simply
copying and pasting from the PDF will lead to program errors.
Acknowledgements
Since the publication of the 2019 version following the 2019 academic year, we have received many
helpful opinions as well as identifications of misprints. Our deepest thanks for all of those who
shared their opinions with us.
K2PFE font used in this textbook were developed as a collaborative research by Professor Akihisa
Tatsumi, Part-time Lecturer Maya Kusunoki of Kyoto City University of Art, Dr. Tamaki Motoki of
Kyoto University and Hajime Kita one of the authors of this textbook. It is partly supported by JSPS
KAKENHI Grant Number JP 21K028 80.
English translation from Japanese version was supported by Center for Innovative Research and
Education in Data Science, Institute for Liberal Arts and Sciences, Kyoto University as one of its
activities in development of learning materials and their publication.
This book is licensed under CC-BY-NC-ND. For detail, access the following:
https://creativecommons.org/licenses/by-nc-nd/4.0/deed.en
18
1 Computers and Programming Next Chapter Table of Contents
19
1 Computers and Programming Next Chapter Table of Contents
In Babbage’s era, complex mechanical movements could only be attained by using gears or
something similar. Later on, it became possible to create mechanisms that use electricity to fit in
another electrical switch. One of these was to use an electromagnet to mechanically move (relay) an
electrical contact. Attempts were actually made to use these electrical relays to make computers.
However, while this works from an electrical standpoint, the mechanical movement that
accompanies it was far too slow.
After this, computers were developed that utilized vacuum tubes. These were tubes in which
electrons flowing between an electrode (cathode, anode) are controlled by the voltage applied to a
different electrode placed between them. Vacuum tubes had the advantage of fast electronic
movement, however, the fact that a filament was needed to add heat in order to make the cathode
emit electrons meant they had short lifespans.
Following this, transistors were invented. Transistors are devices that enable behavior similar to that
of a vacuum tube to occur within the solid matter of a semiconductor. Transistors have a long
lifespan, are very small, and do not consume much electricity. At this point, computers that consisted
of a large number of discrete transistors wired together were made.
Finally, integrated circuits were developed. These circuits are printed as an entire unit and consist
of a lot of transistors and wiring on top of a single semiconductor chip. Integrated circuits are much
smaller and much more cost efficient when compared to normal electronic circuits. Integrated circuit
technology was then used to develop microprocessors, which are essentially the main component of
a computer (all contained in a single chip). Microprocessors are the breakthrough that made cheap,
small computers that anyone can use, such as PCs and smartphones, into a reality.
20
1 Computers and Programming Next Chapter Table of Contents
Vacuum Integrated
Relay Transistor
tube Circuit
Stored-program computer
So just how do modern computers carry out complex data processing?
The actions a computer (the hardware itself) can perform at one time are very simple, and complex
work like data processing is merely a combination of these simple actions. This combination of
actions is expressed as a program and put into action.
In modern computers, programs are stored in memory just like the data they handle. They are read at
rapid speeds and then executed. Computers that work in this manner are called “stored-program
21
1 Computers and Programming Next Chapter Table of Contents
computers.” 1 All computers used today, from the small microprocessors used in home appliances to
0 F0 F
The fundamental operations that a computer can perform are the following simple tasks.
Configure a program and data used in the program in the memory (by some method).
Provide the CPU with an execution start location forthea program
The CPU repeats the following:
1. Reads one step of the program from the memory and performs calculations or move data
according to the instructions.
The result of the calculation can also be stored in the memory.
Input/output can also be performed.
2. The CPU advances the instruction being executed to the next location.
In some cases, the executed location can change based on the program.
1 In an early computer called ENIAC, calculation settings were not done in stored-program fashion; rather, they were set
by altering the wiring of the cables. However, upon developing its successor, EDVAC, the stored-program method was
proposed. As the report proposing it was submitted by von Neumann, it is sometimes referred to as the von Neumann
architecture.
22
1 Computers and Programming Next Chapter Table of Contents
Memory
Display and
Keyboard
external storage
Data
CPU
Read one step of the
Program
program from memory,
executes the contents,
and proceeds to the
next step
23
1 Computers and Programming Next Chapter Table of Contents
Software
Software that
that
Program written in the executes
executes thethe Computer
language source code
source code hardware
(Source code) (language processor)
(language processor)
Executed by the
language processor Virtual computer that executes
the programming language
In addition, there are many things that strongly resemble programming languages that are often used
together with them. For example, HTML which codes for web pages, CSS which codes for the
page’s style, XML and JSON which code for data, and SQL which codes for database inquiries.
Why are there so many programming languages being used? Why are they not just all combined into
one?
The advancement of computing requires the overall improvement of the programs that are
developed. Consequently, the ways of thinking required to effectively code as well the programming
languages based in these ways of thinking developed over time. The desire to write programs more
easily, more quickly, and more securely is ever-present. There is a demand for programming
languages that are specially tailored to specific uses. New programming languages have been
developed and the specifications and language processors for specific programming languages have
been altered with these facts in mind.
On the other hand, the use of software developed in a certain programming language as well as the
programmers who wish to code in that language create demand for its continued usage.
Discontinuing old languages can be difficult. FORTRAN, a programming language that is used in
scientific computing, is the oldest programming language, yet still sees use following various
modifications.
Some programming languages have been developed by software companies, while others have been
created by individuals or as a community effort. Certain programming languages are developed by
companies strictly for-profit and require that you buy their language processors. Additionally, there
24
1 Computers and Programming Next Chapter Table of Contents
are cases in which languages are developed due to the needs of a company and the language
processors are distributed freely with their source code made public.
1) Compiler
Executes the source code and then translates (compiles) it into machine code. The resulting machine
code is then executed. Compiling takes time, however the compiled executable program (machine
code program) can be executed very quickly.
2) Interpreter
Interprets the source code line by line, simulating the operations. Execution speeds can be slow as
interpreting the source code takes time; however, interpreters are so flexible that they can be used for
various purposes such as interactive usage.
Translated Executed by
into machine Machine
Source code computer
code by code
compiler hardware
Sequentially
Computer
Source code executed by
hardware
interpreter
Translated by
representation
Intermediate
Intermediate
intermediate Computer
Source code representation
representation hardware
interpreter
compiler
25
1 Computers and Programming Next Chapter Table of Contents
1.5 Python
History of Python
In 1989, Guido van Rossum began working on Python. Version 2.0 was released in 2000, and version
3.0 was released in 2008.
Note: Python version 3 is not backward compatible with version 2 (version 3 does not contain the
specifications of version 2). As such, both versions tend to be run concurrently in order to ensure that
programs written with version 2 can run properly.
Note: Python generally comes pre-installed on Mac and Redhat Linux, but in some cases
version 2 is the one that is installed. In order to use version 3, you may need to install the version 3
language processor separately and ensure the correct version is being used at all times.
Characteristics of Python
Easy for beginners to learn yet capable of advanced programming
Can be used for a wide variety of applications
Libraries for scientific computing (NumPy, scipy, matplotlib, pandas, etc.) are being
developed by many people.
In recent years, interest in data science and artificial intelligence (machine learning)
techniques has increased dramatically. Python has been growing in popularity due to its
abundant libraries for these applications.
26
1 Computers and Programming Next Chapter Table of Contents
CUI programs. These programs operate via the Windows command prompt or something
similar, take text input from the keyboard, and output text onto the screen. These programs are
relatively easy to learn due to the simplicity of input and output, but they also tend to not be
very user-friendly.
GUI programs. These programs operate within a window and are controlled via buttons or
similar objects within the window. GUI programs enable the user to operate the program in a
manner they are likely already accustomed to, and images can also be included. However, the
number of things that you have to program is usually much higher.
Reading and writing files, network management, and many other actions require similar
programming in both CUI and GUI programs.
A few examples of using potential applications are given below.
Scientific computing and numerical simulations
Data processing and analysis of numbers, strings of text, and images
Video games and graphical works
Automatic data collection from websites (called web scraping)
Other applications
Smartphone applications
Programs that operate on web servers or other servers on networks
Programs that operate in coordination with electronic circuits. Raspberry Pi is a small
computer that runs on Linux and Python that was developed for this purpose.
27
1 Computers and Programming Next Chapter Table of Contents
28
1 Computers and Programming Next Chapter Table of Contents
5) Tracing
Follow a program manually by hand in order to see how it will function (called tracing)
29
1 Computers and Programming Next Chapter Table of Contents
writing programs that contain errors in order to see what happens can be an effective
way to gain experience.
Read the error messages. There are many beginners who do not read the error messages that
are displayed when they encounter an error. Error messages can definitely seem difficult to
understand, but they are telling you where or what the error you have encountered is. Error
messages for errors that you have intentionally caused should be relatively easy to understand,
so please try to familiarize yourself with them.
7) Look up information
You should strive to become able to search for information on programming via topic or
method. A few methods for doing so are given below.
Learn how to use various libraries and advanced programming concepts.
Learn about tools that support programming.
You can look up information in books or on the internet.
Ask others for help with things you don’t understand. This requires the communication
skills to be able to ask for help when you need it.
1 While variable names in Python can use kanji, this is not the case for many programming languages, so it is safer to just
avoid using it.
30
1 Computers and Programming Next Chapter Table of Contents
Pronunciations and notes regarding the usage of the most common symbols can be found in the table
below. This table was taken from a literature reference [1] and a portion added with the consent of
the authors.
31
1 Computers and Programming Next Chapter Table of Contents
" Double quotes Both " and ' can be used to surround
' Single quotes, apostrophe strings in Python. Either can be used,
but you must use the same type of quotes
on both sides of the string.
# Pound sign, no. sign
$ Dollar sign
% Percent
& And, ampersand
* Asterisk
+ Plus
, Comma
- Minus, hyphen
. Period, dot
/ Forward slash
: Colon Take note of the difference between these
; Semicolon two
32
1 Computers and Programming Next Chapter Table of Contents
| Vertical bar
~ Tilde
[ Square bracket (open bracket) Python and many other programming
] Square bracket (close bracket) languages make use of brackets and
{ Curly bracket (open bracket) parentheses for various different uses.
} Curly bracket (close bracket) It can be easy to make typos.
( Parenthesis (open parenthesis)
) Parenthesis (close parenthesis)
33
1 Computers and Programming Next Chapter Table of Contents
Library
Use as needed
Framework
(The framework within which GUIs and web server programs operate)
References
喜多 一,岡本雅子,藤岡健史,吉川直人:写経型学習による C 言語プログラミングワーク
ブック,共立出版(2012, in Japanese
34
2 Python: Execution Environment and How to Use It Next Chapter Table of Contents
2.3 Setup
Create the folder where you will be saving the Python programs (scripts) that you write for this class.
For example, you can make a folder called “Python Scripts” within your “My Documents” folder 1. 1F1F
1 If you make a folder on the NextCloud N: drive on one of the university’s computers, you will be able to access it on your own PC at
home.
35
2 Python: Execution Environment and How to Use It Next Chapter Table of Contents
36
2 Python: Execution Environment and How to Use It Next Chapter Table of Contents
there are times when the incorrect version (Python 2, for example) is launched. If this happens,
double check how to launch IDLE.
Double check the prompt. The “>>>” within the window is a symbol (called a prompt) meant
to prompt you to input commands. You can input Python commands here via the keyboard.
the remainder of a division operation in their program. The “%” operator can be used to obtain this
remainder.
38
2 Python: Execution Environment and How to Use It Next Chapter Table of Contents
Simply inputting a variable’s name into the Python shell will display its value. In the programs that
you will code later on, which will be scripts in which multiple lines are executed all at once, will
require you to explicitly use the print() function.
39
2 Python: Execution Environment and How to Use It Next Chapter Table of Contents
Figure 2-5 Note the differences between IDLE Editor and the Python shell
Exercise 2-2 Differences between the Python shell and IDLE Editor
Please review the differences between the Python shell and IDLE Editor.
Confirm that there are no typos and then select “Run” and then “Run Module.” Run means to
execute the program, and module refers to the Python program that is currently being edited.
As this is a new program, you will need to save it. Save it as p2-1.py (.py is the filename extension
for Python programs) in the folder that you created for your Python programs. After doing so, it will
be run in the Python shell and the results will be displayed.
40
2 Python: Execution Environment and How to Use It Next Chapter Table of Contents
Interactive use
Save and run
Idle Editor
• Resetting the Python shell Write programs
• Running programs
• Reverts to interactive mode
(scripts) and
upon finishing running a execute in shell
program
• Possible to run functions
from program or check
its variables
to interactive mode where it can receive input from the keyboard. In this mode, you can check the
values of the program’s variables and call its functions.
1The reason that the shell needs to be reset is to eliminate the potential effects of any lingering variables from when the
shell was in interactive mode.
41
2 Python: Execution Environment and How to Use It Next Chapter Table of Contents
2. Set a working directory using the Anaconda Prompt shortcut on the desktop.
1) Right click the Anaconda Prompt icon on the desktop
2) Select “Properties”
3) Add the folder location of your Python script folder to “Start in”
4) Click “Ok”
42
2 Python: Execution Environment and How to Use It Next Chapter Table of Contents
From now on, when you double click this desktop icon, the Anaconda Prompt and idle will work
from the specified folder.
43
2 Python: Execution Environment and How to Use It Next Chapter Table of Contents
44
2 Python: Execution Environment and How to Use It Next Chapter Table of Contents
Figure 2-9 Using the -i option to stay in interactive mode once the program is
finished running
Exercise 2-4 Prepare your own Python learning environment and report it.
45
2 Python: Execution Environment and How to Use It Next Chapter Table of Contents
Figure 2-11 Python online manual (the right side is after selecting Japanese)
1) Installing Anaconda
Press the download button on the site below or scroll down the page and download the Mac OS
installer from the screen that is displayed (if you don’t know which to choose, select the 64-Bit
Graphical Installer).
https://www.anaconda.com/products/individual/
Run the package file that you downloaded to install it (if you don’t understand the choices in the
installer, select “install for me only”).
If you use a Mac equipped with the new M1 CPUs, you will be asked whether to install Rosetta,
which is software that enables you to run programs designed for the older CPUs. Therefore, proceed
with the installation.
Also, it is worth noting that when Anaconda is installed, the terminal environment is changed into a
Conda environment more suitable for running Python (will display “(base)” at the start of every line).
This is all well and good if you only plan to use the terminal for programming exercises, but it may
be problematic when trying to run other software. To return the terminal to the default environment,
input “conda deactivate.” In order to return it to the Conda environment after deactivating it, simply
input “conda activate.”
If the Conda environment does not seemed to be installed (“(base)” is not displayed), run the line
below in the terminal, close it, and then reopen it. The “zsh” at the end is the name of the shell that
runs in the terminal. In the event that a shell other than zsh is being used, simply use the name of that
shell.
/opt/anaconda3/bin/conda init zsh
46
2 Python: Execution Environment and How to Use It Next Chapter Table of Contents
2) Launching IDLE
The terminal is the equivalent to the Windows command prompt. IDLE is run from the terminal.
You can launch it by selecting “Applications” => “Utilities” => “Terminal” in Finder.
Provided that Anaconda is installed, IDLE for Python 3 can be launched by inputting “idle3” using
the keyboard and pressing enter (please note that this is slightly different than the previous section in
which you needed to enter “idle” into the command prompt in Windows).
3) Navigating IDLE
Sometimes, when launching the IDLE Editor, you will be unable to navigate the menus by clicking.
If this happens, just click on another window or the desktop background and then click back to the
IDLE window (it will be titled “Python3.8”). This should fix the problem and enable you to use the
menus.
6) Closing IDLE
Once idle is closed, you can close the terminal window.
47
2 Python: Execution Environment and How to Use It Next Chapter Table of Contents
References
Many books about Python have been published in recent years, so it is likely difficult to decide
which to buy. As such, we will offer a few recommendations. References [2]-[6] are introductions to
Python. While it may be difficult to discern from the title, Reference [7] includes the experiences of
the author, who learned Python via self-study and became a programmer. Reference [8] explains
subjects that are not often included in introductory texts in the field of programming. References [9]
and [10] are geared towards practical applications. References [11] and [12] are texts that discuss the
numerical computing libraries, NumPy, matplotlib, and pandas, that will be touched on in this text.
For books other than these ones, please confirm that they deal with Python Version 3 before using
them.
Bill Lubanovic: Introducing Python: Modern Computing in Simple Package, Oreilly & Associates Inc,
2nd Ed (2019)
柴田淳:みんなの Python 第 4 版,SB クリエイティブ (2017, in Japanese)
大津真:基礎 Python,インプレス (2016, in Japanese))
松浦健一郎,司ゆき:はじめての Python エンジニア入門編,秀和システム (2019, in
Japanese))
大澤文孝:いちばんやさしい Python 入門教室,ソーテック社 (2017, in Japanese))
Cory Althoff: The Self-Taught Programmer: The Definitive Guide to Programming Professionally,
Self-Taught Media (2017)
増井敏克:基礎からのプログラミングリテラシー,技術評論社 (2019, in Japanese))
日経ソフトウェア編:いろいろ作りながら学ぶ!Python 入門,日経 BP(2019, in Japanese))
Al Sweigart: Automate the Boring Stuff with Python, 2nd Edition: Practical Programming for Total
Beginners, No Starch Press, 2nd Ed. (2019)
Wes McKinney: Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython,
O'Reilly Media, 2nd Ed. (2017)
Jake VanderPlas: Python Data Science Handbook: Essential Tools for Working with Data, O'Reilly
Media, (2016)
48
3 Assigning and Operating on Variables Next Chapter Table of Contents
Sequential execution
In the example from the previous chapter
a = 1 + 2
print(a)
the program is executed one line at a time starting from the top. This is called “sequential
execution,” and it is a foundation on which programs are built. In addition, programs can:
Diverge such that certain parts are only executed if certain conditions are met
Repeat certain processes
Call functions, effectively delegating the process to the definition of the function
These subjects will be tackled in later chapters. The source code of Python programs is written in
accordance with what is known as “the flow of execution.”
49
3 Assigning and Operating on Variables Next Chapter Table of Contents
Sample sheet music: Kyoto University school anthem (taken from the link below)
https://www.kyoto-u.ac.jp/ja/about/operation/symbol/song-a.html
In this program, the value assigned to 'a' in line 1 is immediately overwritten in line 2. As such, you
can immediately see that this assignment is meaningless for print(a) in the third line by simply
following what happens to 'a'.
50
3 Assigning and Operating on Variables Next Chapter Table of Contents
Variables with very short names (like one-character names) should only be used when they
are only needed to have a very small scope to bring about their desired effect. In particular, l,
o, and O (lowercase L, lowercase O, and uppercase O) can be confused for the numbers 1 and
0, so it is best to avoid using them.
In general, use lowercase letters instead of uppercase letters. Uppercase letters are generally
used for constants that do not change in value.
Variable names with multiple words should use an underscore (_) as spaces. For example,
“street_name” 2
Use English when possible. There are times where programs grow much larger than initially
expected and come to be used by a large number of people. Often times this can mean people
1 We don’t often encounter the concept of “naming” in everyday life; naming kids or pets are generally the only times we name
anything. However, when using computers, the act of naming things is critically important when it comes to filenames, folder
names, and the like. Naming is one of the most common concepts within programming. It would be best to go in understanding that
good naming sense is needed when programming.
2 Alternatively, it is common to merely capitalize the first letter in each word after the first. In this case, the example would become
“StreetName.”
51
3 Assigning and Operating on Variables Next Chapter Table of Contents
all around the world will be using the program, so it is best to using English naming from the
beginning. 1 3 F4 F
Even beyond variable names, no matter how you write your programs, making them easy to
understand is of critical importance. PEP8[13] is the recommended coding guideline forPython
programs.
1 There was a situation in which a FORTRAN program written by a German professor for his research was rewritten in C. Older
FORTRAN specifications placed limits on variable name length, so the variables were named using abbreviated German which was
completely unintelligible. The professor’s program had thorough English comments accompanying it, so it was still able to fulfill its
purpose.
52
3 Assigning and Operating on Variables Next Chapter Table of Contents
10
10
10 10
Assignment: save value in a Evaluate: obtain the
value of a
a a = 10 a
a
53
3 Assigning and Operating on Variables Next Chapter Table of Contents
+= a += b a = a + b
-= a -= b a = a - b
*= a *= b a = a*b
/= a /= b a = a/b
Note that the “++” and “--” operators commonly used in the C language are not present in Python.
1 Named after George Boole, the man who pioneered the theory behind the algebra of logical operators.
54
3 Assigning and Operating on Variables Next Chapter Table of Contents
It is worth noting that in Python, as with most programming languages, arithmetic using floating-
point numbers is carried out in binary. We often express fractions using decimals, but just like how
1/3 cannot be perfectly expressed as a decimal, 1/10 cannot be perfectly expressed using floating-
point numbers. For a more detailed explanation, please refer column chapter “What Does Float
Mean?”
print(a)
print(b)
print(c)
print(type(a))
print(type(b))
print(type(c))
Although data (generally referred to as “objects”) has various “types” in Python, variables can be
assigned values regardless of the type of data they already contain.
The type() function can be used to find out what type of object is currently assigned to a variable.
10 0.3
Z U
'Japanese' True
X Y
55
3 Assigning and Operating on Variables Next Chapter Table of Contents
Here Here
Z U
Here Here
ⅹ Y
1 Although this is not explained here, a data type called a tuple is being used here behind the scenes.
56
3 Assigning and Operating on Variables Next Chapter Table of Contents
2 4
as the output.
In order to switch the values of two variables, most programming languages assign the value to a
temporary variable (tmp in the example below) as shown below.
a = 1
b = 2
tmp = a
a = b
b = tmp
In Python, this can be done in the following manner.
a = 1
b = 2
a, b = b, a
References
PEP 8 -- Style Guide for Python Code, https://www.python.org/dev/peps/pep-0008/ (Accessed on
2/12/20
57
4 Exercise: Find the Square Root Next Chapter Table of Contents
For simplicity’s sake, think of the two equivalent sides of this triangle as having a length of 1 (for
those who dislike that this differs from the actual length, think of the small side of the A4 paper as
210mm), then we get that the length of the hypotenuse x is equal to
𝑥𝑥 2 = 12 + 12 = 2
according to the Pythagorean theorem. Thus, x has a value equal to the square root of 2 (√2), or
about 1.414. As a matter of fact, this length is the same as the length of the long side of the paper as
seen in the figure below.
58
4 Exercise: Find the Square Root Next Chapter Table of Contents
When folding A-series paper in two, the area is halved but the shape does not change. Setting the
horizontal side’s length as 1 and the vertical side’s length as √2, when one folds it in two the
vertical side’s length becomes √2/2 = 1/√2 and the horizontal edge’s length becomes √2 times
the length of the vertical edge resulting in the shape remaining unchanged.
In reality, A4 paper is 210 mm x 297 mm 1, so the ratio of the vertical side to the horizontal side is
297/210 which is approximately equal to 1.414 ≅ √2. The square root of two is hiding in plain
sight all around us.
However, the square root is defined as the number that, when multiplied with itself, produces
the desired number. It is not apparent how one should find this value. Many students are told
that √2 or perhaps √3 and √5 are used often so they need to be memorized. It kind of leaves a
bad taste in one’s mouth, right?
Let’s use programming to solve for an approximate square root.
1 A0 paper is 841 mm x 1189 mm, so four times the size of A4 paper on each side. This is because at those dimensions the area
becomes 841 mm x 1198 mm = 1,007,518 mm2 which is approximately 1 square meter.
59
4 Exercise: Find the Square Root Next Chapter Table of Contents
approximation r is indeed the square root being solved for, 2/r will become the square root as
well.
The new approximation r NEW is the midpoint (average) between these two values. In this
example, that would be:
2 2
r+ r 2+2 2+1
r NEW = = = = 1.5
2 2 2
At this point, simply repeat the process after setting the value of r to r NEW .
2
1.5 + 1.5 + 1.33333
r NEW = 1.5 = = 1.41666
2 2
As you can see, the number is indeed approaching the square root of 2. Repeating this procedure
over and over will further increase the accuracy of the approximation.
Laying out all of the variables in order to make this into a program yields the following:
1. Assign the number (>0) whose square root is being approximated to the variable x.
x = 2
2. Set an initial value (>0) for the square root approximation and assign this to the variable rnew. In
this example, we will set this value equal to x.
rnew = x
3. Assign the value of rnew to the variable r1.
r1 = nnew
4. You can think of another approximation, x/r1, and assign this value to the variable r2 (r2 = x/r1).
r2 = x/r1
If r1 is the square root of x, r2 will also become the square root of x. If it isn’t, one will be higher
than the true value, and one will be lower, making the true value fall somewhere in between.
5. As such, the new approximation can be set to the average of r1 and r2, (r1 + r2)/2, and update
the variable rnew by assigning it this new value.
rnew = (r1 + r2)/2
6. Repeat steps 3-5 a certain number of times.
60
4 Exercise: Find the Square Root Next Chapter Table of Contents
r2 = x/r1
rnew =
rnew x/r1 (r1 + r2)/2
(r1 + r2)/2
Average of the two,
improved approximation
r2 = x/r1
2nd time
and on Another approximation
Input the source code of Program 4-1 from the following table into the IDLE Editor, save it as p4-
1.py, and run it. (Use ‘space’ instead of ‘␣’)
61
4 Exercise: Find the Square Root Next Chapter Table of Contents
Program 4-1 Program that solves for square roots (ver. 1, p4-1.py)
62
4 Exercise: Find the Square Root Next Chapter Table of Contents
Try a mistake of spelling "rmew" instead of "rnew" in line 4 of Program 4-1, and examine what will
happen if you run the program. See also "19 Appendix: How to Read Error Messages in
IDLE/Python."
Exercise 4-3 Solve for the square root of some other numbers.
1. Alter p4-1.py to solve for the square roots of other positive numbers.
2. Also, try and see what happens when this program attempts to solve for the square root of 0.
Don’t just look at the error message, actually go through the program step-by-step (called
tracing) to see where the problem occurs.
63
5 Lists Next Chapter Table of Contents
5. Lists
64
5 Lists Next Chapter Table of Contents
print(a[0])
prints the element of the list at index zero.
5
Inputting
print(a[2])
prints the third element of the list.
3
65
5 Lists Next Chapter Table of Contents
5.5 Methods
In the previous example, we used the split() method to split a string using spaces as the delimiter.
Data handled by Python are generally referred to as “objects,” and the ways you can operate on this
data is determined in advance, and they change based on the class, type, and value of the data. These
predetermined operations are called “methods,” and can be called by placing a period after the
variable name and then writing the name of the method. In the previous example, the split() method
was called by placing a period after the variable t and then including “split()” after the period.
t = "a textbook of Python"
tlist = t.split()
1 Calling this method without an argument will cause it to default to using spaces as the delimiter. You can specify a desired delimiter.
You can also input help(str.split) into the Python shell to get an explanation of this method.
66
5 Lists Next Chapter Table of Contents
A method can also be called by attaching it to the string itself. For the example above, this would
become:
tlist = "a Python textbook".split()
A few methods for lists will be introduced below, so be sure to remember what a method is and how
to call one. 1
Negative indices
Using an index of -x (x being an integer) refers to the element whose index is x elements from the
end of the list.
1 Methods are very similar to functions, which will be introduced in a later chapter. The major difference is that functions are not tied
to specific objects, while methods are mainly restricted to operating on certain objects. The way to call them is also similar. Classes
exist as a way for programmers to set their own data types that include their own method definitions. These will also be introduced
in a later chapter.
67
5 Lists Next Chapter Table of Contents
a = [5, 1, 3, 4]
print(a[-1])
yields the last element
4
See the table below for reference.
a[ 5, 1, 3, 4 ]
Accessing using a positive index a[0] a[1] a[2] a[3]
Accessing using a negative index a[-4] a[-3] a[-2] a[-1]
Slicing
By making the index [starting index:stopping index], you can take out a select part of a list. This is
called a slice of the list. Please keep in mind that this includes up to the index before the stopping
index.
a = [5, 1, 3 4]
b = a[1:3]
print(b)
yields
[1, 3]
append method
This method adds the arguments to the end of a list.
a = [5, 1, 3 4]
a.append(2)
print(a)
This adds 2 to the end of list a, resulting in
[5, 1, 3, 4, 2]
1 Inputting “help(list)” into the Python shell will enable you to read an explanation on the methods available for lists.
68
5 Lists Next Chapter Table of Contents
extend method
The extend() method is used to combine two lists.
a = [5, 1, 3, 4]
b = [2, 6]
a.extend(b)
print(a)
This will add list b to the end of list a, resulting in the following output:
[5, 1, 3, 4, 2, 6]
Note: using the append method will append the entirety of list b as the final element of list a, as seen
in the example below.
a = [5, 1, 3, 4]
b = [2, 6]
a.append(b)
print(a)
The entirety of list b is appended as the final element of list a, leading to the following output:
[5, 1, 3, 4, [2, 6]]
69
5 Lists Next Chapter Table of Contents
[1, 0, 3]
[0, 2, 3]
but rather
[0, 0, 3]
[0, 0, 3]
This is because variables a and b refer to the exact same list. Checking this by inputting
print(id(a), id(b))
reveals that a and b both have the exact same id (which will vary based on your operating
environment).
In Python, the variables themselves do not contain the data, but rather the location of the data. Thus,
b = a
does not assign the data that a represents to b. Rather, it assigns to b the location of the data (list)
represented by a. As such, any changes to the elements of either a or b are in fact changes made to
the same list.
70
5 Lists Next Chapter Table of Contents
1 2 3
List contents
Here Here
a b
By setting b=a, the reference to the list contents that is
contained in a is assigned to b, making them reference the
same contents
If you wish to handle b as an entity independent of a, you will need to explicitly create a copy and
assign it (when using lists).
b = a.copy()
This same issue can occur when passing lists into a function as arguments. Reference the column
titled "Reference & Duplication."
List contents
1 2 3
Duplication
Here Here
1 2 3
a b
By using b=a.copy() a duplicate of a’s contents are created, and a
reference to these contents is assigned to b.
print(a, b)
An important concept regarding data management in Python is the idea of mutable versus
immutable objects.
As you can see, a and b refer to the same location in line 3. However, by line 5 they refer to different
locations.
72
5 Lists Next Chapter Table of Contents
b = a.copy()
Let’s see what happens when we do the following:
b.appen([5, 6])
print(a)
[[1, 2], [3, 4]]
print(b)
[[1, 2], [3, 4], [5, 6]]
As you would expect, adding append() to b works without affecting a because we created a copy of a
and assigned it to b. Next, try the following:
b[0][0] = 0
print(a)
[[0, 2], [3, 4]]
print(b)
[[0, 2], [3, 4], [5, 6]]
This time, the assignment to the element at index [0][0] of b affected a as well. When we check to
see what a[0] and b[0] each refer to, we get:
print(id(a[0]), id(b[0]))
3188920520008 3188920520008
As you can see, they reference the same object.
This is because the copy() method prepares a new list separate from the target list (copy source) and
then transcribes the locations of each element over to this new list. Thus, when the elements
themselves are lists, the method does not create copies of them. This kind of copy is called a shallow
copy, and a copy in which the elements themselves are also copied is called a deep copy.
73
5 Lists Next Chapter Table of Contents
74
5 Lists Next Chapter Table of Contents
21 rnew␣=␣(r1␣+␣r2)/2
22 print(r1,␣rnew,␣r2)
23 rnew_list.append(rnew)
24 #
25 r1␣=␣rnew
26 r2␣=␣x/r1
27 rnew␣=␣(r1␣+␣r2)/2
28 print(r1,␣rnew,␣r2)
29 rnew_list.append(rnew)
30 print(rnew_list) print the list
In Program 5-1, accuracy of rnew can be estimated by r1 - r2. Modify the program to calculate
the estimated accuracy, store it in another list, say diff_list, and output the list at the end of the
program.
Tuple
Similar to lists, tuples are a data type that consists of multiple elements.
Tuples can be created by simply delimiting the elements on the right-hand side of the equation with
commas and assigning them to the variables on the left-hand side.
a =1, 2
a
(1, 2)
The right-hand side can also be surrounded by parenthesis.
a = (1, 2)
a
(1, 2)
Actually, data is treated as tuples in assignments of and function 'return' statements containing
multiple values. If the left side has a number of variables equal to the number of elements, each
element will be assigned to its respective index.
(b, c) = a
75
5 Lists Next Chapter Table of Contents
b
1
c
2
As with lists, the elements of a tuple can be referenced using [] and the correct index.
print(a[0])
1
However, tuples are immutable objects, so elements cannot be assigned new values after they are
created.
a[0] = 2
The above code will yield the following error:
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
a[0] = 2
TypeError: 'tuple' object does not support item assignment
Dictionaries
With lists, you access elements using a numerical index. This is useful when the numerical order of
the elements is meaningful. Dictionaries are a data type in which elements are accessed using strings
(words). The string that functions as the index is called a “key.”
age = {"Yamada":18, "Tanaka":19}
age
{'Yamada': 18, 'Tanaka': 19}
age["Yamada"]
18
Referencing a key that does not exist will result in an error, but assigning it simply adds it to the
dictionary.
age["Sato"] = 20
age
{'Yamada': 18, 'Tanaka': 19, 'Sato': 20}
The existence of a key in a dictionary can be checked using the 'in' operator.
"Okada" in age
76
5 Lists Next Chapter Table of Contents
False
As with lists, tuples and dictionaries can be used to iterate through for-loops.
77
6 Control Flow Next Chapter Table of Contents
6. Control Flow
6.1 Learning goals of this chapter
In this chapter, you will learn the following methods for controlling the execution of a program.
1. Repeated processing and range() functions using for and while loops
2. Branching using if statements
3. Error handling with try statements
In addition, you will learn the following things which are related to the above points
4. How to write conditional expressions
5. Getting input from the keyboard using the input() function
6. Mathematical functions in Python
7. Format designation for outputted text
There is a lot to learn in this chapter, but the material covered will show up in many programs
throughout the following chapters. You should be able to pick up the material naturally after seeing
many instances of it in use.
It isn’t necessary to learn all the fine details at this point. It is important to separate the concept of
“what can this code do” from the experience of actually writing it. If you remember what certain
code can do and how to write it in a general sense, you can always check out the fine details in your
textbook when the need arises.
Exercise 6-1 Apply 'for' statement to the program of solving square root
Write and run the program contained in the table below.
78
6 Control Flow Next Chapter Table of Contents
Program 6-1 Program that solves for square roots (ver. 2, p6-1.py)
It is possible to indent large portions of text all at once in the IDLE Editor by selecting the text,
holding down the Ctrl key, and pressing the ] key (Ctrl-]). Text can be unindented by using the Ctrl-
[ shortcut.
Writing for-loops 1 5F 6F
The word “for” has many different meanings. In the context of programming, thinking of it as “for
the sake of” can make things difficult to understand. It is better to think of it as closer to its meaning
that is synonymous with “regarding.” for-loops in Python are written in the following manner.
for target variable in range of repetition :
Repeated block
In the p6-1.py example above, the target variable is 'i', the range of repetition is 'range(10),' and the
block is the indented code in lines 7-10.
The range(10) function generates 10 values from 0 to 9 (index of -1). The for-loop puts the generated
values into the variable i and repeats the block.
Translating the for-loop into plain English would yield the following.
For values of the target variable within the range of repetition, repeat the repeated block.
From here onward, explanations of Python’s syntax will be enclosed in a frame like the example
above. Fixed expressions will be written in red, and parts that can change based on context will be
written in black.
1for-loops in Python can be written very effectively using lists and other data types. These usages will be introduced later. This chapter
will cover using for-loops with the range() function.
79
6 Control Flow Next Chapter Table of Contents
Program 6-2 Program that solves for square roots (ver. 2, p6-2.py)
Blocks in Python
Multiple line portions that are all executed as a unit are called blocks. This concept is very important
in the world of programming.
Blocks in Python are denoted by indenting them all by the same amount. This is one of Python’s
defining features.
'for' statements and other lines that require a subsequent block of code require that a colon (:) be
placed at the end of the line.
As indentation carries significant meaning in Python programs, you should stick to the standard
practice of indenting by 4 spaces.
When 'for' statements and other lines that require a subsequent block of code are entered into the
IDLE Editor, it will automatically indent the next lines.
Using full-width spaces in an indent will result in an error. Be careful not to do this, as it
can be a very difficult error to spot. Also, while this can depend on the settings of the editor
being used, using the TAB key will result in an error if the TAB code is input as is.
In other languages, like C, blocks are enclosed in { }. Students who are familiar with other
languages will need to take care to use the correct notation.
80
6 Control Flow Next Chapter Table of Contents
Examine what will happen if you forget to type ":", and run the program. Or also try a mistake of
writing semicolon ";" instead of ":". See also "19 Appendix: How to Read Error Messages in
IDLE/Python."
range() function
To be precise, range is implemented as a class and not a function. However, as it is often used
81
6 Control Flow Next Chapter Table of Contents
similarly to a function, we will refer to it as the range() function in order to facilitate easier
understanding. range() generates a sequence of numbers over a set interval. However, you cannot
know exactly what values are generated by merely looking at the calling of the range() function
itself. The generated values can be checked by creating a list.
Inputting
list(range(10))
into the Python shell yields
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The range() function can be used in three different ways based on what arguments are passed to it.
These usages can be seen below.
Only an ending value is passed as an argument. This takes the form
range(ending_value)
as seen above. This starts at 0 and stops at the integer before the ending value.
Students who aren’t as familiar with programming languages may feel that it’s odd that it starts with
0 and that the ending value is not included. Please refer to the column titled “Starting from 0” for
information about this. The total number of numbers generated still matches the ending value, so
it isn’t that difficult to remember. It is standardized throughout Python to start with 0 and stop at the
value before the specified end point.
Both a starting value and an ending value are passed as arguments.
range(starting_value, ending_value)
The starting value is included, but the ending value is not. A comma must be placed between the two
arguments. Placing a half-width space between the arguments will make it easier to read.
A starting value, ending value, and step width are passed as arguments.
range(starting_value, ending_value, step_width)
Calculating sums
In the previous example, the range function was merely used to specify the number of repetitions,
and the target variable was not used in any particular way. In this example, we will examine a
program that actually utilizes the target variable.
82
6 Control Flow Next Chapter Table of Contents
Nested for-loops
Values for two-dimensional structures such as tables, which contain rows and columns, can be
generated by nesting a for-loop within the block of another for-loop. For example,
83
6 Control Flow Next Chapter Table of Contents
85
6 Control Flow Next Chapter Table of Contents
accuracy of the calculation. Let’s write the program specifying the error to be no more than 10-6.
Accuracy in this manner, in which you specify a certain number of digits past the decimal point, is
known as absolute accuracy. However, in scientific calculations, there are many situations in which it
is better to specify a number of significant digits. For more information on this subject, please refer
to the column titled “Relative Accuracy.”
Program 6-6 Program that solves for square roots (ver. 3, p6-6.py)
86
6 Control Flow Next Chapter Table of Contents
The condition of the ‘while’ statement determines whether to continue, but the condition that
determines whether to activate the ‘break’ statement is a condition that judges whether to
stop. So, in this manner, the conditions are inverted.
Program 6-7 Program that solves for square roots (infinite loop method, p6-7.py)
Structure of a while-loop
The format of a while loop, which repeatedly processes a block of code as long as the given
condition remains true, is as follows:
while conditional expression:
Block of code
The condition is checked before the block of code is executed. This is why, in the example above, the
value of diff is calculated both before entering the while loop and inside of it. Details regarding how
to write conditional expressions will be introduced in the coming sections.
As with for-loops, ‘break’ and ‘continue’ statements can be used when you wish to break from the
loop or enter the next iteration.
Infinite loops
You will also frequently encounter instances in which while loops are used in the manner seen below.
while True:
Block containing a break statement
In this usage, the conditional expression is the constant True, meaning that the condition is always
87
6 Control Flow Next Chapter Table of Contents
satisfied. This means that the while-loop itself will continue infinitely. As such, you need to include a
condition to exit the loop in the form of a ‘break’ statement within the block.
If the break condition is not met, execution of Python will need to be forcibly stopped. You can do
this by using the keyboard shortcut Ctrl-C.
if conditional expression:
Block to be executed if the condition is true
else:
Block to be executed if the condition is false
if conditional expression 1:
Block to be executed if conditional expression 1 is true
elif conditional expression 2:
Block to be executed if conditional expression 1 is false
but conditional expression 2 is true
else:
Block to be executed if both conditions are false
It is worth noting that Python does not have an equivalent to the switch statement found in C in
which you can evaluate three or more conditions to switch between many blocks of code. You can
achieve similar branching using multiple ‘elif’ statements.
88
6 Control Flow Next Chapter Table of Contents
The equivalence operator is two equals signs (==). Please take mental note of this, because it is easy
to mix up with the assignment operator (=).
Also, it is worth noting that floating-point numbers are in many cases merely approximations. As
such, the equivalence operator can potentially produce unexpected behavior. In order to avoid this,
try to make determinations using inequalities when possible.
2) Comparing strings
The operators above can also be used with strings. However, please note that string values are
determined by their character encoding (Unicode) number, so make sure to keep this in mind when
comparing strings in this manner.
In addition to the above, you can use “in” to check whether the string on the left is included within
the string on the right. For example,
'a' in 'abc'
returns
True
3) Logical operations
The logical operators “and,” “or,” and “not” enable you to combine multiple conditions.
89
6 Control Flow Next Chapter Table of Contents
(a == 1) and (b != 0)
90
6 Control Flow Next Chapter Table of Contents
91
6 Control Flow Next Chapter Table of Contents
92
6 Control Flow Next Chapter Table of Contents
In addition, Python is equipped with a library (module) containing many sorts of mathematical
functions. To use this, simply write
import math
to import the module before you use it. Constants and functions defined in the math module can be
called by writing the module name followed by a period and the name of the function or constant you
wish to call. For example:
math.pi
3.141592653589793
math.sqrt(2)
1.4142135623730951
The examples above are for mathematical constant pi and obtaining a square root.
93
6 Control Flow Next Chapter Table of Contents
na = 6.02214076E23
form = "light speed is {0:12.8g} m/s, Avogadroʼs number is {1:12.8g} mol**(-1)"
print(form.format(c, na))
94
6 Control Flow Next Chapter Table of Contents
The above code enables you to pick both the number of digits and the format displayed 1. 8F9 F
The right side of the third line is the string that specifies the format. The portion enclosed in
{} is the format to which the number will be converted.
For example, {0:12.8g} acts upon the 0th element (the number before the colon in the
format) of the argument of the format method below it,
displaying at least 12 digits and going to 8 digits (only 8 digits are displayed to the user)
past the decimal point in g format (one of the formats used to display floating-point
numbers).
Existing formats include 'd' format, which is used to display integers in base 10, ‘e’
format, which is used to display floating-point numbers using exponent representation,
and 'f' format, which displays in fixed-point representation. 'g' format switches between
both of these based on the value of the number.
The form.format(c, na) on the fourth line generates a string in which variables c and na are
converted to strings according to the format specified within form. This code calls the format
method, which is a method belonging to string variables (form in this case). This method is
called by connecting it to the string it acts upon with a period, i.e., “.”.
1 The International System of Units (SI) announced with its 2018 amendments that as of May 20, 2019, The International Prototype of
the Kilogram would be replaced by a new definition of the kilogram based on physical constants. The values for the speed of light
and Avogadro’s number used in this example were not determined by actual measurements, rather they are defined to be certain
quantities.
95
7 Making Kyoto Intersections Next Chapter Table of Contents
Your screen in the IDLE Editor should look like the screenshot below. Make sure that the reserved
keywords for and in, the strings (such as “Sanjyo”), and the print function are all colored
appropriately.
1 There are cases in which Kyoto intersections are named with the east-west street said first (such as ShijyoKawaramachi) and there
are cases in which the north-south street is said first (like HigashiyamaSanjyo). In this example, we will be generating the names
mechanically, so they may differ from the way they are actually said.
96
7 Making Kyoto Intersections Next Chapter Table of Contents
SanjyoHorikawa
SanjyoKarasuma
SanjyoKawaramachi
ShijyoHorikawa
ShijyoKarasuma
ShijyoKawaramachi
GojyoHorikawa
GojyoKarasuma
GojyoKawaramachi
The following example, Street Name in Kanji because of showing a problem of full-width characters.
If you accidentally use a full-width ” to close a string, the text that is colored will change.
Running this will result in an error (invalid syntax). The 四 is displayed in red in the editor. This is
because the double quote closing "三条 (Sanjyo)” is in doble-width character, and hence the double
quote opening "四条 (shijyou)" is interpreted as double quotes that end the strings following ‘”三
条.’
97
7 Making Kyoto Intersections Next Chapter Table of Contents
Using indices
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
sum = 0
for i in range(len(a)):
for j in range(len(a[i])):
sum += a[i][j]
print(sum)
yields the following:
45
1 Usually in Python, statements cannot span multiple lines. This is the case in Python 3, but you can clearly see that the example
above spans multiple lines. If open brackets such as ( do are not closed, then line breaks will not result in an error. In cases where
brackets are not used, a \ is required to achieve the same effect.
98
7 Making Kyoto Intersections Next Chapter Table of Contents
than a number, so “row” and “element” are used for ease of understanding.
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
sum = 0
for row in a:
for element in row:
sum += element
print(sum)
After running this, you can look at cross_table and see that the table was constructed correctly.
>>> cross_table
[['SanjyoHorikawa', 'SanjyoKarasuma', 'SanjyoKawaramachi'],
['ShijyoHorikawa', 'ShijyoKarasuma', 'ShijyoKawaramachi'], ['GojyoHorikawa',
'GojyoKarasuma', 'GojyoKawaramachi']]
As the table in the program above is small, it can be directly defined in line 3. For larger tables, you
99
7 Making Kyoto Intersections Next Chapter Table of Contents
can use something similar to the code below. This example creates a table with 5 rows and 4
columns.
cross_table = []
for i in range(5):
row = []
for j in range(4):
row.append("")
cross_table.append(row)
Set cross_table to be an empty list and then create a list of intersections for each east-west street.
Finally, add (append) this to cross_table.
1) Outputting lists
Let’s output the list with commas (a half-width comma and a space) inserted between intersections
that start with the same east-west street, but with no commas at the end of each line. This would look
like so:
SanjyoKawaramachi, SanjyoKarasuma, SanjyoHorikawa
The print function defaults to ending with a line break, but you can specify the end option to change
the string that displays at the end.
street = ["SanjyoKawaramachi", "SanjyoKarasuma", "SanjyoHorikawa"]
for i in range(len(street)):
if i < len(street)-1:
100
7 Making Kyoto Intersections Next Chapter Table of Contents
print(street[i], end=", ") # Adds “, ” to all but the final of the line
else:
101
8 Test of skills Next Chapter Table of Contents
8. Test of skills
8.1 Learning goals of this chapter
In this chapter, we will test your skills with some practical exercises that span the material
covered so far.
Combine input_check.py and p6-1.py to create a program satisfying the following conditions that
can solve for square roots. Do not try to grapple with everything listed below all at once. Try to sort
out which section of the text is related to each item listed and then update your program to satisfy
each condition one at a time. Test your program and confirm it is working as intended after adding
each one.
1. Use the abs() function to calculate the absolute value.
2. Make the program repeatedly ask for what number’s square root to solve for.
3. Make the program notify the user if the input cannot be converted into a number, then have
the program ask for another input.
4. Make the program notify the user if the input is below 0, then have the program ask for
another input.
If you can, try your hand at the following:
5. Have the program end when the input received from the terminal is “end”
6. Make the calculation accuracy function based on relative accuracy (10-6) instead of absolute
accuracy. After implementing this, try solving for the square roots of very small and very
large numbers (like 1010 and 10-10) and see how the program performs. On relative accuracy,
see the chapter of “Relative Accuracy” in the Column Edition.
8.3 Calculating Pi
Leibnitz Formula
The following formula (Leibnitz Formula) regarding Pi is well-known. The right hand side is an
alternating series of the reciprocals of odd numbers.
π 1 1 1 1
= − + − …
4 1 3 5 7
102
8 Test of skills Next Chapter Table of Contents
The formula used in Chapter 3 and 4 to solve for square roots converges extremely quickly. On the
other hand, this formula is quite simple but is known for converging quite slowly. One must calculate
10 times as many terms in order to raise the accuracy of the calculation by just a single digit.
Write a program that uses the Leibnitz formula to solve for an approximation of Pi. Run the program
with 1, 10, 100, 1000, 10000, 100000, and 1000000 terms on the right hand side and compare the
result to Pi as it is defined by the math module.
It is worth noting that the math module must be imported in order to do this. The value of Pi can be
referenced by using math.pi.
import math
print(math.pi)
3.141592653589793
Hint
In the Leibnitz formula, to solve for the right hand side, for example one can set
n = 10
for i in range(n):
to 0 initially and use a for-loop where i is incremented by 1 with each loop. The denominator for the
i-th term would be i%2 + 1, and the sign would be positive when i%2 ==0 (when i is even), and it
would be negative when i%2 == 1 (when i is odd).
Set of cards
A deck of cards consists of 4 suits with 13 cards each as well as a joker (we will only add one) added
in.
Consider the process of creating a list of card names (one for each combination of suit and value) and
then randomly shuffling them to create a deck of cards. Complete the program seen below using the
program that creates Kyoto intersections as a reference.
103
8 Test of skills Next Chapter Table of Contents
import random
a = [1, 2, 3, 4]
b = random.sample(a, len(a))
print(a)
print(b)
to get the following. b changes with each execution.
[1, 2, 3, 4]
[2, 1, 3, 4]
It is worth noting that the random module also contains the shuffle function, but the way that it
returns a random sorting of the list passed through it as an argument differs from the sample
function. For example, running
import random
a = [1, 2, 3, 4]
random.shuffle(a)
print(a)
yields different results each time, however it will yield results like the ones seen below.
[1, 4, 3, 2]
104
8 Test of skills Next Chapter Table of Contents
From these, the Oji (main streets) running east to west arranged starting from the north are as
follows.
1 As it were, this is apparently a blueprint of Heian-kyō, not an exact map of it as it actually was.
Those who are interested in maps of Kyoto will find [13] by Mr. Kaneda to be a good reference.
105
8 Test of skills Next Chapter Table of Contents
The Oji (main streets) running north to south arranged starting from the east are as follows.
Kyogoku Oji,Higashi no Touin Oji,Nishi no Touin Oji,Omiya Oji,Mibu Oji,
Suzaku Oji,
Kogamon Oji,Nishi Omiya Oji,Sai Oji,Kitsuji Oji,Nishi Kyogoku Oji
List the intersection names using the format “East-west street name” + “North-south street name.”
However, be sure to satisfy the conditions seen below.
Omit the “Oji (main street)” portion from the intersection names as is generally done in present
day Kyoto. For example, as in “Gojo Omiya.”
List intersections starting in the northwestern corner and going east. Once you reach the end of
that east-west street, proceed to the next east-west street immediately to the south starting once
again from the west side. For example, going along the Ichijo Oji would yield the result seen below.
Ichijo Nishi Kyogoku, Ichijo Kitsuji, Ichijo Sai, IchijoNishi Omiya, Ichijo Kogamon, Ichijo
Suzaku, Ichijo Mibu, Ichijo Omiya, Ichijo Nishi no Touin, Ichijo Higashi no Touin, Ichijo
Kyogoku
Delimit the names with ", " when going from west to east, do not start a new line. Start a new line
once you reach the eastern end (do not put a comma at the end).
There are no intersections within the inner part of the Heian Palace, so just display “****” instead
of an intersection name. This special case can also be delimited with a comma. Intersections on
the side of the Heian Palace (except the part on the north side that is not a proper intersection)
should be displayed. In other words:
Display:
Ichijo Nishi Omiya,Ichijo Omiya,
Tsuchimikado Nishi Omiya,Tsuchimikado Omiya,
Konoe Nishi Omiya,Konoe Omiya,
Nakamikado Nishi Omiya,Nakamikado Omiya,
Oimikado Nishi Omiya,Oimikado Omiya,
Nijo Nishi Omiya,Nijo Kogamon,Nijo Suzaku,Nijo Mibu,Nijo Omiya
Hidden:
Ichijo Kogamon, Ichijo Suzaku,Ichijo Mibu,
106
8 Test of skills Next Chapter Table of Contents
Hint
There are various ways one could go about displaying “****” instead of an intersection name. For
example, use
Consider treating from Ichijo Oji to Oimikado Oji as well as anything from Nijo Oji and further
south separately.
If the east-west street is from Ichijo Oji to Oimikado Oji and the north-south street is from
Kogamon Oji to Mibu Oji, change the intersection name to “****” etc.
References
金田 章裕:古地図で見る京都: 『延喜式』から近代地図まで,平凡社 (2016, in
Japanese)
107
9 Encapsulation of Processing Using Functions Next Chapter Table of Contents
Program 9-2 Example of an absolute value function (p9-2.py, returns when possible)
108
9 Encapsulation of Processing Using Functions Next Chapter Table of Contents
Even if there are no parameters, the () after the function name cannot be omitted. The () are also
necessary when calling a function with no parameters.
The explanatory string (it is called a docstring) can be omitted. Reference the column titled
"Documenting a Program."
'return' statements are generally written at the end of the function definition.
'return' statements can be included anywhere and are not limited to the block of an 'if' statement
that checks for certain conditions or to the end of the definition.
If the function does not need a return value, you do not need to include a 'return' statement.
1 There are other ways to treat variables in Python that will be omitted here.
109
9 Encapsulation of Processing Using Functions Next Chapter Table of Contents
parameter used internally within the function are also called formal arguments. Reference the
column titled " Parameters and Arguments."
Arguments can be variables, equations, and function calls. The equation or function will be
evaluated first before the result is passed to the function.
Arguments and parameters do not need to have the same names.
If a number, string, etc. is passed to a function as a argument, the value of the corresponding
parameter will not be affected even if another value is assigned to the parameter within the
function 1. 10F1 1F
Parameters
Arguments
110
9 Encapsulation of Processing Using Functions Next Chapter Table of Contents
1. Receive input, calculate the square root only when the proper input is received, and repeat by
asking for more input.
2. Continually repeat receiving proper input from the terminal followed by solving for the square
root of the input.
If you were to program both of these, 1 would need to solve for the square root, and 2 would need to
obtain proper input from the terminal before solving for the square root. If you were to assume these
actions were performed by the functions get_positive_numeral() and square_root(), the programs
could be written as described below.
1.
while True:
Obtain input x from the terminal and check
whether it is a positive number
if positive number:
r = square_root(x)
print(r)
2.
while True:
x = get_positive_numeral()
r = square_root(x)
print(r)
Writing a fixed batch of processing as a function like this allows you to encapsulate said processing.
The advantages of doing this include:
The program that calls the function becomes much shorter and easier to understand.
The same processing can easily be performed in different parts of the program.
Modifying the definition of the function becomes easier when you separate the program
where it is used from the program where it is defined.
111
9 Encapsulation of Processing Using Functions Next Chapter Table of Contents
square_root(x)
Calculate square root of argument x
>>>
112
9 Encapsulation of Processing Using Functions Next Chapter Table of Contents
Scope of Variables."
Local variables: Variables defined (assigned) within functions can only be used within those
functions. Every time the function is run, these variables will be lost when the function ends.
Parameters are treated as local variables.
Global variables: Variables defined outside of the function can be read to obtain their values.
Assignments to global variables: Within functions, only global variables that are declared with
'global' statement can be assigned values.
Because variables are treated in this manner in Python:
Variables only temporarily needed within functions can be used freely without worrying about
their influence on anything else.
Operating on global variables can be a primary cause of longer programs being difficult to
understand. In Python, reading variables, which is relatively safe, is permitted unconditionally.
On the other hand, writing to variables requires an explicit 'global' statement. In this way, Python
strikes a good balance between convenience and safety.
113
9 Encapsulation of Processing Using Functions Next Chapter Table of Contents
Pass arguments but do not use a return value. Used to execute a set of statements that contains
changing values.
For example, turtle’s forward(100) function seen in the next chapter
Pass no arguments and use a return value. Used to gain information about the state of something.
For example, turtle’s p = pos() seen in the next chapter
There are also functions that read and write to global variables as well as functions that exchange
information using lists and other rewriteable arguments. However, these uses for functions are
often referred to as function side effects. Because they are often difficult to explicitly state within the
source code (particularly the side that calls the function), they have the downside of making
programs more difficult to understand.
No arguments or returns
values; performs fixed actions f() f() Fixed actions
Pass an argument;
performs actions based on
the argument and no
f(y) f(x) Action based on argument
return value
No arguments;
receive a return b = f() f() Obtains state of something
value
114
9 Encapsulation of Processing Using Functions Next Chapter Table of Contents
Default parameters
Within function definitions in Python, it is possible to specify a value to be implicitly used (default
value) in the case that an argument is not passed. This can be done by setting the argument equal to
something (using “=”) within the function definition.
Keyword parameters
When calling a function, arguments are written in order from left to right. However, by writing
“argument name = value”, you can pass a value for only the specified parameter.
Example
def f(a, b=2, c=3):
return a + b + c
115
9 Encapsulation of Processing Using Functions Next Chapter Table of Contents
f(1,1,1)
3
f(1)
6
f(1, c=2)
5
When programming with tkinter in later chapters, there will be a large number of parameters. Thus,
we will be using this method of employing keyword parameters to specify only the necessary ones.
116
10 Playing with Turtle Next Chapter Table of Contents
10.2 Modules
Python offers a variety of libraries in the form of “modules.” To use a module, you must first import
the module in the Python script. There are a few ways you can do this, as seen below.
graphics functionality. The mascot of Scratch, which is a cat that you can make run around using
programming, is descended from turtle graphics. You can also use the Turtle module in Python to
have fun with turtle graphics.
Dealing only with numbers can get tiresome, so in this chapter, we will review what you have
learned up until now using turtle graphics.
It can be used in two ways: procedurally, to manipulate a single turtle with function calls, and
object-oriented, to handle multiple turtles.
1The MIT Media Lab Group that developed Scratch is called “lifelong kindergarten.” Isn’t that a wonderful name?
2IDLE, which is used in this course, and the GUI environment introduced below are similar. Tkinter uses the Tcl/Tk GUI library.
118
10 Playing with Turtle Next Chapter Table of Contents
Note: Do not create Python programs with the same file name as the module name
(turtle.py), or Python will not be able to find the correct module.
119
10 Playing with Turtle Next Chapter Table of Contents
Program 10-2 Program that draws polygons with n faces (incomplete, to be saved as
p10-2.py)
done() End
120
10 Playing with Turtle Next Chapter Table of Contents
Exercise 10-3 Draw regular 7- and 9-sided polygons, and their star equivalents
Make the turtle draw a regular 7-sided polygon, regular 9-sided polygon, and their star equivalents
(where the shape made inside of the star has the same number of vertices as the regular polygon
equivalent).
Exercise 10-4 Categorize the above functions following the usages shown in Section
9.9.
Example program
Program 10-3 Moving multiple turtles (p10-3.py)
121
10 Playing with Turtle Next Chapter Table of Contents
1) 1) Creating a turtle
Objects of the Turtle class are created with the Turtle() command. The function that creates a class
object is called a constructor, which in this case creates a turtle (a construct) 1. In the example below,
by assigning the generated object to the variable t1, the turtle can be referred to by the variable t1
thereafter.
t1 = Turtle()
1 In computer programming, you will often encounter terms with suffixes such as -er, because personifying expressions are useful for
expressing the things you ask a computer to do. The word “computer” also used to mean a person in charge of calculations (a
calculator) until the advent of mechanical calculators.
122
10 Playing with Turtle Next Chapter Table of Contents
radians, so to use it with turtle, where the angle is set in degrees, we convert it as follows.
import math
y = 2
x = 1
angle = math.atan2(y, x)*180/math.pi
x, y
math.atan2(y,x)
1 To calculate coordinates from angles, you can use the trigonometric functions cos and sin, but since these are not suitable as inverse
trigonometric functions, atan2 has been implemented as an extension of the inverse tangent function (atan).
123
10 Playing with Turtle Next Chapter Table of Contents
Drawing Fractals
A shape in which one part is similar to the whole is called a fractal. Fractal figures are interesting
both for what they are drawn as and for the algorithms that draw them.
Use recursion (calling a function within the function itself).
See the column titled "Recursion."
See detour.py and turtle-tree.py. The recursive calls are marked in red.
124
10 Playing with Turtle Next Chapter Table of Contents
One can make a good turtle shape with Python’s Turtle Graphics, but it is hard to make a good hare.
However, one can define and use one’s own as seen in the example below.
1 In Japanese, we use the word “KAME” both for turtle and tortoise, and “USAGI” both for rabbit and hare.
125
10 Playing with Turtle Next Chapter Table of Contents
rdata = ((0, 16), (-2, 14), (-3, 11), (-3, 6), (-2, 5), (-2, 7),
(-1, 10), (-2, 7), (-2, 5), (-3, 6), (-3, 10), (-4,13),
(-5, 13), (-4, 2), (-5, -10), (-4, -10), (-3, -4),
(0, -5), (3, -4), (4, -10), (5, -10), (4, 2), (5, 13),
(4, 13), (3, 10), (3, 6), (2, 5), (2, 7), (1, 10),
(2, 7), (2, 5), (3, 6), (3, 11), (2, 14))
getscreen().register_shape("rabbit", rdata)
126
10 Playing with Turtle Next Chapter Table of Contents
39 getscreen().register_shape("spade",␣s)
40 getscreen().register_shape("clover",␣c)
41 #
42 #␣ Outline␣color␣and␣fill␣color␣of␣the␣generated␣turtle␣shapes
43 #
44 #␣ The␣1st␣row␣of␣shapes␣contains␣the␣6␣shapes␣that␣
45 #␣can␣be␣used␣by␣default
46 shapes␣=␣["arrow",␣"turtle",␣"circle",␣"square",␣"triangle",␣"classic",
47 ␣␣␣␣␣␣␣␣␣␣"rabbit",␣"dia",␣"spade",␣"heart",␣"clover"]
48 colors␣=␣["black",␣"green",␣"black",␣"black",␣"black",␣"black",
49 ␣␣␣␣␣␣␣␣␣␣"red",␣"red",␣"black",␣"red",␣"black"]
50 colors_fill␣=␣["white",␣"white",␣"white",␣"white",␣"white",␣"white",
51 ␣␣␣␣␣␣␣␣␣"white",␣"red",␣"black",␣"red",␣"black"]
52 #
53 #␣In␣the␣turtle␣list␣ttls,␣generate␣a␣turtle␣with␣Turtle(),␣set␣
54 #␣the␣shape␣and␣color␣and␣then␣let␣it␣walk␣for␣a␣bit.
55 ttls␣=␣[]
56 for␣i␣in␣range(len(shapes)):
57 ␣␣␣␣ttls.append(Turtle())
58 ␣␣␣␣ttls[i].up()
59 ␣␣␣␣ttls[i].shape(shapes[i])
60 ␣␣␣␣ttls[i].color(colors[i],␣colors_fill[i])
61 ␣␣␣␣for␣j␣in␣range(i*3):
62 ␣␣␣␣␣␣␣␣ttls[i].fd(20)
63 ␣␣␣␣␣␣␣␣ttls[i].left(10)
64 #
65 #␣Doing␣a␣lap␣together
66 #
67 for␣i␣in␣range(36):
68 ␣␣␣␣for␣i␣in␣range(len(shapes)):
69 ␣␣␣␣␣␣␣␣ttls[i].fd(20)
70 ␣␣␣␣␣␣␣␣ttls[i].left(10)
127
10 Playing with Turtle Next Chapter Table of Contents
128
10 Playing with Turtle Next Chapter Table of Contents
References
Seymour A. Papert: Mindstorms: Children, Computers, And Powerful Ideas, Basic Books (1993)
戸塚滝登著: コンピュータ教育の銀河, 晩成書房 (1995, in Japanese)
Taking a screenshot on a Mac, https://support.apple.com/ja-jp/HT201361(accessed May 7, 2021)
129
10 Playing with Turtle Next Chapter Table of Contents
Ro Source code
w
1 from␣turtle␣import␣*
2 import␣random
3 #␣Import␣random␣module␣as␣you␣will␣be␣using␣random␣numbers
4
5 #␣Variable␣(flag)␣to␣stop␣execution
6 stop_flag␣=␣False
7
8 #␣Function␣called␣when␣the␣mouse␣is␣clicked;␣takes␣x,␣y␣parameters
9 #␣We␣need␣this␣here,␣but␣we␣will␣not␣use␣it
10 #␣Set␣the␣stop␣execution␣flag␣to␣True
11
12 def␣clicked(x,y):
13 ␣␣␣␣global␣stop_flag
14 ␣␣␣␣stop_flag␣=␣True
15
16 #
17 #␣Specify␣what␣to␣do␣when␣the␣mouse␣is␣clicked;
18 # here, call␣the␣clicked␣function.
19 #
20 onscreenclick(clicked)
21
22 speed(0)
23 while(not␣stop_flag):
24 ␣␣␣␣#␣Randomly␣change␣the␣orientation␣in␣the␣range␣of␣-90␣to␣90␣degrees
25 ␣␣␣␣left(random.randint(-90,90))
26 ␣␣␣␣forward(10)
27 ␣␣␣␣#␣If␣the␣turtle's␣position␣is␣more␣than␣a␣certain␣distance␣from␣the␣origin,␣g
o␣back.
28 ␣␣␣␣if␣position()[0]**2+position()[1]**2␣>␣200**2:
29 ␣␣␣␣␣␣␣␣forward(-10)
130
10 Playing with Turtle Next Chapter Table of Contents
131
10 Playing with Turtle Next Chapter Table of Contents
132
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents
Screen
User design
GUI
Framework
Processing
when an event
occurs
User-created
programs
133
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents
and division. Since addition, subtraction, multiplication, and division are operations on two numbers
(binary operations), the user wants to delegate the task to the computer as follows:
The “first number,” “second number,” and “operation to be performed,” are “set,” then
the set operation is “applied.”
The “result of the application” is “obtained”
The words written in blue are “things” that act as the targets of operations such as numbers and
operations, and are indicated by “nouns (phrases).” On the other hand, the words written in red are
“operations” and are indicated by verbs including verbal nouns. These constitute the “model” of the
“calculator” task.
On the other hand, in order for people to interact with this model, you need a user interface that
people can operate. The user interface of a calculator application on a personal computer or a smart
phone is one example, as well as a Python shell where expressions can be entered using the
keyboard. For visually impaired users, interfaces with audio and braille may be required.
If you focus on creating a calculator, you can say that the “model” is shared and only the user
interface changes in various ways. In GUI programming, this concept is called an “MVC
architecture.” Let’s look over the definitions of M, V, and C below. Reference the column titled
"GUI."
M: Model - a model to be computed that provides the framework of the application, essentially
independent of the GUI.
V: View - a program that shows the results obtained by the model to the user, which is handled
by the GUI.
C: Control, a program for user operations on the model, which is handled by the GUI.
CONTROL
User
MODEL
VIEW
GUI
11.4 tkinter
There are several basic software and windowing environments for personal computers, such as
Windows, macOS, Linux/X-Window. Each of them uses different methods for drawing windows.
134
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents
Tcl/Tk is a GUI framework that absorbs the differences between these OS and windowing
environments so that it can be used across different platforms.
tkinter is a package that makes Tcl/Tk available in Python.
Python Application
tkinter
Tcl/Tk
Linux/
Windows macOS
X-window
Terms in tkinter
• Widget: A generic term for a component such as a button that makes up a GUI.
• Container: A receptacle for widgets (groups of widgets).
• Layout manager/geometry manager: A mechanism to adjust the geometric arrangement of
widgets.
• Callback function: A function that is called when a widget is manipulated to perform the
necessary processing.
135
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents
It seems to be common to import the tkinter module using the name tk. (3rd row)
Defining the variables to be used in the program (5th and 6th row).
Definition of the call back function, description of the behavior when the button is pressed
(when an event occurs). (Rows 8 to 25)
136
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents
In this exercise, by making current_dow, which is the variable that indicates the display
position of the days of the week, into a global variable, we are able to get the two buttons to
work properly without messing each other up.
Changing the text attribute of l_dow that displays the day when the button is pressed. (14th
and 22th row)
In the fin() function, we terminate the GUI by calling the window root’s destroy() method.
(25th row)
We have fleshed out the inner workings of the program pretty well now, so next we will
generate and position the windows and widgets that control and display it.
Generate a window using the tk.Tk() method
Use the tl.Frame() method to generate a Frame container that has the window root as its
parent.
Assignment to Frame f window root using the geometry manager grid() method. An
argument is not necessary because f is the only thing that it can be assigned to.
Generate and position label and button widgets positioned on top of Frame widget f
Generation and assignment of Label widgets that will display characters. In this
example, the 0th column to the 3rd column of the 0th row is used for assignment.
Generate and position 3 buttons. The characters that the text attribute displays can
specify the callback function that runs when the command attribute’s button is pressed.
At this point, the GUI is ready, so launch the GUI using the mainloop() method from root. Please
confirm for yourself that 44th row is not executed until the EXIT button is pressed and the GUI
is closed.
The generated window and widget object relationships are showed on Figure
root f
Also, show the behavior carried out by the widgets, call back functions, and global variables on
Figure 11-5 when a button is pressed.
137
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents
Figure 11-5 Behavior carried out by the widgets, call back functions, and global
variables
138
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents
139
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents
43 ␣␣␣␣key(4)
44
45 def␣key5():
46 ␣␣␣␣key(5)
47
48 def␣key6():
49 ␣␣␣␣key(6)
50
51 def␣key7():
52 ␣␣␣␣key(7)
53
54 def␣key8():
55 ␣␣␣␣key(8)
56
57 def␣key9():
58 ␣␣␣␣key(9)
59
60 def␣key0():
61 ␣␣␣␣key(0)
62 The processing of number
63 #␣Functions␣for␣batch␣processing␣number␣keys keys is the same, only the
64 def␣key(n): numbers are different
65 ␣␣␣␣global␣current_number
66 ␣␣␣␣current_number␣=␣current_number␣*␣10␣+␣n
67 ␣␣␣␣show_number(current_number)
68 Processing the Clear key
69 def␣clear():
70 ␣␣␣␣global␣current_number
71 ␣␣␣␣current_number␣=␣0
72 ␣␣␣␣show_number(current_number)
73 Processing the + key
74 def␣plus():
75 ␣␣␣␣do_plus()
76 ␣␣␣␣show_number(current_number)
77 Processing the = key
78 def␣eq():
79 ␣␣␣␣do_eq()
80 ␣␣␣␣show_number(result)
81 Function to display a
82 def␣show_number(num): number entered by the user
83 ␣␣␣␣e.delete(0,tk.END)
84 ␣␣␣␣e.insert(0,str(num))␣
85 ␣␣␣␣
86 #␣Create␣the␣tkinter␣screen
87 Create a window with Tk()
88 root␣=␣tk.Tk() Create a frame container
89 f␣=␣tk.Frame(root) Assign a frame
90 f.grid()
140
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents
91
92 #␣Create␣a␣widget
93 Create a button with
94 b1␣=␣tk.Button(f,text='1',␣command=key1) display text and a
95 b2␣=␣tk.Button(f,text='2',␣command=key2) callback function
96 b3␣=␣tk.Button(f,text='3',␣command=key3)
97 b4␣=␣tk.Button(f,text='4',␣command=key4)
98 b5␣=␣tk.Button(f,text='5',␣command=key5)
99 b6␣=␣tk.Button(f,text='6',␣command=key6)
100 b7␣=␣tk.Button(f,text='7',␣command=key7)
101 b8␣=␣tk.Button(f,text='8',␣command=key8)
102 b9␣=␣tk.Button(f,text='9',␣command=key9)
103 b0␣=␣tk.Button(f,text='0',␣command=key0)
104 bc␣=␣tk.Button(f,text='C',␣command=clear)
105 bp␣=␣tk.Button(f,text='+',␣command=plus)
106 be␣=␣tk.Button(f,text="=",␣command=␣eq)
107
108 #␣Lay␣out␣widgets␣using␣a␣grid␣geometry␣manager
109 Assign the button to the
110 b1.grid(row=3,column=0) frame by specifying its
111 b2.grid(row=3,column=1) position with grid
112 b3.grid(row=3,column=2)
113 b4.grid(row=2,column=0)
114 b5.grid(row=2,column=1)
115 b6.grid(row=2,column=2)
116 b7.grid(row=1,column=0)
117 b8.grid(row=1,column=1)
118 b9.grid(row=1,column=2)
119 b0.grid(row=4,column=0)
120 bc.grid(row=1,column=3)
121 be.grid(row=4,column=3)
122 bp.grid(row=2,column=3)
123 Create an Entry widget for
124 #␣Widget␣to␣display␣numbers text input to display
125 e␣=␣tk.Entry(f) numeric values, and define
126 e.grid(row=0,column=0,columnspan=4) its horizontal size
127 clear()
128 Go to GUI processing with
129 #␣The␣GUI␣starts␣here the mainloop method
130 root.mainloop()
141
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents
# Create a button with f as the parent. The text to display is ʻ1ʼ, command
to execute is key1
1. Create a widget (entry, to display text)
e = tk.Entry(f)
2. Specify the layout
b1.grid(row=3, column=0)
3. Run the GUI
root.mainloop()
142
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents
e.grid(row=0,column=0,columnspan=3) f.grid()
b1.grid(row=3,column=0)
1 1
1 The name comes from a theoretical model called lambda calculus, which is used in computer science.
143
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents
Program 11-3 Setting up a callback function with arguments using a lambda notation
(tkdemo_2term_lambda.py)
144
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents
42
43 def␣plus():
44 ␣␣␣␣do_plus()
45 ␣␣␣␣show_number(current_number)
46
47 def␣eq():
48 ␣␣␣␣do_eq()
49 ␣␣␣␣show_number(result)
50
51 def␣show_number(num):
52 ␣␣␣␣e.delete(0,tk.END)
53 ␣␣␣␣e.insert(0,str(num))␣
54 ␣␣␣␣
55 #␣Create␣the␣tkinter␣screen
56
57 root␣=␣tk.Tk()
58 f␣=␣tk.Frame(root)
59 f.grid()
60
61 #␣Create␣a␣widget
62
63 b1␣=␣tk.Button(f,text='1',␣command=lambda:key(1))
64 b2␣=␣tk.Button(f,text='2',␣command=␣lambda:key(2))
65 b3␣=␣tk.Button(f,text='3',␣command=␣lambda:key(3))
66 b4␣=␣tk.Button(f,text='4',␣command=␣lambda:key(4))
67 b5␣=␣tk.Button(f,text='5',␣command=␣lambda:key(5))
68 b6␣=␣tk.Button(f,text='6',␣command=␣lambda:key(6))
69 b7␣=␣tk.Button(f,text='7',␣command=␣lambda:key(7))
70 b8␣=␣tk.Button(f,text='8',␣command=␣lambda:key(8))
71 b9␣=␣tk.Button(f,text='9',␣command=␣lambda:key(9))
72 b0␣=␣tk.Button(f,text='0',␣command=␣lambda:key(0))
73 bc␣=␣tk.Button(f,text='C',␣command=clear)
74 bp␣=␣tk.Button(f,text='+',␣command=plus)
75 be␣=␣tk.Button(f,text="=",␣command=␣eq)
76
77 #␣Lay␣out␣widgets␣using␣a␣grid␣geometry␣manager
78
79 b1.grid(row=3,column=0)
80 b2.grid(row=3,column=1)
81 b3.grid(row=3,column=2)
82 b4.grid(row=2,column=0)
83 b5.grid(row=2,column=1)
84 b6.grid(row=2,column=2)
85 b7.grid(row=1,column=0)
86 b8.grid(row=1,column=1)
87 b9.grid(row=1,column=2)
88 b0.grid(row=4,column=0)
89 bc.grid(row=1,column=3)
145
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents
90 be.grid(row=4,column=3)
91 bp.grid(row=2,column=3)
92
93 #␣Widget␣to␣display␣numbers
94 e␣=␣tk.Entry(f)
95 e.grid(row=0,column=0,columnspan=4)
96 clear()
97
98 #␣The␣GUI␣starts␣here
99 root.mainloop()
146
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents
To reference the current value, call the cget() method with the attribute as an argument. Note that the
attribute is given as a string.
b.cget(“size”)
Exercise 11-3 Extending the Calculator to Four Arithmetic Operations (Skill Test)
Extend the addition calculator so that it can perform the four primary arithmetic operations.
However, keep the following in mind.
You must consider the placement of the buttons.
For division, since a divide by zero error may occur, when the second term is zero, either do
nothing or display an error.
Omit the decimal point for division. The operator for finding the integer quotient in Python is
“//.”
Hint: The program needs to be extended in the following two ways.
147
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents
148
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents
149
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents
25 ␣␣␣␣global␣second_term
26 ␣␣␣␣global␣result
27 ␣␣␣␣global␣current_number
28 ␣␣␣␣second_term␣=␣current_number
29 ␣␣␣␣result␣=␣first_term␣+␣second_term
30 ␣␣␣␣current_number␣=␣0
31 #
32 #␣Create␣a␣class␣called␣MyFrame␣that␣inherits␣from␣tk.Frame
33 #␣Then␣you␣can␣add␣widgets␣and␣callback␣functions␣(methods)␣in␣it,
34 #␣Which␣is␣the␣standard␣way␣of␣using␣tkinter
35 #
36 class␣MyFrame(tk.Frame):
37 #
38 #␣␣__init__␣is␣the␣initialization␣method␣used␣to␣create␣class␣obje
cts;
39 #␣It␣has␣two␣underscores␣on␣each␣side
40 ␣␣␣␣def␣__init__(self,␣master␣=␣None):
41 ␣␣␣␣␣␣␣␣super().__init__(master)
42 #␣Create␣a␣widget␣that␣will␣not␣be␣referenced␣later␣(with␣local␣va
riables)
43 ␣␣␣␣␣␣␣␣b1␣=␣tk.Button(self,text='1',␣command=lambda:self.key(1))
44 ␣␣␣␣␣␣␣␣b2␣=␣tk.Button(self,text='2',␣command=lambda:self.key(2))
45 ␣␣␣␣␣␣␣␣b3␣=␣tk.Button(self,text='3',␣command=lambda:self.key(3))
46 ␣␣␣␣␣␣␣␣b4␣=␣tk.Button(self,text='4',␣command=lambda:self.key(4))
47 ␣␣␣␣␣␣␣␣b5␣=␣tk.Button(self,text='5',␣command=lambda:self.key(5))
48 ␣␣␣␣␣␣␣␣b6␣=␣tk.Button(self,text='6',␣command=lambda:self.key(6))
49 ␣␣␣␣␣␣␣␣b7␣=␣tk.Button(self,text='7',␣command=lambda:self.key(7))
50 ␣␣␣␣␣␣␣␣b8␣=␣tk.Button(self,text='8',␣command=lambda:self.key(8))
51 ␣␣␣␣␣␣␣␣b9␣=␣tk.Button(self,text='9',␣command=lambda:self.key(9))
52 ␣␣␣␣␣␣␣␣b0␣=␣tk.Button(self,text='0',␣command=lambda:self.key(0))
53 ␣␣␣␣␣␣␣␣bc␣=␣tk.Button(self,text='C',␣command=self.clear)
54 ␣␣␣␣␣␣␣␣bp␣=␣tk.Button(self,text='+',␣command=self.plus)
55 ␣␣␣␣␣␣␣␣be␣=␣tk.Button(self,text="=",␣command=self.eq)
56
57 #␣Lay␣out␣widgets␣using␣a␣grid␣geometry␣manager
58 ␣␣␣␣␣␣␣␣b1.grid(row=3,column=0)
59 ␣␣␣␣␣␣␣␣b2.grid(row=3,column=1)
60 ␣␣␣␣␣␣␣␣b3.grid(row=3,column=2)
61 ␣␣␣␣␣␣␣␣b4.grid(row=2,column=0)
62 ␣␣␣␣␣␣␣␣b5.grid(row=2,column=1)
63 ␣␣␣␣␣␣␣␣b6.grid(row=2,column=2)
64 ␣␣␣␣␣␣␣␣b7.grid(row=1,column=0)
65 ␣␣␣␣␣␣␣␣b8.grid(row=1,column=1)
66 ␣␣␣␣␣␣␣␣b9.grid(row=1,column=2)
67 ␣␣␣␣␣␣␣␣b0.grid(row=4,column=0)
68 ␣␣␣␣␣␣␣␣bc.grid(row=1,column=3)
69 ␣␣␣␣␣␣␣␣be.grid(row=4,column=3)
70 ␣␣␣␣␣␣␣␣bp.grid(row=2,column=3)
150
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents
71
72 #␣Widgets␣and␣class␣objects␣that␣display␣numbers␣that␣will
73 #␣be␣referenced␣by␣other␣methods␣are␣created␣as␣an␣instance
74 #␣variable␣with␣the␣"self."␣prefix
75 ␣␣␣␣␣␣␣␣self.e␣=␣tk.Entry(self)
76 ␣␣␣␣␣␣␣␣self.e.grid(row=0,column=0,columnspan=4)
77 #␣When␣defining␣a␣class,
78 #␣The␣first␣parameter␣of␣a␣method␣is␣"self."
79 #␣Inside␣of␣a␣class,␣the␣class␣object␣variable␣and␣method␣also
80 #␣reference␣"self"
81 ␣␣␣␣def␣key(self,n):
82 ␣␣␣␣␣␣␣␣global␣current_number
83 ␣␣␣␣␣␣␣␣current_number␣=␣current_number␣*␣10␣+␣n
84 ␣␣␣␣␣␣␣␣self.show_number(current_number)
85
86 ␣␣␣␣def␣clear(self):
87 ␣␣␣␣␣␣␣␣global␣current_number
88 ␣␣␣␣␣␣␣␣current_number␣=␣0
89 ␣␣␣␣␣␣␣␣self.show_number(current_number)
90
91 ␣␣␣␣def␣plus(self):
92 ␣␣␣␣␣␣␣␣do_plus()
93 ␣␣␣␣␣␣␣␣self.show_number(current_number)
94
95 ␣␣␣␣def␣eq(self):
96 ␣␣␣␣␣␣␣␣do_eq()
97 ␣␣␣␣␣␣␣␣self.show_number(result)
98
99 ␣␣␣␣def␣show_number(self,␣num):
100 ␣␣␣␣␣␣␣self.e.delete(0,tk.END)
101 ␣␣␣␣␣␣␣self.e.insert(0,str(num))
102 ␣␣␣␣␣␣␣␣
103 #
104 #␣Main␣program␣from␣here
105 #
106 root␣=␣tk.Tk()
107 f = MyFrame(root) Use the
108 f.pack() extended
109 f.mainloop() class. pack()
is a geometry
manager.
151
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents
Card images
In this section, we will make use of the exercise that displays images of cards. For the images, we
will use the card images that have been published at the site below.
https://www.kenney.nl/assets/boardgame-pack
It is worth noting that the terms of use are as seen below.
License: (CC0 1.0 Universal) You're free to use these game assets in any
project, personal or commercial. There's no need to ask permission before
using these. Giving attribution is not required, but is greatly appreciated!
In the package that one downloads, one will find image data in the form of PNG files within the
Cards folder found inside the PNG folder. The image size (number of pixels) is 140 x 190.
152
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents
7 ranks␣=␣["A",␣"2",␣"3",␣"4",␣"5",␣"6",␣"7",␣
8 ␣␣␣␣␣␣␣␣␣"8",␣"9",␣"10",␣"J",␣"Q",␣"K"]
9 joker␣=␣["Joker"]
10
11 #␣List␣that␣stores␣card␣filenames
12 cardImages␣=␣[]
13 #␣Card␣reverse␣image␣name
14 for␣b␣in␣backs:
15 ␣␣␣␣for␣i␣in␣range(1,6): Generate image filenames
16 ␣␣␣␣␣␣␣␣card␣=␣"cardBack_"␣+␣b␣+␣str(i)␣+␣".png" in order.
17 ␣␣␣␣␣␣␣␣cardImages.append(card)
18 #␣Card␣front␣image␣name
19 for␣s␣in␣suits:
20 ␣␣␣␣for␣r␣in␣ranks:
21 ␣␣␣␣␣␣␣␣card␣=␣"card"␣+␣s␣+␣r␣+␣".png"
22 ␣␣␣␣␣␣␣␣cardImages.append(card)
23 #␣Joker␣image␣name
24 cardImages.append("card"␣+␣joker[0]␣+␣".png")
25
26 root␣=␣tk.Tk()
27
28 #␣Read␣the␣image␣files␣in␣order␣and␣create␣a␣list␣of
29 #␣PhotoImage␣class␣objects
30 cardImageWidgets␣=␣[] Specify a pass to the
31 for␣i␣in␣cardImages: file, read the image
32 ␣␣␣␣image␣=␣tk.PhotoImage(file␣=␣"cards/"␣+␣i) file, and generate a
33 ␣␣␣␣cardImageWidgets.append(image) PhotoImage class object.
34
35 #␣Index␣to␣access␣image
36 cardIndex␣=␣0 Two callback functions
37
38 def␣back():
39 ␣␣␣␣'callback␣function␣that␣returns␣to␣previous␣image'
40 ␣␣␣␣global␣cardIndex
41 ␣␣␣␣cardIndex␣-=␣1
42 ␣␣␣␣if␣cardIndex␣<␣0:
43 ␣␣␣␣␣␣␣␣cardIndex␣=␣len(cardImageWidgets)␣-␣1
44 ␣␣␣␣#␣Convert␣label␣image␣attribute
45 ␣␣␣␣l["image"]␣=␣cardImageWidgets[cardIndex]
46
47 def␣forward():
48 ␣␣␣␣'callback␣function␣that␣returns␣to␣next␣image'
49 ␣␣␣␣global␣cardIndex
50 ␣␣␣␣cardIndex␣+=␣1
51 ␣␣␣␣if␣cardIndex␣>=␣len(cardImageWidgets):
52 ␣␣␣␣␣␣␣␣cardIndex␣=␣0
53 ␣␣␣␣l["image"]␣=␣cardImageWidgets[cardIndex]
54
55 f␣=␣tk.Frame(root)
56 f.pack() Main program starts here
57 #␣″ Return″ ␣button␣and␣″ Next″ ␣button
58 bb␣=␣tk.Button(f,␣text␣=␣"<",␣command␣=␣back)
59 bf␣=␣tk.Button(f,␣text␣=␣">",␣command␣=␣forward)
153
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents
Running the program results in the display shown below (examples of a few cards are shown).
References
There are many resources on the internet explaining how to use Tkinter. The use of tkinter is slightly
different between Python 2 and Python 3. For example, the module to import is Tkinter in Python 2,
while it is tkinter in Python 3. Please be careful when referring to articles online.
Tkinter 8.5 reference: a GUI for Python
https://infohost.nmt.edu/tcc/help/pubs/tkinter/web/index.html
154
12 Creating a GUI Application with Tkinter (2) Next Chapter Table of Contents
Using after
Time display
Waiting for input Call_back process Register after
As a caveat, note that this way of doing things is not suitable for applications that require a lot of
computation time, such as simulations. You need to look into the use of libraries and concepts such
as threads to run programs in parallel.
and second hands, and the date display can be turned on and off with a button. Refer to Figure 12-3
for calculating the position of the clock hands.
The following program is implemented by extending the Frame class. Some lines are longer than
others; in the list below, the lines without numbers are a part of long single lines that have had the
text wrapped onto a new line. Please be careful when you type this code out.
12
x = x0 + r * cos(θ)
(x0, y0)
9 3
θ = (seconds/60)*360-90
r
y = y0 + r * sin(θ)
y 6
(x, y)
156
12 Creating a GUI Application with Tkinter (2) Next Chapter Table of Contents
Source code
The program is a bit complicated, so at first, we will look at the code without the button to turn
on/off the date display. The code with the button added is shown further below.
157
12 Creating a GUI Application with Tkinter (2) Next Chapter Table of Contents
33 ␣␣␣␣␣␣␣␣self.hour␣=␣time.localtime().tm_hour
34 ␣␣␣␣#
35 ␣␣␣␣#␣Draw␣a␣dynamic␣display
36 ␣␣␣␣#
37 ␣␣␣␣def␣display(self):
38 ␣␣␣␣␣␣␣␣#
39 ␣␣␣␣␣␣␣␣#␣Draw␣the␣second␣hand
40 ␣␣␣␣␣␣␣␣#
41 ␣␣␣␣␣␣␣␣self.sec␣=␣time.localtime().tm_sec
42 ␣␣␣␣␣␣␣␣angle␣=␣math.radians(self.sec*360/60␣-␣90)
43 ␣␣␣␣␣␣␣␣x0␣=␣self.size/2␣-␣math.cos(angle)*self.size/2*0.1
44 ␣␣␣␣␣␣␣␣y0␣=␣self.size/2␣-␣math.sin(angle)*self.size/2*0.1
45 ␣␣␣␣␣␣␣␣x␣=␣self.size/2␣+␣math.cos(angle)*self.size/2*0.75
46 ␣␣␣␣␣␣␣␣y␣=␣self.size/2␣+␣math.sin(angle)*self.size/2*0.75
47 ␣␣␣␣␣␣␣␣#
48 ␣␣␣␣␣␣␣␣#␣Search␣for␣the␣previous␣drawing␣using␣its␣tag,␣de
lete␣it,␣then␣redraw␣the␣new␣line
49 ␣␣␣␣␣␣␣␣#
50 ␣␣␣␣␣␣␣␣self.clock.delete("SEC")
51 ␣␣␣␣␣␣␣␣self.clock.create_line(x0,y0,x,y,␣width=1,␣fill="re
d",␣tag="SEC")
52 ␣␣␣␣␣␣␣␣#
53 ␣␣␣␣␣␣␣␣#␣Draw␣the␣minute␣and␣hour␣hands,␣and␣make␣the␣hour
␣hand␣move␣slightly␣every␣minute
54 ␣␣␣␣␣␣␣␣#
55 ␣␣␣␣␣␣␣␣x0␣=␣self.size/2
56 ␣␣␣␣␣␣␣␣y0␣=␣self.size/2
57 ␣␣␣␣␣␣␣␣self.min␣=␣time.localtime().tm_min
58 ␣␣␣␣␣␣␣␣angle␣=␣math.radians(self.min*360/60␣-␣90)
59 ␣␣␣␣␣␣␣␣x␣=␣self.size/2␣+␣math.cos(angle)*self.size/2*0.65
60 ␣␣␣␣␣␣␣␣y␣=␣self.size/2␣+␣math.sin(angle)*self.size/2*0.65
61 ␣␣␣␣␣␣␣␣self.clock.delete("MIN")
62 ␣␣␣␣␣␣␣␣self.clock.create_line(x0,y0,x,y,␣width=3,␣fill="bl
ue",␣tag="MIN")
63
64 ␣␣␣␣␣␣␣␣self.hour␣=␣time.localtime().tm_hour
65 ␣␣␣␣␣␣␣␣x0␣=␣self.size/2
66 ␣␣␣␣␣␣␣␣y0␣=␣self.size/2
67 ␣␣␣␣␣␣␣␣angle␣=␣math.radians((self.hour%12+self.min/60)*360
/12␣-␣90)
68 ␣␣␣␣␣␣␣␣x␣=␣self.size/2␣+␣math.cos(angle)*self.size/2*0.55
69 ␣␣␣␣␣␣␣␣y␣=␣self.size/2␣+␣math.sin(angle)*self.size/2*0.55
70 ␣␣␣␣␣␣␣␣self.clock.delete("HOUR")
71 ␣␣␣␣␣␣␣␣self.clock.create_line(x0,y0,x,y,␣width=3,␣fill="gr
een",␣tag="HOUR")
72 ␣␣␣␣␣␣␣␣#
73 ␣␣␣␣␣␣␣␣#␣Draw␣the␣date␣
74 ␣␣␣␣␣␣␣␣#
158
12 Creating a GUI Application with Tkinter (2) Next Chapter Table of Contents
75 ␣␣␣␣␣␣␣␣x␣=␣self.size/2
76 ␣␣␣␣␣␣␣␣y␣=␣self.size/2␣+␣20
77 ␣␣␣␣␣␣␣␣text␣=␣time.strftime('%Y/%m/%d␣%H:%M:%S')
78 ␣␣␣␣␣␣␣␣self.clock.delete("TIME")
79 ␣␣␣␣␣␣␣␣self.clock.create_text(x,␣y,␣text=text,␣font=("",12
),␣fill="black",␣tag="TIME")
80 ␣␣␣␣␣␣␣␣#
81 ␣␣␣␣␣␣␣␣#␣Call␣again␣in␣100␣milliseconds
82 ␣␣␣␣␣␣␣␣#␣
83 ␣␣␣␣␣␣␣␣self.after(100,␣self.display)
84
85 root␣=␣tk.Tk() Main program
86 f␣=␣MyFrame(root) starts here
87 f.pack()
88 f.display() Call display first
89 root.mainloop()
159
12 Creating a GUI Application with Tkinter (2) Next Chapter Table of Contents
24 ␣␣␣␣␣␣␣␣for␣number␣in␣range(1,12+1):
25 ␣␣␣␣␣␣␣␣␣␣␣␣x␣=␣self.size/2␣+␣math.cos(math.radians(number*
360/12␣-␣90))*self.size/2*0.85
26 ␣␣␣␣␣␣␣␣␣␣␣␣y␣=␣self.size/2␣+␣math.sin(math.radians(number*
360/12␣-␣90))*self.size/2*0.85
27 ␣␣␣␣␣␣␣␣␣␣␣␣self.clock.create_text(x,y,text=str(number),␣fi
ll="black",␣font␣=("",14))
28 #
29 #␣Create␣a␣button␣to␣toggle␣the␣date␣display␣on/off
30 #
31 ␣␣␣␣␣␣␣␣self.b␣=␣tk.Button(self,␣text="Show␣Date",␣font=(""
,14),␣command␣=␣self.toggle)
32 ␣␣␣␣␣␣␣␣self.b.grid(row␣=␣1,␣column␣=␣0)
33 #
34 #␣Create␣instance␣variables␣to␣check␣for␣the␣passage␣of␣tim
e
35 #
36 ␣␣␣␣␣␣␣␣self.sec␣=␣time.localtime().tm_sec
37 ␣␣␣␣␣␣␣␣self.min␣=␣time.localtime().tm_min
38 ␣␣␣␣␣␣␣␣self.hour␣=␣time.localtime().tm_hour
39 ␣␣␣␣␣␣␣␣self.show_date␣=␣False
40
41 ␣␣␣␣#
42 ␣␣␣␣#␣Callback␣when␣the␣button␣is␣pressed
43 ␣␣␣␣#
44 ␣␣␣␣def␣toggle(self):
45 ␣␣␣␣␣␣␣␣if␣self.show_date: Is the date
46 ␣␣␣␣␣␣␣␣␣␣␣␣self.b.configure(text="Show␣Date") displayed?
47 ␣␣␣␣␣␣␣␣else: Change the button
48 ␣␣␣␣␣␣␣␣␣␣␣␣self.b.configure(text="Hide␣Date") text
49 ␣␣␣␣␣␣␣␣self.show_date␣=␣not␣self.show_date Invert whether or
50 not the date is
51 ␣␣␣␣# shown
52 ␣␣␣␣#␣Draw␣a␣dynamic␣display
53 ␣␣␣␣#
54 ␣␣␣␣def␣display(self):
55 ␣␣␣␣␣␣␣␣#
56 ␣␣␣␣␣␣␣␣#␣␣Draw␣the␣second␣hand
57 ␣␣␣␣␣␣␣␣#
58 ␣␣␣␣␣␣␣␣self.sec␣=␣time.localtime().tm_sec
59 ␣␣␣␣␣␣␣␣angle␣=␣math.radians(self.sec*360/60␣-␣90)
60 ␣␣␣␣␣␣␣␣x0␣=␣self.size/2␣-␣math.cos(angle)*self.size/2*0.1
61 ␣␣␣␣␣␣␣␣y0␣=␣self.size/2␣-␣math.sin(angle)*self.size/2*0.1
62 ␣␣␣␣␣␣␣␣x␣=␣self.size/2␣+␣math.cos(angle)*self.size/2*0.75
63 ␣␣␣␣␣␣␣␣y␣=␣self.size/2␣+␣math.sin(angle)*self.size/2*0.75
64 ␣␣␣␣␣␣␣␣#
65 ␣␣␣␣␣␣␣␣#␣Search␣for␣the␣previous␣drawing␣using␣its␣tag,␣de
lete␣it,␣then␣redraw␣the␣new␣line
160
12 Creating a GUI Application with Tkinter (2) Next Chapter Table of Contents
66 ␣␣␣␣␣␣␣␣#
67 ␣␣␣␣␣␣␣␣self.clock.delete("SEC")
68 ␣␣␣␣␣␣␣␣self.clock.create_line(x0,y0,x,y,␣width=1,␣fill="re
d",␣tag="SEC")
69 ␣␣␣␣␣␣␣␣#
70 ␣␣␣␣␣␣␣␣#␣Draw␣the␣minute␣and␣hour␣hands,␣and␣make␣the␣hour
␣hand␣move␣slightly␣every␣minute
71 ␣␣␣␣␣␣␣␣#
72 ␣␣␣␣␣␣␣␣self.min␣=␣time.localtime().tm_min
73 ␣␣␣␣␣␣␣␣x0␣=␣self.size/2
74 ␣␣␣␣␣␣␣␣y0␣=␣self.size/2
75 ␣␣␣␣␣␣␣␣angle␣=␣math.radians(self.min*360/60␣-␣90)
76 ␣␣␣␣␣␣␣␣x␣=␣self.size/2␣+␣math.cos(angle)*self.size/2*0.65
77 ␣␣␣␣␣␣␣␣y␣=␣self.size/2␣+␣math.sin(angle)*self.size/2*0.65
78 ␣␣␣␣␣␣␣␣self.clock.delete("MIN")
79 ␣␣␣␣␣␣␣␣self.clock.create_line(x0,y0,x,y,␣width=3,␣fill="bl
ue",␣tag="MIN")
80 ␣␣␣␣␣␣␣␣self.hour␣=␣time.localtime().tm_hour
81 ␣␣␣␣␣␣␣␣x0␣=␣self.size/2
82 ␣␣␣␣␣␣␣␣y0␣=␣self.size/2
␣␣␣␣␣␣␣␣angle␣=␣math.radians((self.hour%12+self.min/60)*360
83 /12␣-␣90)
84 ␣␣␣␣␣␣␣␣x␣=␣self.size/2␣+␣math.cos(angle)*self.size/2*0.55
85 ␣␣␣␣␣␣␣␣y␣=␣self.size/2␣+␣math.sin(angle)*self.size/2*0.55
86 ␣␣␣␣␣␣␣␣self.clock.delete("HOUR")
87 ␣␣␣␣␣␣␣␣self.clock.create_line(x0,y0,x,y,␣width=3,␣fill=
"green",␣tag="HOUR")
88
89 ␣␣␣␣␣␣␣␣#
90 ␣␣␣␣␣␣␣␣#␣Draw␣the␣date
91 ␣␣␣␣␣␣␣␣#
92 ␣␣␣␣␣␣␣␣x␣=␣self.size/2
93 ␣␣␣␣␣␣␣␣y␣=␣self.size/2␣+␣20
94 ␣␣␣␣␣␣␣␣text␣=␣time.strftime('%Y/%m/%d␣%H:%M:%S')
95 ␣␣␣␣␣␣␣␣self.clock.delete("TIME") Draw only when
96 ␣␣␣␣␣␣␣␣if␣self.show_date: the date is
97 ␣␣␣␣␣␣␣␣␣␣␣␣self.clock.create_text(x,␣y,␣text=text,␣font=(" displayed
",12),␣fill="black",␣tag="TIME")
98 ␣␣␣␣␣␣␣␣#
99 ␣␣␣␣␣␣␣␣#␣Call␣again␣in␣100␣milliseconds
100 ␣␣␣␣␣␣␣␣#␣
101 ␣␣␣␣␣␣␣␣self.after(100,␣self.display)
102 Main program
103 root␣=␣tk.Tk() starts here
104 f␣=␣MyFrame(root)
105 f.pack()
106 f.display()
107 root.mainloop()
161
12 Creating a GUI Application with Tkinter (2) Next Chapter Table of Contents
162
12 Creating a GUI Application with Tkinter (2) Next Chapter Table of Contents
2. Add another button to toggle the display of the second hand on and off.
Hint: Review the role of the self.toggle method, and figure out how to do the same thing for the
second hand display.
toggle display
Button
If self.show_date
Yes
Draw the date
Register in after
show_date
163
13 Classes Next Chapter Table of Contents
13. Classes
13.1 Learning goals of this chapter
You have already used class objects in turtle graphics and tkinter. Here, you will learn about classes
in more detail.
You will learn about the concept of object-oriented programming.
You will define and use classes.
You will learn about variables that are used in classes.
164
13 Classes Next Chapter Table of Contents
Source code
Program 13-1 CUI calculator program (p13-1.py)
Example
First term 1
Operation +
Second term 2
Result 3
First term 10
Operation -
Second term 5
Result 5
Press Ctrl-C to interrupt
First term
Traceback (most recent call last):
File "M:/Documents/Python Scripts/class_demo.py", line 17, in <module>
f = int(input("First term "))
KeyboardInterrupt
>>>
165
13 Classes Next Chapter Table of Contents
The name of the class (Calculator in this example) can be determined by the same rules as for
variables, but the convention is to capitalize the first letter and write the rest in lowercase. When
using multiple words in a name, “camel case” is used, whereby the first letter of each word is
capitalized (with no spaces in between words) and the rest of the letters are lowercase. (For
example, FunctionCalculator)
The definition of the method __init__(self) (lines 2-6): methods and variables beginning with
__ (two underscores) often have special roles in Python.
__infit__() is a method that is executed whenever a class object is created.
It is used to initialize variables in the class, and it is also called a "constructor" because it takes
a role of making a object. Reference the column titled " Personification." Unlike functions, class
method definitions must always contain a parameter, which is usually named self by
convention. The value of this parameter is automatically given by the system when the method
is called. There is no need to write the first argument when calling a class method.
Instance variables and initialization (lines 3-6): The __init__() method initializes the variables
used in the class.
Variables that begin with self. are called “instance variables.” They are object-specific
variables that can always be used within the object whenever an object of that class is
created.
On the other hand, variables without self. are treated as local variables like in functions, and
are discarded when the method is finished processing.
Definition of the method do_operation() (lines 8-12): This is a method that can be called
explicitly, which performs the specified operation on the first and second terms and prints the
result. Note the self. in the code; the parameter self is attached to the instance variables when
they are processed.
Main program (line 14 onward): This is a calculator program that receives text input from the
terminal and executes it. It is written in an infinite loop, so use Ctrl-C to escape.
Generating a class-type object (line 15). Class-type objects are created by calling the class
name like a function and assigning it to a variable.
Variable = ClassName ()
166
13 Classes Next Chapter Table of Contents
Class Variables
Creation: Declared in the class definition, outside of the method definition.
Behavior: Acts as a variable shared by the class.
Access: Can be referenced without creating a class object by writing
ClassName.variablename in the code.
Instance Variables
Creation: Declared by adding the self. prefix in the method definition.
Behavior: Each instance that is created is treated as an independent variable. The value is
retained as long as the instance is in use.
Access: In the definition of a method, refer to it by adding the self. prefix as you do when
creating it.
To reference an instance variable in a program that used the created instance, the variable to
which the instance is assigned (e.g., a) is reference by writing the name, followed by a
period (.), followed by the name of the instance variable.
Python does not have a very strong variable protection feature. Both class variables and instance
variables can be referenced and rewritten externally. One way to restrict access from outside the class
is to use variables that begin with two underscores. Such variables can be accessed by methods in
the class, but cannot be manipulated directly from outside the class.
167
13 Classes Next Chapter Table of Contents
If you run this program, you will get the following. You can see that the instances are numbered
using class variables, that the instance variable mydata is independent for each instance, and that it
can be accessed directly from the main program.
168
13 Classes Next Chapter Table of Contents
Class definition
a1 = A()
Class type
Created
Object
Instance variables
class A():
Independent for a2 = A() Blocks
each instance (such as method
Class type definitions)
Object
Class variables
Instance variables
169
13 Classes Next Chapter Table of Contents
13.5 Inheritance
Inheritance is an important aspect of writing programs using classes. For example, in the example of
tkinter implementation, the MyFrame class we defined inherited from tkinter's Frame class.
MyFrame inherits the functionality of the Frame class and adds the definition of widgets on the
Frame.
170
14 File Input/Output Next Chapter Table of Contents
In this section, you will learn how to handle files on a computer, which is the basis of all of these
methods.
File Path
Files on computers are managed by operating systems such as Windows, macOS, and linux. These
operating systems have a hierarchical folder (directory) 1 structure, in which folders can be placed
within folders, and the location of a file is identified by its position in the folder structure. The string
describing the location of a file is called the “file path,” and is a combination of the “hierarchical
folder structure notation” and the file name.
To give an example, in Windows
1Windows uses folders as a mechanism for organizing files, while its predecessors, MS-DOS and unix, used the term “directory.”
Strictly speaking, they are slightly different, but here we will treat folders and directories as the same thing.
171
14 File Input/Output Next Chapter Table of Contents
M:\documents\python scripts\p3-1.py
is the file path. Depending on a used font, it may be represented as
M:\documents\python scripts\p3-1.py
Here
M: the drive name (corresponding to the disk device or file server)
¥document¥python_scripts: folder path
p3-1.py: file name
.py: everything after the “.” in a file name is called the “extension,” which indicates the file type.
A full path starts at the drive name and includes all of the folders. A full path is the only way to
identify a specific file on a computer.
In addition to this, there is a “current working folder [directory]” that is referred to as the current
working directory, (cwd), as well as a “relative path” which is a path that describes only the
differences from the specified folder. For example, if your working folder is
M:\documents\python scripts
then the relative path notation
p3-1.py
would refer to
M:\documents\python scripts\p3-1.py
Text Files
A text file is a file written in text code (and symbols such as line breaks) in a format that can
be read and written by humans using an editor. For example, Python source code and
email messages are text files.
On the other hand, a file consisting of data in a computer's internal format is called a “binary file.”
The word “binary” means “base-2.” Binary files are written in the computer's internal format with no
172
14 File Input/Output Next Chapter Table of Contents
change; they have the advantage of not losing numerical value accuracy, and taking up a small
amount of data. However, without a description of the file's contents, it’s not possible to tell what is
written in a binary file.
In this chapter, you will learn how to read and write text files in Python.
CSV format
Python programs can be used in conjunction with other tools without much effort. The CSV (comma
separated value) format is an easy way to handle data for this purpose. This is a type of text file in
which each line consists of:
Data entry 1, Data entry 2, Data entry 3
and so on, with commas separating the data. If you add the extension .csv to the file name of a file in
this format, it can be read by spreadsheet software such as Microsoft Excel, making it easy to create
graphs.
Data in the CSV format is relatively easy to output. On the other hand, reading data in the CSV
format data can be tricky due to the handling of comma and line break characters; depending on the
content of your data, you may want to consider using a library 1 or other method.
Error Handling
Error handling is extremely important for file input/output. This is because the contents of files, the
file system, and the data to be read cannot be controlled by the program. When you try to open a file,
you must be aware that various things may happen. For example, the file or folder may not exist, you
may not have write permission, or you may run out of disk space in the middle of writing a file.
1In Python, the csv module is a library for handling CSV. In a later chapter we will see an example of loading a CSV file with pandas.
173
14 File Input/Output Next Chapter Table of Contents
Source code
Program 14-1 Example of File Input/Output (p14-1.py)
Program Notes
• Figure out the current working folder (current working directory) (line 8)
• Open the file named “Japanese file.txt” for writing (w), and assign it to the variable “f” for
future use. It is written as a relative path, so it will be created in the working folder with this
name. (line 10)
• Write the string to a file (line 11). “\n” means “new line.”
• Close the writing file (line 12)
• Open a file with the same name for reading (r). (line 15)
• Assign the entire contents of the file to the variable s. (Line 16)
• Close the file (line 17)
• Output the data (text) (line 18)
174
14 File Input/Output Next Chapter Table of Contents
1. Open the file with the open function and get the file object in the return value.
file = open(file name,mode)
The mode can be “r” for reading, “w” for writing, etc. In the above example, the return value is
assigned to the variable file.
In Python, unless otherwise specified, text files are written in the standard character set of the
operating system, and the encoding argument can be used to explicitly specify the character set.
file = open(file name,mode, encoding= "utf-8")
If it fails to open the file, it raises an IOError exception.
2. Reading and writing to a file object
A. Reading from a file object using the read() method
s = file.read()
In the above example, the entire text file is read as a string and assigned to the variable s.
B. Writing to a file object using the write() method
file.write(s)
The above example writes data in s to the file as a string.
The data can be added in the same way until the file is closed.
3. Close the file
file.close()
Note: open is a built-in function, and read, write, and close are methods of the file object.
In the above example, the entire contents of the file are read at once; to read a single line, use the
readline() method. It is also possible to process the contents of a file line by line using a for statement
as follows 1. 16F1 7F
1 Python's 'for' statement can be applied to a variety of objects, such as range() functions, strings (one character at a time), lists
(element by element), etc. This is because they are iterable, which means that they can be iterated over. File objects are also iterable,
where iterations occur line by line.
175
14 File Input/Output Next Chapter Table of Contents
The close() method is not executed due to an error in the code where it is written.
To avoid this, Python provides 'with' statement, which automatically closes the file opened by the
with statement after the block ends.
with open(File name and other arguments of the open function) as variables for the
file object :
A block that manipulates the file
176
14 File Input/Output Next Chapter Table of Contents
For simplicity, the signs of the terms shown above are all the same, but for the sawtooth wave (that
has a positive slope at the origin), the signs change alternately as shown below.
sin(𝑥𝑥) sin(2𝑥𝑥) sin(3𝑥𝑥) sin(4𝑥𝑥)
f(𝑥𝑥) = − + − …
1 2 3 4
A sawtooth wave with an amplitude of 1 (maximum and minimum values are ±1) has a coefficient
(2/π) applied to the whole wave.
177
14 File Input/Output Next Chapter Table of Contents
Source code
Program 14-2 Approximation of a sawtooth wave by summing trigonometric
functions (p14-2.py)
41 ␣␣␣␣␣␣␣␣␣␣␣␣angle_in_degree␣=␣360*cycles*i/steps
42 ␣␣␣␣␣␣␣␣␣␣␣␣angle␣=␣math.radians(angle_in_degree)
43 ␣␣␣␣␣␣␣␣␣␣␣␣s␣=␣str(angle_in_degree) Express the angle as
44 ␣␣␣␣␣␣␣␣␣␣␣␣w␣=␣0 a string
45 ␣␣␣␣␣␣␣␣␣␣␣␣for␣j␣in␣range(1,harmonics+1):
46 ␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣w␣+=␣math.sin(angle*j)/j Concatenate sum w to
47 ␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣s␣=␣s+",␣"+␣str(w) s, separated by a
48 ␣␣␣␣␣␣␣␣␣␣␣␣#print(s) comma (,)
49 ␣␣␣␣␣␣␣␣␣␣␣␣file.write(s+"\n") Add a line break
50 ␣␣␣␣␣␣␣␣print("Writing␣to␣file␣"+␣filename␣+␣"␣is␣finishe "\n" and write it
d") Append s to the
51 except␣IOError: file.
52 ␣␣␣␣print("Unable␣to␣open␣file")
Program Notes
179
14 File Input/Output Next Chapter Table of Contents
The summation is computed in the variable w, and the contents of a line are added to the variable
s as a string. To make the CSV format, the value of w is converted to a string and concatenated
to s separated by a comma (,) as follows:
s = s+", "+ str(w)
The comma is followed by a 17F18F
1 space to make the resulting file easier to read.
After the computation up to the fifth term in the for statement is completed, lines 49 and 50 are
output to a file.
# print(s)
file.write(s+"\n")
Line 49 is commented, but if you want to see the result in the Python shell, remove the #. In line
50, file.write() writes to the file, but “\n” is added to the single-line string s to add a “line break.”
Mac users should enter a backslash “\” instead of “¥.”
Calculate the trigonometric approximation for the square wave in the same way as in the example,
output the result to a CSV file, and create a graph using spreadsheet software.
180
14 File Input/Output Next Chapter Table of Contents
output.
Write the result of the calculation to a list using a list.
After the calculation is completed, write a CSV file in the same format as in Example 1 that
refers to the list.
There are two ways of constructing a list, as follows. Either implementation method is acceptable.
Series of sums up
Series of sums up
to the fourth term
Series of times
181
14 File Input/Output Next Chapter Table of Contents
5 #
6 #␣Create␣a␣class␣called␣MyFrame␣that␣inherits␣from␣tk.Frame
7 #␣Set␣up␣widgets␣and␣callback␣functions␣(methods)␣in␣it.
8 #␣This␣is␣the␣standard␣way␣to␣use␣tkinter.
9 #
10 class␣MyFrame(tk.Frame):
11 #␣__init__␣is␣the␣initialization␣method␣for␣creating␣a␣class␣object
12 ␣␣␣␣def␣__init__(self,␣master␣=␣None):
13 ␣␣␣␣␣␣␣␣super().__init__(master)
14 ␣␣␣␣␣␣␣␣self.master.title('Simple␣Editor')
15
16 #␣Create␣a␣menu:␣menubar␣->␣filemenu␣->␣Open,␣Save␣as,␣Exit
17 ␣␣␣␣␣␣␣␣menubar␣=␣tk.Menu(self)
18 ␣␣␣␣␣␣␣␣filemenu␣=␣tk.Menu(menubar,␣tearoff␣=␣0)
19 ␣␣␣␣␣␣␣␣filemenu.add_command(label␣=␣"Open",␣command␣=␣self.openfile)
20 ␣␣␣␣␣␣␣␣filemenu.add_command(label␣=␣"Save␣as...",␣command␣=␣self.saveas)
21 ␣␣␣␣␣␣␣␣filemenu.add_command(label␣=␣"Exit",␣command␣=␣self.master.destroy)
22 ␣␣␣␣␣␣␣␣menubar.add_cascade(label␣=␣"File",␣menu␣=␣filemenu)
23 ␣␣␣␣␣␣␣␣self.master.config(menu␣=␣menubar)
24
25 #␣Create␣a␣Text␣widget␣for␣editing␣as␣a␣class␣variable␣using␣editbox
26 ␣␣␣␣␣␣␣␣self.editbox␣=␣tk.Text(self)
27 ␣␣␣␣␣␣␣␣self.editbox.pack()
28
29 #␣Method␣to␣open␣a␣file,␣requires␣the␣parameter␣"self"␣
which␣is␣different␣than␣the␣parameter␣that␣a␣function␣would␣take
30 ␣␣␣␣def␣openfile(self):
31 #␣Get␣the␣file␣name␣in␣filedialog
32 ␣␣␣␣␣␣␣␣filename␣=␣tkinter.filedialog.askopenfilename()
33 #␣Process␣the␣filename␣if␣it's␣not␣empty
34 ␣␣␣␣␣␣␣␣if␣filename:
35 ␣␣␣␣␣␣␣␣␣␣␣␣tkinter.messagebox.showinfo("Filename","Open:␣"+filename)
36 #␣Open␣a␣file␣with␣a␣variable␣named␣file␣in␣it␣using␣a␣with␣statement
37 ␣␣␣␣␣␣␣␣␣␣␣␣with␣open(filename,'r')␣as␣file:
38 ␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣text␣=␣file.read()
39 #␣Set␣the␣file␣contents␣in␣the␣editbox␣Text␣widget
40 ␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣self.editbox.delete('1.0',tk.END)
41 ␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣self.editbox.insert('1.0',text)
42 ␣␣␣␣␣␣␣␣else:
43 ␣␣␣␣␣␣␣␣␣␣␣␣tkinter.messagebox.showinfo("Filename","Canceled")
44
45 #␣Method␣to␣save␣to␣a␣file
46 ␣␣␣␣def␣saveas(self):
47 #␣open␣a␣file␣with␣a␣variable␣named␣file␣using␣a␣with␣statement
48 ␣␣␣␣␣␣␣␣filename␣=␣tkinter.filedialog.asksaveasfilename()
49 ␣␣␣␣␣␣␣␣if␣filename:
50 ␣␣␣␣␣␣␣␣␣␣␣␣with␣open(filename,'w')␣as␣file:
51 ␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣file.write(self.editbox.get('1.0',tk.END))
182
14 File Input/Output Next Chapter Table of Contents
52 ␣␣␣␣␣␣␣␣␣␣␣␣tkinter.messagebox.showinfo("Filename","Saved␣AS:"+filename)
53 ␣␣␣␣␣␣␣␣else:
54 ␣␣␣␣␣␣␣␣␣␣␣␣tkinter.messagebox.showinfo("Filename","Canceled")
55
56 #␣Main␣program␣from␣here
57 root␣=␣tk.Tk()
58 f␣=␣MyFrame(root)
59 f.pack()
60 f.mainloop()
183
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
184
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
Tic-Tac-Toe
Describe in words the rules of tic-tac-toe and how the game proceeds.
〇 ×
〇 ×
Sentence analysis
Analyze the sentences you made that describe the rules of tic-tac-toe and the progression of the game
in terms of parts of speech (nouns, copulas, verbs). 1 You will end up with points similar to those
below.
Items (nouns) that take a specific state: these are candidates for variables
3×3 board, turn
The state of items (copulas): possible values for the variables
The state of each square (empty, O (player one), X (player two))
Whose turn it is
Actions that check states (candidates for functions)
Whose turn it is
State of the squares
Player one wins, player two wins, draw
Changing the state of a square (this is a candidate for a function)
Placing O or X in a square
Alternating turns
1This existence of such tasks is why literacy in the humanities is important for programmers.
185
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
手番 row
Turn column row column row column
1〇 0 0 0 0 0 1
2× 1 1 1 0 0 0
3〇 1 0 1 1 2 1
4× 2 0 2 2 1 1
5〇 0 2 0 2 2 2
6× 0 1 0 1 2 0
7〇 2 1 2 0 1 0
8× 2 2 0 2
9〇 1 2
結果
Result 引き分け
Draw 先手勝ち
Player one wins 後手勝ち
Player two wins
0 1 2 0 1 2 0 1 2
0 1〇 6× 5〇 0 1〇 6× 5〇 0 2× 1〇 8×
1 3〇 2× 9〇 1 2× 3〇 1 7〇 4×
2 4× 7〇 8× 2 7〇 4× 2 6× 3〇 5〇
Variable design
1) The board
The 3×3 board is represented by a nested list in which the elements are integers.
board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]]
The initial state is all 0s (empty)
The meaning of the values is as follows: 0 is an empty space, 1 is for player one (O), and 2 for
player two (X).
For this purpose, we define constants (there is no way to forbid changing the values in Python).
We use uppercase letters to make it clear that they are constants. we also use the following
186
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
2) Turn
An integer variable will indicate which player’s turn it is. The initial value is FIRST (the first
move)
turn = FIRST
The values use the previous constants (FIRST, SECOND), where FIRST indicates that it is
player one’s turn, and SECOND indicates that it is player two’s turn
3) Game record
The turn order is always “player one, then player two, then player one...” The move made by
each player is represented in the list of rows and columns.
We then append the result (undecided, player one wins, player two wins, draw) to this list 1. 18F19F
Game Record = [[first move (row, column)], [second move (row, column)], ..., [last move (row,
column)], [result]]
The row and column can be represented by an integer value of either 0, 1, or 2. The result can be
represented by an integer value of 0, 1, 2, or 3.
1) Turns
Operation: Initialize the turn
Operation: Change whose turn it is
Display: Display the turn (generate a string for it)
1 Because the game record is represented by a single list, different list elements actually represent two different things (where the
players moved, and the result). This is admittedly not a very straightforward implementation.
187
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
2) The Board
Operation: Initialize the board
Operation: Mark the specified square on the board with the marker of the player whose turn it is
Check: Determine the state of individual squares on the board
Check: Determine which player wins the game, based on the board
Check: Determine if all squares on the board are occupied
Display: Output the entire board (generate it as a string)
3) Game Records
Operation: Replay a game using the game record.
188
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
and or
You win if you
have three
spaces in a row
or
If you have all of the
spaces in a row:
victory in a row
Determining
the winner
True
Player one wins?
False
True
Player two wins?
False
True
Are there empty
spaces?
False
189
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
190
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
Main program
191
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
The program has nearly 500 lines in total, but the code with the yellow background is for
testing functions.
Functions come with a docstring. Multi-line docstrings start and end with ''' (three single
quotes).
There are no modules that need to be imported.
The display functions do not “print to the screen,” but generate a string that can be passed to
the print() function.
The main program simply prints “tic-tac-toe.” All the functions are loaded, so you can call
them in Python shell for testing or for actual play.
192
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
193
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
27 #
28 #␣Functions␣related␣to␣turns
29 #
30 #␣Convert␣the␣move␣number␣to␣a␣string
31 #
32 def␣show_turn():
33 ␣␣␣␣'Return␣a␣string␣showing␣current␣turn'
34 ␣␣␣␣if␣turn␣==␣FIRST:
35 ␣␣␣␣␣␣␣␣return('First')
36 ␣␣␣␣elif␣turn␣==␣SECOND:
37 ␣␣␣␣␣␣␣␣return('Second')
38 ␣␣␣␣else:
39 ␣␣␣␣␣␣␣␣return('Vaule␣of␣turn␣is␣not␣adequate')
40 #
41 #␣Initialize␣the␣turn
42 #
43 def␣init_turn():
44 ␣␣␣␣'Initialize␣turn'
45 ␣␣␣␣global␣turn
46 ␣␣␣␣turn␣=␣FIRST
47 #
48 #␣Change␣the␣turn
49 #
50 def␣change_turn():
51 ␣␣␣␣'Change␣turn'
52 ␣␣␣␣global␣turn
53 ␣␣␣␣if␣turn␣==␣FIRST:
54 ␣␣␣␣␣␣␣␣turn␣=␣SECOND
55 ␣␣␣␣elif␣turn␣==␣SECOND:
56 ␣␣␣␣␣␣␣␣turn␣=␣FIRST
57 #
58 #␣Test␣turn-related␣functions
59 #
60 def␣test_turn():
61 ␣␣␣␣'Test␣program␣of␣turn'
62 ␣␣␣␣init_turn()
63 ␣␣␣␣print(show_turn(),"␣is␣the␣current␣turn")
64 ␣␣␣␣change_turn()
65 ␣␣␣␣print(show_turn(),"␣is␣the␣current␣turn")
66 ␣␣␣␣change_turn()
67 ␣␣␣␣print(show_turn(),"␣is␣the␣current␣turn")
194
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
68 #
69 #␣Board-related␣functions
70 #
71 #␣A␣string␣that␣displays␣the␣board
72 #
73 def␣show_board():
74 ␣␣␣␣'Return␣a␣string␣showing␣the␣current␣board'
75 ␣␣␣␣s␣=␣'␣:0␣1␣2\n---------\n'
76 ␣␣␣␣for␣i␣in␣range(3):
77 ␣␣␣␣␣␣␣␣s␣=␣s␣+␣str(i)␣+␣':␣'
78 ␣␣␣␣␣␣␣␣for␣j␣in␣range(3):
79 ␣␣␣␣␣␣␣␣␣␣␣␣cell␣=␣''
80 ␣␣␣␣␣␣␣␣␣␣␣␣if␣board[i][j]␣==␣OPEN:
81 ␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣cell␣=␣'␣'
82 ␣␣␣␣␣␣␣␣␣␣␣␣elif␣board[i][j]␣==␣FIRST:
83 ␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣cell␣=␣'O'
84 ␣␣␣␣␣␣␣␣␣␣␣␣elif␣board[i][j]␣==␣SECOND:
85 ␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣cell␣=␣'X'
86 ␣␣␣␣␣␣␣␣␣␣␣␣else:
87 ␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣cell␣=␣'?'
88 ␣␣␣␣␣␣␣␣␣␣␣␣s␣=␣s␣+␣cell␣+␣'␣'
89 ␣␣␣␣␣␣␣␣s␣=␣s␣+␣'\n'
90 ␣␣␣␣return␣s
91 #
92 #␣Initialize␣the␣board
93 #
94 def␣init_board():
95 ␣␣␣␣'Set␣all␣the␣places␣on␣board␣OPEN'
96 ␣␣␣␣for␣i␣in␣range(3):
97 ␣␣␣␣␣␣␣␣for␣j␣in␣range(3):
98 ␣␣␣␣␣␣␣␣␣␣␣␣board[i][j]␣=␣OPEN
99 #
100 #␣Return␣the␣value␣of␣position␣i,␣j␣on␣the␣board
101 #
102 def␣examine_board(i,j):
103 ␣␣␣␣'Return␣state␣of␣the␣i-th␣row␣j-th␣column␣place␣on␣the␣board'
104 ␣␣␣␣return␣board[i][j]
105 #
106 #␣Register␣the␣turn␣t␣to␣i,␣j␣on␣the␣board,␣and␣return␣its␣status␣as␣a␣string
107 #
108 def␣set_board(i,j,t):
109 ␣␣␣␣'''
110 set␣turn␣t␣on␣the␣i,␣j␣place␣of␣the␣board,␣and␣return␣the␣status
111 returned␣value␣will␣be
112 ␣␣'ok'␣if␣successfully␣places
113 ␣␣'Not␣empty'␣the␣place␣is␣not␣empty
195
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
114 ␣␣'illegal␣turn'␣if␣turn␣value␣is␣not␣adequate
115 ␣␣'illegal␣slot'␣if␣place␣is␣not␣adequate
116 '''
117 ␣␣␣␣if␣(i>=0)␣and␣(i<3)␣and␣(j>=0)␣and␣(j<3):
118 ␣␣␣␣␣␣␣␣if␣(t>0)␣and␣(t<3):
119 ␣␣␣␣␣␣␣␣␣␣␣␣if␣examine_board(i,␣j)␣==␣0:
120 ␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣board[i][j]␣=␣t
121 ␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣return␣'OK'
122 ␣␣␣␣␣␣␣␣␣␣␣␣else:
123 ␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣return␣'Not␣empty'
124 ␣␣␣␣␣␣␣␣else:
125 ␣␣␣␣␣␣␣␣␣␣␣␣return␣'illegal␣turn'
126 ␣␣␣␣else:
127 ␣␣␣␣␣␣␣␣return␣'illegal␣slot'
128 #
129 #␣Testing␣function␣for␣the␣board
130 #
131 def␣test_board1():
132 ␣␣␣␣'The␣first␣test␣program␣on␣the␣board'
133 ␣␣␣␣init_board()
134 ␣␣␣␣print(show_board())
135 ␣␣␣␣print(set_board(0,0,1))
136 ␣␣␣␣print(show_board())
137 ␣␣␣␣print(set_board(1,1,2))
138 ␣␣␣␣print(show_board())
139 ␣␣␣␣print(set_board(1,1,1))
140 ␣␣␣␣print(show_board())
196
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
141 #
142 #␣Determine␣if␣a␣turn␣t␣wins␣in␣the␣horizontal␣direction
143 #
144 def␣check_board_horizontal(t):
145 ␣␣␣␣'Check␣whether␣turn␣t␣is␣win␣in␣horizontal␣direction'
146 ␣␣␣␣for␣i␣in␣range␣(3):
147 ␣␣␣␣␣␣␣␣if␣(board[i][0]␣==␣t)␣and␣(board[i][1]␣==␣t)␣and␣(board[i][2]␣==␣t):
148 ␣␣␣␣␣␣␣␣␣␣␣␣return␣True
149 ␣␣␣␣return␣False
150 #
151 #␣Determine␣if␣a␣turn␣t␣wins␣in␣the␣vertical␣direction
152 #
153 def␣check_board_vertical(t):
154 ␣␣␣␣'Check␣whether␣turn␣t␣is␣win␣in␣vertical␣direction␣'
155 ␣␣␣␣for␣j␣in␣range␣(3):
156 ␣␣␣␣␣␣␣␣if␣(board[0][j]␣==␣t)␣and␣(board[1][j]␣==␣t)␣and␣(board[2][j]␣==␣t):
157 ␣␣␣␣␣␣␣␣␣␣␣␣return␣True
158 ␣␣␣␣return␣False
159 #
160 #␣Determine␣if␣a␣turn␣t␣wins␣in␣the␣diagonal␣direction
161 #
162 def␣check_board_diagonal(t):
163 ␣␣␣␣'Check␣whether␣turn␣t␣is␣win␣in␣diagonal␣direction'
164 ␣␣␣␣if␣(board[0][0]␣==␣t)␣and␣(board[1][1]␣==␣t)␣and␣(board[2][2]␣==␣t):
165 ␣␣␣␣␣␣␣␣return␣True
166 ␣␣␣␣return␣False
167 #
168 #␣Determine␣if␣a␣turn␣t␣wins␣in␣the␣reverse␣diagonal␣direction
169 #
170 def␣check_board_inverse_diagonal(t):
171 ␣␣␣␣'␣Check␣whether␣turn␣t␣is␣win␣in␣inverse␣diagonal␣direction␣'
172 ␣␣␣␣if␣(board[0][2]␣==␣t)␣and␣(board[1][1]␣==␣t)␣and␣(board[2][0]␣==␣t):
173 ␣␣␣␣␣␣␣␣return␣True
174 ␣␣␣␣return␣False
175 #
176 #␣Simple␣determination␣of␣victory␣for␣a␣turn␣t
177 #
178 def␣is_win_simple(t):
179 ␣␣␣␣'Check␣win␣of␣turn.␣Do␣not␣check␣win␣of␣the␣other␣turn'
180 ␣␣␣␣if␣check_board_horizontal(t):
181 ␣␣␣␣␣␣␣␣return␣True
182 ␣␣␣␣if␣check_board_vertical(t):
183 ␣␣␣␣␣␣␣␣return␣True
184 ␣␣␣␣if␣check_board_diagonal(t):
185 ␣␣␣␣␣␣␣␣return␣True
186 ␣␣␣␣if␣check_board_inverse_diagonal(t):
197
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
187 ␣␣␣␣␣␣␣␣return␣True
188 ␣␣␣␣return␣False
189 #
190 #␣Determine␣the␣winner␣by␣confirming␣the␣opponent␣has␣not␣won.
191 #
192 def␣is_win_actual(t):
193 ␣␣␣␣'Check␣win␣of␣turn␣t.␣It␣also␣check␣whether␣the␣other␣turn␣do␣not␣win'
194 ␣␣␣␣if␣not␣is_win_simple(t):
195 ␣␣␣␣␣␣␣␣return␣False
196 ␣␣␣␣if␣t==FIRST:
197 ␣␣␣␣␣␣␣␣␣if␣is_win_simple(SECOND):
198 ␣␣␣␣␣␣␣␣␣␣␣␣␣return␣False
199 ␣␣␣␣else:
200 ␣␣␣␣␣␣␣␣if␣is_win_simple(FIRST):
201 ␣␣␣␣␣␣␣␣␣␣␣␣return␣False
202 ␣␣␣␣return␣True
203 #
204 #␣Determine␣whether␣the␣board␣is␣full
205 #
206 def␣is_full():
207 ␣␣␣␣'Confirm␣all␣the␣places␣are␣not␣empty'
208 ␣␣␣␣for␣i␣in␣range(3):
209 ␣␣␣␣␣␣␣␣for␣j␣in␣range(3):
210 ␣␣␣␣␣␣␣␣␣␣␣␣if␣board[i][j]␣==␣OPEN:
211 ␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣return␣False
212 ␣␣␣␣return␣True
213 #
214 #␣Determine␣whether␣a␣draw␣has␣occurred
215 #
216 def␣is_draw():
217 ␣␣␣␣'Check␣wheter␣board␣is␣draw'
218 ␣␣␣␣if␣is_win_simple(FIRST):
219 ␣␣␣␣␣␣␣␣return␣False
220 ␣␣␣␣if␣is_win_simple(SECOND):
221 ␣␣␣␣␣␣␣␣return␣False
222 ␣␣␣␣if␣not␣is_full():
223 ␣␣␣␣␣␣␣␣return␣False
224 ␣␣␣␣return␣True
198
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
225 #
226 #␣Second␣board␣testing␣function,␣which␣tests␣the␣victory␣determination
227 #
228 def␣test_board2():
229 ␣␣␣␣'The␣second␣test␣program␣of␣the␣board'
230 ␣␣␣␣init_board()
231 ␣␣␣␣board[0][0]␣=␣FIRST
232 ␣␣␣␣board[1][0]␣=␣FIRST
233 ␣␣␣␣board[2][0]␣=␣FIRST
234 ␣␣␣␣print(show_board())
235 ␣␣␣␣print("HORIZONTSL␣FIRST:␣"␣,check_board_horizontal(FIRST))
236 ␣␣␣␣print("HORIZONTSL␣SECOND:␣",check_board_horizontal(SECOND))
237 ␣␣␣␣print("VERTICAL␣FIRST:␣"␣␣␣,check_board_vertical(FIRST))
238 ␣␣␣␣print("VERTICAL␣SECOND:␣"␣␣,check_board_vertical(SECOND))
239 ␣␣␣␣init_board()
240 ␣␣␣␣board[0][0]␣=␣SECOND
241 ␣␣␣␣board[1][0]␣=␣SECOND
242 ␣␣␣␣board[2][0]␣=␣SECOND
243 ␣␣␣␣print(show_board())
244 ␣␣␣␣print("HORIZONTSL␣FIRST:␣"␣,check_board_horizontal(FIRST))
245 ␣␣␣␣print("HORIZONTSL␣SECOND:␣",check_board_horizontal(SECOND))
246 ␣␣␣␣print("VERTICAL␣FIRST:␣"␣␣␣,check_board_vertical(FIRST))
247 ␣␣␣␣print("VERTICAL␣SECOND:␣"␣␣,check_board_vertical(SECOND))
248
249 ␣␣␣␣init_board()
250 ␣␣␣␣board[0][0]␣=␣FIRST
251 ␣␣␣␣board[0][1]␣=␣FIRST
252 ␣␣␣␣board[0][2]␣=␣FIRST
253 ␣␣␣␣print(show_board())
254 ␣␣␣␣print("HORIZONTSL␣FIRST:␣"␣,check_board_horizontal(FIRST))
255 ␣␣␣␣print("HORIZONTSL␣SECOND:␣",check_board_horizontal(SECOND))
256 ␣␣␣␣print("VERTICAL␣FIRST:␣"␣␣␣,check_board_vertical(FIRST))
257 ␣␣␣␣print("VERTICAL␣SECOND:␣"␣␣,check_board_vertical(SECOND))
258 ␣␣␣␣init_board()
259 ␣␣␣␣board[0][0]␣=␣SECOND
260 ␣␣␣␣board[0][1]␣=␣SECOND
261 ␣␣␣␣board[0][2]␣=␣SECOND
262 ␣␣␣␣print(show_board())
263 ␣␣␣␣print("HORIZONTSL␣FIRST:␣"␣,check_board_horizontal(FIRST))
264 ␣␣␣␣print("HORIZONTSL␣SECOND:␣",check_board_horizontal(SECOND))
265 ␣␣␣␣print("VERTICAL␣FIRST:␣"␣␣␣,check_board_vertical(FIRST))
266 ␣␣␣␣print("VERTICAL␣SECOND:␣"␣␣,check_board_vertical(SECOND))
267
268 ␣␣␣␣init_board()
269 ␣␣␣␣board[0][0]␣=␣FIRST
270 ␣␣␣␣board[1][1]␣=␣FIRST
199
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
271 ␣␣␣␣board[2][2]␣=␣FIRST
272 ␣␣␣␣print(show_board())
273 ␣␣␣␣print("DIAGONAL␣FIRST:␣"␣,check_board_diagonal(FIRST))
274 ␣␣␣␣print("DIAGONAL␣SECOND:␣",check_board_diagonal(SECOND))
275 ␣␣␣␣print("INV␣DIAGONAL␣FIRST:␣"␣␣␣,check_board_inverse_diagonal(FIRST))
276 ␣␣␣␣print("INV␣DIAGONAL␣SECOND:␣"␣␣,check_board_inverse_diagonal(SECOND))
277 ␣␣␣␣init_board()
278 ␣␣␣␣board[0][0]␣=␣SECOND
279 ␣␣␣␣board[1][1]␣=␣SECOND
280 ␣␣␣␣board[2][2]␣=␣SECOND
281 ␣␣␣␣print(show_board())
282 ␣␣␣␣print("DIAGONAL␣FIRST:␣"␣,check_board_diagonal(FIRST))
283 ␣␣␣␣print("DIAGONAL␣SECOND:␣",check_board_diagonal(SECOND))
284 ␣␣␣␣print("INV␣DIAGONAL␣FIRST:␣"␣␣␣,check_board_inverse_diagonal(FIRST))
285 ␣␣␣␣print("INV␣DIAGONAL␣SECOND:␣"␣␣,check_board_inverse_diagonal(SECOND))
286
287 ␣␣␣␣init_board()
288 ␣␣␣␣board[0][2]␣=␣FIRST
289 ␣␣␣␣board[1][1]␣=␣FIRST
290 ␣␣␣␣board[2][0]␣=␣FIRST
291 ␣␣␣␣print(show_board())
292 ␣␣␣␣print("DIAGONAL␣FIRST:␣"␣,check_board_diagonal(FIRST))
293 ␣␣␣␣print("DIAGONAL␣SECOND:␣",check_board_diagonal(SECOND))
294 ␣␣␣␣print("INV␣DIAGONAL␣FIRST:␣"␣␣␣,check_board_inverse_diagonal(FIRST))
295 ␣␣␣␣print("INV␣DIAGONAL␣SECOND:␣"␣␣,check_board_inverse_diagonal(SECOND))
296 ␣␣␣␣init_board()
297 ␣␣␣␣board[0][2]␣=␣SECOND
298 ␣␣␣␣board[1][1]␣=␣SECOND
299 ␣␣␣␣board[2][0]␣=␣SECOND
300 ␣␣␣␣print(show_board())
301 ␣␣␣␣print("DIAGONAL␣FIRST:␣"␣,check_board_diagonal(FIRST))
302 ␣␣␣␣print("DIAGONAL␣SECOND:␣",check_board_diagonal(SECOND))
303 ␣␣␣␣print("INV␣DIAGONAL␣FIRST:␣"␣␣␣,check_board_inverse_diagonal(FIRST))
304 ␣␣␣␣print("INV␣DIAGONAL␣SECOND:␣"␣␣,check_board_inverse_diagonal(SECOND))
200
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
305 #
306 #␣Third␣board␣testing␣function,␣which␣determines␣whether␣it␣is␣a␣victory␣or␣draw
307 #
308 def␣test_board3():
309 ␣␣␣␣'␣The␣third␣test␣program␣of␣the␣board␣'
310 ␣␣␣␣init_board()
311 ␣␣␣␣board[0][0]␣=␣FIRST
312 ␣␣␣␣board[1][0]␣=␣FIRST
313 ␣␣␣␣board[2][0]␣=␣SECOND
314 ␣␣␣␣board[0][1]␣=␣SECOND
315 ␣␣␣␣board[1][1]␣=␣SECOND
316 ␣␣␣␣board[2][1]␣=␣FIRST
317 ␣␣␣␣board[0][2]␣=␣FIRST
318 ␣␣␣␣board[1][2]␣=␣FIRST
319 ␣␣␣␣board[2][2]␣=␣SECOND
320 ␣␣␣␣print(show_board())
321 ␣␣␣␣print("HORIZONTSL␣FIRST:␣"␣,check_board_horizontal(FIRST))
322 ␣␣␣␣print("HORIZONTSL␣SECOND:␣",check_board_horizontal(SECOND))
323 ␣␣␣␣print("VERTICAL␣FIRST:␣"␣␣␣,check_board_vertical(FIRST))
324 ␣␣␣␣print("VERTICAL␣SECOND:␣"␣␣,check_board_vertical(SECOND))
325 ␣␣␣␣print("DIAGONAL␣FIRST:␣"␣,check_board_diagonal(FIRST))
326 ␣␣␣␣print("DIAGONAL␣SECOND:␣",check_board_diagonal(SECOND))
327 ␣␣␣␣print("INV␣DIAGONAL␣FIRST:␣"␣␣␣,check_board_inverse_diagonal(FIRST))
328 ␣␣␣␣print("INV␣DIAGONAL␣SECOND:␣"␣␣,check_board_inverse_diagonal(SECOND))
329 ␣␣␣␣print("IS␣WIN␣SIMPLE␣FIRST",␣is_win_simple(FIRST))
330 ␣␣␣␣print("IS␣WIN␣SIMPLE␣SECOND",␣is_win_simple(SECOND))
331 ␣␣␣␣print("IS␣WIN␣ACTUAL␣FIRST",␣is_win_actual(FIRST))
332 ␣␣␣␣print("IS␣WIN␣ACTUAL␣SECOND",␣is_win_actual(SECOND))
333 ␣␣␣␣print("IS␣FULL",␣is_full())
334 ␣␣␣␣print("IS␣DRAW",␣is_draw())
335
336 ␣␣␣␣init_board()
337 ␣␣␣␣board[0][0]␣=␣FIRST
338 ␣␣␣␣board[1][0]␣=␣SECOND
339 ␣␣␣␣board[2][0]␣=␣FIRST
340 ␣␣␣␣board[0][1]␣=␣SECOND
341 ␣␣␣␣board[1][1]␣=␣FIRST
342 ␣␣␣␣board[2][1]␣=␣OPEN
343 ␣␣␣␣board[0][2]␣=␣FIRST
344 ␣␣␣␣board[1][2]␣=␣OPEN
345 ␣␣␣␣board[2][2]␣=␣SECOND
346 ␣␣␣␣print(show_board())
347 ␣␣␣␣print("HORIZONTSL␣FIRST:␣"␣,check_board_horizontal(FIRST))
348 ␣␣␣␣print("HORIZONTSL␣SECOND:␣",check_board_horizontal(SECOND))
349 ␣␣␣␣print("VERTICAL␣FIRST:␣"␣␣␣,check_board_vertical(FIRST))
350 ␣␣␣␣print("VERTICAL␣SECOND:␣"␣␣,check_board_vertical(SECOND))
201
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
351 ␣␣␣␣print("DIAGONAL␣FIRST:␣"␣,check_board_diagonal(FIRST))
352 ␣␣␣␣print("DIAGONAL␣SECOND:␣",check_board_diagonal(SECOND))
353 ␣␣␣␣print("INV␣DIAGONAL␣FIRST:␣"␣␣␣,check_board_inverse_diagonal(FIRST))
354 ␣␣␣␣print("INV␣DIAGONAL␣SECOND:␣"␣␣,check_board_inverse_diagonal(SECOND))
355 ␣␣␣␣print("IS␣WIN␣SIMPLE␣FIRST",␣is_win_simple(FIRST))
356 ␣␣␣␣print("IS␣WIN␣SIMPLE␣SECOND",␣is_win_simple(SECOND))
357 ␣␣␣␣print("IS␣WIN␣ACTUAL␣FIRST",␣is_win_actual(FIRST))
358 ␣␣␣␣print("IS␣WIN␣ACTUAL␣SECOND",␣is_win_actual(SECOND))
359 ␣␣␣␣print("IS␣FULL",␣is_full())
360 ␣␣␣␣print("IS␣DRAW",␣is_draw())
361
362 ␣␣␣␣init_board()
363 ␣␣␣␣board[0][0]␣=␣SECOND
364 ␣␣␣␣board[1][0]␣=␣FIRST
365 ␣␣␣␣board[2][0]␣=␣SECOND
366 ␣␣␣␣board[0][1]␣=␣FIRST
367 ␣␣␣␣board[1][1]␣=␣SECOND
368 ␣␣␣␣board[2][1]␣=␣FIRST
369 ␣␣␣␣board[0][2]␣=␣SECOND
370 ␣␣␣␣board[1][2]␣=␣OPEN
371 ␣␣␣␣board[2][2]␣=␣FIRST
372 ␣␣␣␣print(show_board())
373 ␣␣␣␣print("HORIZONTSL␣FIRST:␣"␣,check_board_horizontal(FIRST))
374 ␣␣␣␣print("HORIZONTSL␣SECOND:␣",check_board_horizontal(SECOND))
375 ␣␣␣␣print("VERTICAL␣FIRST:␣"␣␣␣,check_board_vertical(FIRST))
376 ␣␣␣␣print("VERTICAL␣SECOND:␣"␣␣,check_board_vertical(SECOND))
377 ␣␣␣␣print("DIAGONAL␣FIRST:␣"␣,check_board_diagonal(FIRST))
378 ␣␣␣␣print("DIAGONAL␣SECOND:␣",check_board_diagonal(SECOND))
379 ␣␣␣␣print("INV␣DIAGONAL␣FIRST:␣"␣␣␣,check_board_inverse_diagonal(FIRST))
380 ␣␣␣␣print("INV␣DIAGONAL␣SECOND:␣"␣␣,check_board_inverse_diagonal(SECOND))
381 ␣␣␣␣print("IS␣WIN␣SIMPLE␣FIRST",␣is_win_simple(FIRST))
382 ␣␣␣␣print("IS␣WIN␣SIMPLE␣SECOND",␣is_win_simple(SECOND))
383 ␣␣␣␣print("IS␣WIN␣ACTUAL␣FIRST",␣is_win_actual(FIRST))
384 ␣␣␣␣print("IS␣WIN␣ACTUAL␣SECOND",␣is_win_actual(SECOND))
385 ␣␣␣␣print("IS␣FULL",␣is_full())
386 ␣␣␣␣print("IS␣DRAW",␣is_draw())
202
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
387 #
388 #␣Log␣replay
389 #
390 def␣replay_log(log):
391 ␣␣␣␣'Replay␣a␣game␣log.␣It␣shows␣replay␣on␣screen␣with␣print()␣function'
392 ␣␣␣␣init_board()
393 ␣␣␣␣init_turn()
394 ␣␣␣␣print(show_board())
395 ␣␣␣␣for␣m␣in␣log:
396 ␣␣␣␣␣␣␣␣if␣len(m)␣==␣2:
397 ␣␣␣␣␣␣␣␣␣␣␣␣print(show_turn(),"␣is␣the␣current␣turn")
398 ␣␣␣␣␣␣␣␣␣␣␣␣print(set_board(m[0],␣m[1],␣turn))
399 ␣␣␣␣␣␣␣␣␣␣␣␣print(show_board())
400 ␣␣␣␣␣␣␣␣␣␣␣␣print("IS␣WIN",␣turn,␣":␣",␣is_win_actual(turn))
401 ␣␣␣␣␣␣␣␣␣␣␣␣change_turn()
402 ␣␣␣␣␣␣␣␣else:
403 ␣␣␣␣␣␣␣␣␣␣␣␣print("RESULT␣IN␣LOG:␣",m[0])
404 ␣␣␣␣print("IS␣WIN␣FIRST:␣",␣is_win_actual(FIRST))
405 ␣␣␣␣print("IS␣WIN␣SECOND:␣",␣is_win_actual(SECOND))
406 ␣␣␣␣print("IS␣DRAW:␣",␣is_draw())
407 #
408 #␣Log␣test
409 #
410 def␣test_log():
411 ␣␣␣␣'Test replay of logs'
412 ␣␣␣␣print("LOG1")
413 ␣␣␣␣replay_log(log1)
414 ␣␣␣␣print("LOG2")
415 ␣␣␣␣replay_log(log2)
416 ␣␣␣␣print("LOG3")
417 ␣␣␣␣replay_log(log3)
418 #
419 #␣Test␣all
420 #
421 def␣test_all():
422 ␣␣␣␣'Do all the test programs'
423 ␣␣␣␣test_turn()
424 ␣␣␣␣test_board1()
425 ␣␣␣␣test_board2()
426 ␣␣␣␣test_board3()
427 ␣␣␣␣test_log()
203
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
Program 15-8 Tic-tac-toe program, example (Part 8: The play() function and the main
program)
428 #
429 #␣Actual␣gameplay
430 #
431 def␣play():
432 ␣␣␣␣'Conduct␣an␣actual␣tic-tac-toe␣game␣interactively␣on␣terminal'
433 ␣␣␣␣init_turn()
434 ␣␣␣␣init_board()
435 ␣␣␣␣print(show_board())
436 #␣Create␣an␣empty␣list␣for␣the␣game␣record.␣
437 #␣Declare␣it␣as␣a␣global␣variable␣if␣you␣want␣to␣access␣it␣outside␣of␣play()
438 #␣␣␣␣global␣log
439 ␣␣␣␣log␣=␣[]
440 ␣␣␣␣while␣True:
441 ␣␣␣␣␣␣␣␣print(show_turn(),"␣is␣the␣current␣turn")
442 ␣␣␣␣␣␣␣␣while(True):
443 ␣␣␣␣␣␣␣␣␣␣␣␣row␣=␣int(input("Input␣the␣number␣of␣row␣you␣want␣to␣place:␣"))
444 ␣␣␣␣␣␣␣␣␣␣␣␣column␣=␣int(input("Input␣a␣number␣of␣column:␣"))
445 ␣␣␣␣␣␣␣␣␣␣␣␣result␣=␣set_board(row,␣column,␣turn)
446 ␣␣␣␣␣␣␣␣␣␣␣␣print(result)
447 ␣␣␣␣␣␣␣␣␣␣␣␣if␣result␣==␣"OK":
448 ␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣␣break
449 ␣␣␣␣␣␣␣␣␣␣␣␣print("Inadequate␣value(s),␣try␣again")
450 ␣␣␣␣␣␣␣␣#␣Add␣a␣turn␣to␣the␣log␣here␣(outside␣of␣the␣inner␣while)
451 ␣␣␣␣␣␣␣␣#␣Additional␣code␣required␣here
452 ␣␣␣␣␣␣␣␣#
453 ␣␣␣␣␣␣␣␣print(show_board())
454 ␣␣␣␣␣␣␣␣if␣is_draw():
455 ␣␣␣␣␣␣␣␣␣␣␣␣print("Game␣is␣draw")
456 #␣Add␣the␣game␣result␣(a␣draw)␣to␣log␣here.
457 ␣␣␣␣␣␣␣␣␣␣␣␣break
458 ␣␣␣␣␣␣␣␣if␣is_win_actual(turn):
459 ␣␣␣␣␣␣␣␣␣␣␣␣print(show_turn(),␣"won␣the␣game")
460 #␣Add␣the␣game␣result␣(current␣player's␣win)␣to␣log␣here.
461 ␣␣␣␣␣␣␣␣␣␣␣␣break
462 ␣␣␣␣␣␣␣␣change_turn()
463 ␣␣␣␣#␣This␣is␣a␣replay␣of␣the␣game
464 ␣␣␣␣#␣Currently␣the␣log␣is␣empty,␣so␣determine␣victory,␣and␣process
465 ␣␣␣␣if␣len(log)>0:
466 ␣␣␣␣␣␣␣␣replay_log(log)
467 ␣␣␣␣else:
468 ␣␣␣␣␣␣␣␣print("Game␣log␣was␣not␣recorded")
469 if␣__name__␣==␣'__main__':
470 ␣␣␣␣print('Tic-Tac-Toe')
204
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
Extract defined functions in the tic-tac-toe program, and make a spreadsheet on the
relationship of functions as shown in the following figure.
Make a table having function names in the 1st row and column,
Mark cells with ‘↑’ whose column functions are called by the function shown in the
row.
By arranging rows and columns appropriately, marks can be placed lower than the diagonal
line.
function 1 function 2 function 3
function 1
function 2 ↑
function 3 ↑ ↑
205
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
you must remember that if a program passes a test, it does not guarantee that it will run
properly in all cases where it is expected to have passed the test.
It is easier to test component functions than it is to test their combined functions. You can build more
confidence in your skill at using complex functions by building them with correctly working
components.
Refactoring
There are two ways in which a program can be improved, as below
Enhancing the functionality of the program
Maintaining the functionality of the program, but rearranging how it is implemented in order to
make it easier to maintain and extend.
The latter kind of improvement is called “refactoring.” An example of this is reprogramming your
tic-tac-toe program using classes. There are several reasons why refactoring is necessary.
Programs are used for a long time, so they must be easy to maintain.
Also, the developers of the program may be replaced.
There is a constant demand for additional functionality in programs.
206
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents
It is not
Specifications supposed to be Creating value
(“This is the software I want”) like this through the
product
207
16 Academic Use of Python Next Chapter Table of Contents
Python
Plot a list or other data with
the plot method in pyplot
208
16 Academic Use of Python Next Chapter Table of Contents
16.3 NumPy
Python is a slow programming language, but NumPy is written in C, and can perform vector and
matrix operations very quickly.
ndarray attributes
You can read up on your own about the following attributes of ndarrays.
ndim:ndarray dimension
shape: ndarray size
dtype: Data type
import numpy as np
209
16 Academic Use of Python Next Chapter Table of Contents
arr2 = py.array([[1,2,3],[4,5,6]]
arr2.ndim
2
arr2.shape
(2,3)
arr2.dtype
dtype('Int32')
Note that while Python's integer types have no limit on the number of digits, ndarray uses a fixed-
length type that allows fast operations to be performed in order to speed up computation.
Slicing
ndarrays can be sliced in the same manner as lists can.
arr1[2:]
array([3])
Multi-dimensional arrays use the following notation: [:,:]
arr2[0:2,0:2]
array([1,2][4,5])
Note The result of slicing an ndarray is not a “copy,” but a reference to a part of the original ndarray.
If you assign a scalar value to a slice, it will be assigned to all elements.
210
16 Academic Use of Python Next Chapter Table of Contents
ndarray operations
ndarray data can be used to perform arithmetic operations, powers, comparisons, and so on. These
operations are iterable over all elements in the ndarray.
Matrix products use the @ operator.
The value is applied to all the elements for scalar operations.
arr1 = np.array([1,2,3])
arr1*2
array([2,4,6])
arr1 + 1
array([2,3,4])
Matrix Calculations
Numpy makes it easy to perform mathematical matrix calculations on ndarrays.
Matrix transposition (swapping rows and columns)
We will use the T attribute of ndarray.
Matrix product
We will use the @ operator.
Using the linalg (linear algebra) module: numpy.linalg (or np.linalg if you imported numpy
with the np alias) defines the following matrix functions.
diag (diagonal elements),
trace (sum of diagonal elements),
det (determinant),
eig (eigenvalue),
inv (inverse),
solve (to solve a linear equation)
211
16 Academic Use of Python Next Chapter Table of Contents
Random numbers
Numpy allows you to generate random numbers in bulk.
seed: sets the initial value for random number generation.
rand: generates uniformly continuous random numbers.
randn: generates random numbers that follow a standard normal distribution.
randint: generates random numbers in a given range.
Here is an example of how to use it.
np.random.rand(10)
Generates 10 floating-point random numbers with values between 0 and 1
np.random.randn(5,5)
Generates random numbers that follow a standard normal distribution as a two-dimensional
array of size (5,5)
np.random.permutation([1,2,3,4,5])
Generates a random permutation of the list [1,2,3,4,5]. range() and ndarray can be specified as
arguments. For multi-dimensional arrays, only the first index is replaced.
np.random.randint(2,size=10)
Generates an integer random number in range(0,2) with a size of 10. Since we are able to
provide lower and upper limits, The size of the array can be specified using “size=”
16.4 Matplotlib
212
16 Academic Use of Python Next Chapter Table of Contents
Usage of fonts for OS in matplotlib is shown in Program 16-1, and execution result is shown
in Figure 16-2.
For Mac user, comment out line 7, and uncomment line 10 in Program 16-1.
Program 16-1 matplotlib example(use_matplotlib_outline.py)
1 The following example uses Yu Gothic, but Yu Mincho, MS Gothic, MS Mincho, etc. can also be used.
213
16 Academic Use of Python Next Chapter Table of Contents
214
16 Academic Use of Python Next Chapter Table of Contents
Example
1) use_matplotlib.py
Title
Series 1
Series 2
Series 3
Vertical axis
Horizontal axis
215
16 Academic Use of Python Next Chapter Table of Contents
• use_matplotlib_scatter.py
216
16 Academic Use of Python Next Chapter Table of Contents
Title
Data 1
Data 2
Vertic
• Horizontal axis
217
16 Academic Use of Python Next Chapter Table of Contents
30 #␣
31 datax␣=␣np.random.randn(100)
32 datay␣=␣0.6*datax␣+␣np.random.randn(100)*0.4
33 #
34 #␣Specify␣the␣color,␣then␣create␣a␣scatter␣plot
35 #
36 plt.scatter(datax,datay,color='red',label='Data2')
37 #
38 #␣Fill␣in␣the␣title,␣axis␣labels,␣and␣legend
39 #
40 plt.title('Title')
41 plt.xlabel('Horizontal Axis ')
42 plt.ylabel('Vertical Axis ')
43 plt.legend()
44 #
45 #␣Display
46 #
47 plt.show()
•
3) Drawing a Histogram
You can draw a histogram by feeding the data for it into the hist function of pyplot. The number of
bars is automatically adjusted, but it can also be specified.
use_matplotlib_hist.py
Histogram
Frequency
Data value
218
16 Academic Use of Python Next Chapter Table of Contents
219
16 Academic Use of Python Next Chapter Table of Contents
Draw each subplot with the plot, scatter, and hist functions.
Add the title and axis labels with set_title, set_xlabel, and set_ylabel. Make sure the function
names are correct.
use_matplotlib_subplot.py
Data 1
Data 2
Attribute 2
Location
Time Attribute 1
Histogram
Frequency
Data value
220
16 Academic Use of Python Next Chapter Table of Contents
20 #
21 fig␣=␣plt.figure()
22 ax1␣=␣fig.add_subplot(2,2,1)
23 ax2␣=␣fig.add_subplot(2,2,2)
24 ax3␣=␣fig.add_subplot(2,2,3)
25 plt.subplots_adjust(hspace=0.5,␣wspace=␣0.5)
26 #
27 #␣First,␣output␣a␣line␣graph
28 #␣
29 data␣=␣np.random.randn(100).cumsum()
30 ax1.plot(data)
31 ax1.set_title('Line Graph')
32 ax1.set_xlabel('Time')
33 ax1.set_ylabel('Place')
34 #
35 #␣Second,␣output␣a␣scatter␣plot
36 #
37 datax␣=␣np.random.randn(100)
38 datay␣=␣datax␣+␣np.random.randn(100)*0.3
39 ax2.scatter(datax,datay,label='Data1')
40
41 datax␣=␣np.random.randn(100)
42 datay␣=␣0.6*datax␣+␣np.random.randn(100)*0.4
43 ax2.scatter(datax,datay,color='red',label='Data2')
44
45 ax2.set_title('Scatter Plot')
46 ax2.set_xlabel('Attribute1')
47 ax2.set_ylabel('Attribute2')
48 ax2.legend()
49
50 #
51 #␣Third,␣output␣a␣histogram
52 #
53 data␣=␣np.random.randn(1000)
54 ax3.hist(data,bins=20)
55
56 ax3.set_title('Histogram')
57 ax3.set_xlabel('Value of Data')
58 ax3.set_ylabel('Data Frequency')
59
60 #
61 #␣Display␣the␣graphs
62 #␣
63 plt.show()
221
16 Academic Use of Python Next Chapter Table of Contents
16.5 pandas
Dataframe
The following are Pandas-specific data formats.
One-dimensional Series
Two-dimensional DataFrame
A DataFrame has a row name (index) and a column name (column).
Column Name
Row Name
Data
Create a DataFrame
222
16 Academic Use of Python Next Chapter Table of Contents
Program 16-6 read the data with the follow steps (use_read_csv.py)
1. Import numpy module.
2. Import pandas module.
3. Import os module.
4. show the current working folder, and then get folder path. If sample.csv is located in the shown
folder, just type ‘.’, otherwise give the folder path.
folderpath␣=␣input("Enter␣folder␣path:␣")
5. Use os.chdir to change to the folder with the csv file.
223
16 Academic Use of Python Next Chapter Table of Contents
os.chdir(folderpath)
6. Import the csv file
df = pd.read_csv("sample.csv")
7. Show the read data and their summary with the following:
print(df)
print(df.describe())
Note: pd.read_csv does not seem to be able to handle Japanese file names correctly.
224
16 Academic Use of Python Next Chapter Table of Contents
7 H 62 73 52 60 74 321
8 I 73 85 41 49 75 323
9 J 61 61 49 51 63 285
10 K 49 56 58 63 85 311
11 L 42 50 56 59 78 285
12 M 52 66 50 49 43 260
13 N 88 72 52 64 48 324
14 O 72 75 56 54 80 337
15 P 94 90 61 58 67 370
16 Q 95 85 72 68 43 363
17 R 70 85 68 62 81 366
18 S 74 85 96 96 53 404
19 T 65 53 64 67 75 324
Japanese English Mathematics Science Social Studies Total
count 20.000000 20.000000 20.000000 20.000000 20.000000 20.000000
mean 73.250000 72.900000 64.850000 65.550000 70.150000 346.700000
std 17.149114 14.164076 17.547754 14.195904 17.141132 53.425896
min 42.000000 50.000000 41.000000 49.000000 43.000000 260.000000
25% 60.250000 60.750000 52.000000 54.750000 55.250000 314.750000
50% 72.500000 74.000000 59.500000 62.500000 74.500000 330.500000
75% 91.250000 85.000000 73.000000 71.500000 80.250000 378.500000
max 97.000000 92.000000 100.000000 96.000000 97.000000 436.000000
225
16 Academic Use of Python Next Chapter Table of Contents
226
16 Academic Use of Python Next Chapter Table of Contents
227
16 Academic Use of Python Next Chapter Table of Contents
18 #
19
20 df.plot()
21 print("Close␣window␣to␣proceed")
22 plt.show()
23 #
24 #␣Stacked␣bar␣graph
25 #
26 df.plot.bar(stacked=True)
27 print("Close␣window␣to␣proceed␣")
28 plt.show()
29 #
30 #␣Scatter␣plot
31 #
32 df.plot.scatter('Japanese','English')
33 print("Close␣window␣to␣proceed␣")
34 plt.show()
35 #
36 #␣Sum␣horizontally␣(axis␣=␣1)␣and␣create␣a␣column␣called␣Total
37 #␣Specify numeric_only␣parameter␣to␣skip␣ID␣column.
38 df['Total']␣=␣df.sum(axis=1␣numeric_only=True)
39
40 #
41 #␣Histogram
42 #
43 df['Total'].plot.hist()
44 print("Close␣window␣to␣proceed␣")
45 plt.show()
Exercise 16-1 Modify it to draw a approximation of a saw wave with sum of trigonometric
functions.
In Numpy (np) you can use np.pi for pi and np.sin() for the sine function.
228
16 Academic Use of Python Next Chapter Table of Contents
Po wer of X
Fourier approximation of a saw wave
1st power
Sum up to term 1
2nd power
Sum up to term 2
3rd power
Sum up to term 3
4th power
Sum up to term 4
Sum up to term 5
Sum up to term 6
Sum up to term 7
Sum up to term 8
Amplitude
Angle
229
16 Academic Use of Python Next Chapter Table of Contents
26 #
27 #␣Create␣a␣value␣for␣x␣in␣linspace
28 #
29 x␣=␣np.linspace(0,maxx,steps)
30 #
31 #␣For␣each␣column,␣calculate␣everything␣at␣once
32 #␣
33 for␣j␣in␣range(1,order+1):
34 ␣␣␣␣datalist[:,j-1]␣=␣x**j
35 ␣␣␣␣legend_label.append('Power␣of'␣+␣str(j))
36 #
37 #␣Plot
38 #
39 plt.plot(x,␣datalist)
40 plt.title('Power␣function␣of␣x')
41 plt.xlabel('x')
42 plt.ylabel('x**n')
43 plt.legend(legend_label)
44 plt.show()
References
Wes McKinney: Python for Data Analysis: Data Wrangling with Pandas, NumPy, and IPython,
O'Reilly Media, 2nd Ed. (2017)
The tutorial pages on the following sites are helpful.
NumPy website
http://www.numpy.org/index.html
Pandas website
https://pandas.pydata.org/
Matplotlib website
https://matplotlib.org/
TkAgg button controls, etc. (hard to find)
https://matplotlib.org/users/navigation_toolbar.html
230
17 Review, and Where to Go From Here Next Chapter Table of Contents
17.2 Reflection
Please reflect on your learning by comparing your skills before and after this class.
• What are you now able to do?
• How was it different from your expectations before the course?
• What kind of learning objectives will you set in the future?
231
17 Review, and Where to Go From Here Next Chapter Table of Contents
used.
1When I was in junior high school, me and a friend of mine whose family owned an ironworks thought about making a bicycle
together. What you think that you can do depends on the environment you are in.
232
17 Review, and Where to Go From Here Next Chapter Table of Contents
If you are able to program computers, not just in Python, we believe that you will be able to look at
things in a way that says, “I should be able to do this with a computer.” If this is the case for you,
we urge you to think about how you can contribute to society through computers and programming.
Computers, programming languages, and other software, including Python, are “other people’s
creations;” they are a gift from many engineers and programmers, so to speak. If you enjoy
programming, be thankful for this and try to give back.
References
We will suggest a few publications to help students continue their studies. Being able to write
programs that are easy to read is a very important skill. Reference [24] teaches how to do that while
also introducing various tools that help support Python programming. One of Python's most
attractive features is the wealth of libraries for all sorts of applications. Reference [25] serves as a
good introductory guide to these libraries. In this book, we also dealt with an example where we
created voice files back in the column section of the chapter that dealt with trigonometric functions.
Reference [26] covers how to handle sounds in Python and explains the acoustics knowledge and
digital signal treatment methods necessary for doing so.
Al Sweigart: Beyond the Basic Stuff with Python,No Starch Press (2020)
松田晃一:Python ライブラリの使い方 第 2 版,カットシステム (2023, in Japanese)
青木直史:Python で始める音のプログラミング,オーム社 (2022, in Japanese)
233
18 Appendix: Useful notes on Python and IDLE Next Chapter Table of Contents
234
18 Appendix: Useful notes on Python and IDLE Next Chapter Table of Contents
Also, command line arguments can now be passed at runtime by selecting the Run ... Customized
menu. (Command line arguments are not explained in this text.)
235
19 Appendix: How to Read Error Messages in IDLE/Python Next Chapter Table of Contents
Let's take a look at some of the most common errors and what they mean 1. An error occurs when the
computer that interprets and executes the program is unable to continue processing. In many cases,
the error occurs in a different place than the actual error caused by the programmer. You need to read
error messages and think about what they mean.
1 Shown messages may depend on the versions of Python and IDLE. Examples given in this chapter uses Python
3.10.12 and IDLE Shell 3.10.12.
236
19 Appendix: How to Read Error Messages in IDLE/Python Next Chapter Table of Contents
237
19 Appendix: How to Read Error Messages in IDLE/Python Next Chapter Table of Contents
238
19 Appendix: How to Read Error Messages in IDLE/Python Next Chapter Table of Contents
239
19 Appendix: How to Read Error Messages in IDLE/Python Next Chapter Table of Contents
In this example, the Python shell displays the following. Since the error is occurring in the function
definition, the traceback will follow the call to the error location. On line 6, it says “NameError:
name 'xx' is not defined. Did you mean: 'x'?,” indicating that the variable called xx is not defined.
240
19 Appendix: How to Read Error Messages in IDLE/Python Next Chapter Table of Contents
In this example, the string “2” is passed as an argument to call math.sin(), and the message
“TypeError: must be real number, not str” is displayed.
241
19 Appendix: How to Read Error Messages in IDLE/Python Next Chapter Table of Contents
This example uses a tkinter class definition that extends the Frame class, but the
indentation of the “do” method is one level too deep. This is why MyFrame is
assumed to have no attribute called do when called as a button callback
function. Also, the creation of the button widget b fails, so only the window of
tkinter is displayed, as shown on the right.
242
19 Appendix: How to Read Error Messages in IDLE/Python Next Chapter Table of Contents
243
19 Appendix: How to Read Error Messages in IDLE/Python Next Chapter Table of Contents
In this example, the function fun2 calls the function that calculates absolute values and then returns
the absolute value of the sum of the two arguments. The function fun2 is read in 13th row, but no
issue is encountered because both arguments are integers. On the other hand, the two arguments on
18th row are character strings, so while the sum can be calculated, the absolute value written on 4th
row cannot.
The results of running this problem can be seen below. The 17th row is run which then leads to 8th
row being run. Within that, one can see that the error arises upon trying to run 4th row.
Even when using functions from modules one can easily pinpoint where the function is being called
which makes it easier to find errors.
1 -5 4
Traceback (most recent call last):
File "C:/Users/hjkit/Documents/Python Scripts/func-err.py", line 17, in <module>
print(a, b, fun2(a, b))
244
19 Appendix: How to Read Error Messages in IDLE/Python Next Chapter Table of Contents
>>>
245