0% found this document useful (0 votes)
25 views245 pages

Kyoto University Python Version2023 - 10!19!01e

Uploaded by

vishal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views245 pages

Kyoto University Python Version2023 - 10!19!01e

Uploaded by

vishal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 245

Programming Practice Python 2023

These are reserved Python keywords. Faded words will not be covered in this book.

Hajime Kita, Institute for Liberal Arts and Sciences

Yoshitaka Morimura, Institute for Information Management and Communication

Masako Okamoto, Center for Promotion of Excellence in Higher Education


Kyoto University

Version 2023/10/19

1
Table of Content Next Chapter Table of Contents

Table of Content
Table of Content ······································································ 2

Table of Figures ······································································· 6

Table of Tables ········································································ 9

Table of Programs ·································································· 10

Table of Exercises ·································································· 13

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

1. Computers and Programming ············································ 19


1.1 Learning goals of this chapter ......................................................................... 19
1.2 Computers and programs ............................................................................... 19
1.3 Computer structure ......................................................................................... 21
1.4 Programming languages ................................................................................. 23
1.5 Python ............................................................................................................. 26
1.6 Various applications ........................................................................................ 26
1.7 How to learn programming .............................................................................. 27
1.8 The fundamental concepts used in programming .......................................... 33
1.9 What part of the program do you write? ......................................................... 33
References .................................................................................................................. 34

2. Python: Execution Environment and How to Use It ··············· 35


2.1 Learning goals of this chapter ......................................................................... 35
2.2 Assumptions regarding the learning environment .......................................... 35
2.3 Setup ............................................................................................................... 35
2.4 Launching IDLE............................................................................................... 36
2.5 Python Shell .................................................................................................... 36
2.6 Writing and running scripts ............................................................................. 39
2.7 Setting the working directory with the Anaconda Prompt ............................... 41
2.8 IDLE keyboard shortcuts ................................................................................. 43
2.9 Executing Python commands ......................................................................... 43
2.10 Creating a good environment for learning Python .......................................... 45
2.11 For Mac users ................................................................................................. 46
References .................................................................................................................. 48

3. Assigning and Operating on Variables ································ 49


3.1 Learning goals of this chapter ......................................................................... 49
3.2 Flow of execution and information in programs .............................................. 49
3.3 Variable naming............................................................................................... 50
3.4 Variable assignment and evaluation ............................................................... 52

2
Table of Content Next Chapter Table of Contents

3.5 Assignment operators ..................................................................................... 53


3.6 Data types used in Python .............................................................................. 54
3.7 A more accurate understanding of Python variables ...................................... 56
3.8 Assigning multiple variables............................................................................ 56
References .................................................................................................................. 57

4. Exercise: Find the Square Root·········································· 58


4.1 Learning goals of this chapter ......................................................................... 58
4.2 The square root hiding in plain sight ............................................................... 58
4.3 Calculation procedure ..................................................................................... 59
4.4 Python program............................................................................................... 61
4.5 Be careful when using division........................................................................ 63
4.6 Notation to make equations easy to read ....................................................... 63

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

6. Control Flow ··································································· 78


6.1 Learning goals of this chapter ......................................................................... 78
6.2 Repeated processing using for-loops ............................................................. 78
6.3 Repetition using while-loops ........................................................................... 85
6.4 Branching using 'if' statements ....................................................................... 88
6.5 Termination of the Python program................................................................. 90
6.6 Input from the terminal .................................................................................... 91
6.7 Handling errors ................................................................................................ 92
6.8 Mathematical functions in Python ................................................................... 93
6.9 Converting numbers and strings; Combining strings ...................................... 94
6.10 Format specification when displaying a number............................................. 94

7. Making Kyoto Intersections ··············································· 96


7.1 Learning goals of this chapter ......................................................................... 96
7.2 Creating Kyoto’s intersections ........................................................................ 96
7.3 List of lists and how to scan them ................................................................... 97

8. Test of skills ·································································· 102


8.1 Learning goals of this chapter ....................................................................... 102
8.2 Fine tuning the square root calculation ......................................................... 102
8.3 Calculating Pi ................................................................................................ 102
8.4 Generating a deck of cards ........................................................................... 103
8.5 Intersections in Heian-kyō ............................................................................. 105
References ................................................................................................................ 107

9. Encapsulation of Processing Using Functions ···················· 108

3
Table of Content Next Chapter Table of Contents

9.1 Learning goals of this chapter ....................................................................... 108


9.2 Let’s make an absolute value function.......................................................... 108
9.3 Format for function definitions....................................................................... 109
9.4 Parameters and arguments .......................................................................... 109
9.5 Return values ................................................................................................ 110
9.6 From an exercise in a prior chapter .............................................................. 110
9.7 Let’s write the square_root() function ........................................................... 111
9.8 Treatment of variables within functions......................................................... 112
9.9 Common uses of functions ........................................................................... 113
9.10 Function calls and passing function objects ................................................. 115
9.11 Default parameters and keyword parameters .............................................. 115

10. Playing with Turtle ·························································· 117


10.1 Learning goals of this chapter ....................................................................... 117
10.2 Modules ......................................................................................................... 117
10.3 Turtle — The time-honored turtle .................................................................. 118
10.4 Python’s turtle module................................................................................... 118
10.5 Let’s try it out ................................................................................................. 119
10.6 The major functions in the turtle module....................................................... 121
10.7 Moving multiple turtles .................................................................................. 121
10.8 Tips for creating your project......................................................................... 123
10.9 Turtle Demo ................................................................................................... 128
10.10 Theme: Creating projects with turtle ............................................................. 128
10.11 How to take a screenshot ............................................................................. 128
References ................................................................................................................ 129

11. Creating a GUI Application with Tkinter (1) ························· 133


11.1 Learning goals of this chapter ....................................................................... 133
11.2 GUIs and event-driven programming............................................................ 133
11.3 Separating the model and user interface ...................................................... 133
11.4 tkinter ............................................................................................................. 134
11.5 A simple exercise .......................................................................................... 135
11.6 tkinter example of calculator (tkdemo_2term.py).......................................... 138
11.7 Basic structure of a program using tkinter .................................................... 141
11.8 Layout on a grid ............................................................................................ 142
11.9 Writing a callback function using a lambda (λ) notation ............................... 143
11.10 Configuring the appearance of a widget ....................................................... 146
11.11 How to close tkinter ....................................................................................... 148
11.12 How to extend the Frame class .................................................................... 149
11.13 Utilizing images with tkinter........................................................................... 152
References ................................................................................................................ 154

12. Creating a GUI Application with Tkinter (2) ························· 155


12.1 Learning goals of this chapter ....................................................................... 155
12.2 Conflicts between autonomous programs and GUIs .................................... 155
12.3 Analog clock program using tkinter............................................................... 155
12.4 Coordinating actions using variables ............................................................ 163

13. Classes ········································································· 164


13.1 Learning goals of this chapter ....................................................................... 164
13.2 Object-oriented programming ....................................................................... 164
13.3 How to write and use classes in Python ....................................................... 164
13.4 Class variables and access restrictions ........................................................ 167
13.5 Inheritance..................................................................................................... 170
13.6 Designing classes starting from instances.................................................... 170

4
Table of Content Next Chapter Table of Contents

14. File Input/Output ···························································· 171


14.1 Learning goals of this chapter ....................................................................... 171
14.2 How to store data permanently ..................................................................... 171
14.3 Regarding files .............................................................................................. 171
14.4 Let's try to run the code below first. .............................................................. 174
14.5 Reading and writing files in Python ............................................................... 174
14.6 Example 1 Wave approximation ................................................................... 176
14.7 Example 2 Text Editor ................................................................................... 181

15. Learning Program Development with Tic-Tac-Toe ················ 184


15.1 Learning goals of this chapter ....................................................................... 184
15.2 Developing a program ................................................................................... 184
15.3 Design procedure - what to do before using your computer ........................ 184
15.4 Designing a simple tic-tac-toe program ........................................................ 185
15.5 Implementation of the program ..................................................................... 191
15.6 Test of skills ................................................................................................... 206
15.7 Various topics related to program development ........................................... 206

16. Academic Use of Python ·················································· 208


16.1 Learning goals of this chapter ....................................................................... 208
16.2 Using a custom name when importing.......................................................... 208
16.3 NumPy........................................................................................................... 209
16.4 Matplotlib ....................................................................................................... 212
16.5 pandas........................................................................................................... 222
16.6 Practice task .................................................................................................. 228
References ................................................................................................................ 230

17. Review, and Where to Go From Here ·································· 231


17.1 Learning goals of this chapter ....................................................................... 231
17.2 Reflection ...................................................................................................... 231
17.3 Shuhari (three stages of mastery) - “Obey, Digress, Separate” ................... 231
17.4 Python environments .................................................................................... 231
17.5 Adding modules ............................................................................................ 232
17.6 Topics not covered in this book ..................................................................... 232
17.7 Gratitude and repayment - how to make use of what you have learned ...... 232
References ................................................................................................................ 233

18. Appendix: Useful notes on Python and IDLE ······················ 234


18.1 Useful notes on Python ................................................................................. 234
18.2 Pay attention to file names ............................................................................ 234
18.3 IDLE notes: Python shell hotkeys ................................................................. 234
18.4 IDLE notes: Editor ......................................................................................... 234

19. Appendix: How to Read Error Messages in IDLE/Python ······· 236


19.1 Errors displayed by the IDLE editor .............................................................. 236
19.2 Errors displayed in Python shell when executing code ................................ 240

5
Table of Figures Next Chapter Table of Contents

Table of Figures
Figure 1-1 Jacquard machine and Analytical Engine ............................................................ 20

Figure 1-2 Progression of logic gates .................................................................................. 21

Figure 1-3 Microprocessor transistor counts ........................................................................ 21

Figure 1-4 Computer (hardware) organization ..................................................................... 23

Figure 1-5 Programming languages and language processors ............................................. 24

Figure 1-6 Types of language processors ............................................................................ 25

Figure 1-7 JIS keyboard layout ........................................................................................... 31

Figure 1-8 Frameworks and libraries ................................................................................... 34

Figure 2-1 Creating a folder to hold your programs.............................................................. 36

Figure 2-2 Starting IDLE from the Anaconda Prompt ........................................................... 36

Figure 2-3 IDLE’s Python Shell ........................................................................................... 37

Figure 2-4 Operating the Python Shell ................................................................................ 38

Figure 2-5 Note the differences between IDLE Editor and the Python shell .......................... 40

Figure 2-6 Interactions between IDLE shell and Editor ........................................................ 41

Figure 2-7 Running Python in interactive mode ................................................................... 44

Figure 2-8 Running Python via a specified script ................................................................. 45

Figure 2-9 Using the -i option to stay in interactive mode once the program is finished running
............................................................................................................................... 45

Figure 2-10 Launching the online manual from IDLE ........................................................... 46

Figure 2-11 Python online manual (the right side is after selecting Japanese) ...................... 46

Figure 2-12 Inputting backslash on Mac .............................................................................. 47

Figure 3-1 Visual representation of variable assignment and evaluation .............................. 53

Figure 3-2 In Python, a variable can have any type ............................................................. 55

Figure 3-3 Python variables contain information on data (object) location ............................ 56

Figure 4-1 Intuitive explanation of square root approximation .............................................. 61

Figure 4-2 Calculation steps ............................................................................................... 61

Figure 5-1 List assignment .................................................................................................. 71

6
Table of Figures Next Chapter Table of Contents

Figure 5-2 Copying and assigning lists ................................................................................ 71

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 9-1 Arguments and Parameters ............................................................................... 110

Figure 9-2 Global variables and local variables .................................................................. 113

Figure 9-3 Common uses of functions ................................................................................ 114

Figure 9-4 Function calls and “side effects” ........................................................................ 114

Figure 10-1 A result of executing random_turtle.py ............................................................ 124

Figure 10-2 A result of executing turtle-tree.py .................................................................. 125

Figure 10-3 Former Toyosato Elementary School building and banister (10/16/2016 Kita
Photography) ........................................................................................................ 125

Figure 10-4 Execution result of Program 10-5 ................................................................... 127

Figure 10-5 How to run the Turtle Demo ............................................................................ 128

Figure 10-6 Keys used to take a schreen shot in Windows ................................................ 129

Figure 11-1 Framework for event-driven programming ....................................................... 133

Figure 11-2 Model-View-Control Architecture ..................................................................... 134

Figure 11-3 Tkinter system configuration ........................................................................... 135

Figure 11-4 Object relationships in tkinter ......................................................................... 137

Figure 11-5 Behavior carried out by the widgets, call back functions, and global variables . 138

Figure 11-6 Layout with grid .............................................................................................. 143

Figure 11-7 Execution of Program 11-5 ............................................................................. 154

Figure 12-1 Use of 'after' in tkinter .................................................................................... 155

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 12-4 Coordinating actions using variables .............................................................. 163

Figure 13-1 Class and Instance Variables ......................................................................... 169

Figure 14-1 Approximation of a sawtooth wave by summing trigonometric functions .......... 176

Figure 14-2 Approximation of a sawtooth wave by summing trigonometric functions (with


positive slope at the origin) ................................................................................... 177

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 14-5 Using a “list of each series’” ........................................................................... 181

Figure 15-1 Example tic-tac-toe game records .................................................................. 186

Figure 15-2 Determining victory for the turn in question ..................................................... 189

Figure 15-3 Determining the winner .................................................................................. 189

Figure 15-4 Overall source code structure ......................................................................... 191

Figure 15-5 The V-Model of Software Development ........................................................... 207

Figure 16-1 The relationship between NumPy, Matplotlib and pandas ................................ 208

Figure 16-2 Execution of Program 16-1 ............................................................................. 214

Figure 16-3 Example of Matplotlib usage ........................................................................... 215

Figure 16-4 Drawing a scatter plot .................................................................................... 217

Figure 16-5 Drawing a Histogram ...................................................................................... 218

Figure 16-6 Drawing multiple graphs ................................................................................. 220

Figure 16-7 Graphing with pandas .................................................................................... 227

Figure 16-8 A power graph and an approximation of a sawtooth wave by summing


trigonometric functions .......................................................................................... 229

8
Table of Tables Next Chapter Table of Contents

Table of Tables
Table 1-1 Symbols used in programming and their pronunciations ....................................... 32

Table 2-1 Arithmetic operations in Python ............................................................................ 38

Table 3-1 Python assignment operators ............................................................................... 54

Table 3-2 Data types used in Python ................................................................................... 54

Table 5-1 Notation for lists, tuples, and dictionaries ............................................................. 77

Table 6-1 Comparison operators in Python .......................................................................... 89

Table 6-2 Conversions between numbers and strings .......................................................... 94

Table 6-3 Connecting and repeating strings ......................................................................... 94

Table 10-1 Key Operation to Take a Schreen Shot ............................................................. 129

Table 11-1 Specifying colors with tkinter ............................................................................ 146

Table 16-2 sample.csv ...................................................................................................... 224

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 5-1, Keeping calculation process in a list (p5-1.py)................................................ 74

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-3 continue and break (p6-3.py) .......................................................................... 81

Program 6-4 Calculating sum (p6-4.py) ............................................................................... 82

Program 6-5 Nested for-loops (p6-5.py) .............................................................................. 83

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 6-8 Forking using multiple conditions (p6-8.py) ..................................................... 90

Program 6-9 Forking with nested 'if' statements (p6-9.py) ................................................... 90

Program 6-10 Termination of the Python program (p6-10.py) ............................................... 91

Program 6-11 Program that checks user input (input_check.py) ........................................... 92

Program 7-1 Making Kyoto intersections (p7-1.py) .............................................................. 96

Program 7-2 Making a table of Kyoto intersections (p7-2.py) ............................................... 99

Program 7-3 Making a table of Kyoto intersections (p7-3.py) ............................................. 100

Program 8-1 Card deck generation (incomplete, p8-1.py) .................................................. 104

Program 9-1 Example of an absolute value function (p9-1.py) ......................................... 108

Program 9-2 Example of an absolute value function (p9-2.py, returns when possible) ........ 108

Program 9-3 Implementation of the square_root() function (p9-3.py) .................................. 111

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-3 Moving multiple turtles (p10-3.py) ............................................................... 121

Program 10-4 Responding to mouse clicks in turtle graphics (p8-4.py) .............................. 123

Program 10-5 Defining the shape of a turtle (p10-5.py) ..................................................... 126

Program 10-6 random_turtle.py ......................................................................................... 130

10
Table of Programs Next Chapter Table of Contents

Program 10-7 detour.py .................................................................................................... 131

Program 10-8 turtle_tree.py .............................................................................................. 132

Program 11-1 Simple tkinter exercise (tkdemo.py) .......................................................... 136

Program 11-2 Calculator for addition only (tkdemo_2term.py) ............................................ 139

Program 11-3 Setting up a callback function with arguments using a lambda notation
(tkdemo_2term_lambda.py) ................................................................................... 144

Program 11-4 How to extend the Frame class in tkinter (tkdemo-2term_frame_extention.py)


............................................................................................................................. 149

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-1 CUI calculator program (p13-1.py) .............................................................. 165

Program 13-2 Class variables and instance variables (p13-2.py) ....................................... 168

Program 14-1 Example of File Input/Output (p14-1.py) ...................................................... 174

Program 14-2 Approximation of a sawtooth wave by summing trigonometric functions (p14-


2.py) ..................................................................................................................... 178

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

Program 16-1 matplotlib example(use_matplotlib_outline.py) .......................................... 213

Program 16-2 use_matplotlib.py ........................................................................................ 216

Program 16-3 use_matplotlib_scatter.py ............................................................................ 217

11
Table of Programs Next Chapter Table of Contents

Program 16-4 use_matplotlib_hist.py ................................................................................ 219

Program 16-5 use_matplotlib_subplot.py ........................................................................... 220

Program 16-6 use_read_csv.py ......................................................................................... 226

Program 16-7 use_DadaFrame_plot.py ............................................................................. 227

Program 16-8 Drawing graphs of powers of 1 to 4 with Numpy and Matplotlib


(use_matplotlib_power_function.py) ...................................................................... 229

Program 19-1 missing_colon_error.py ............................................................................... 236

Program 19-2 missing_parentheses_error.py..................................................................... 237

Program 19-3 insufficient_indentation_error.py .................................................................. 238

Program 19-4 excess_indentation_error.py ....................................................................... 239

Program 19-5 referencing_undefined_variable_error.py ..................................................... 240

Program 19-6 wrong_argument_type_error.py ................................................................... 241

Program 19-7 incorrect_indentation_in_class_error.py ...................................................... 242

Program 19-8 incorrect_optional_argument_error.py ......................................................... 243

Program 19-9 error-in-function.py ..................................................................................... 244

12
Table of Exercises Next Chapter Table of Contents

Table of Exercises

Exercise 1-1 Motives for taking this course ......................................................................... 19

Exercise 1-2 Symbols used in Programming ........................................................................ 33

Exercise 2-1 Reviewing arithmetic operations ..................................................................... 38

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 3-1 Programs and sheet music.............................................................................. 49

Exercise 3-2 Practice using various variable names ............................................................ 52

Exercise 3-3 Explaining the behavior of variables ................................................................ 53

Exercise 3-4 Confirmaton of data type ................................................................................ 55

Exercise 4-1 Creation and execution of a program to obtain square root .............................. 61

Exercise 4-2 Experience errors (1) ...................................................................................... 63

Exercise 4-3 Solve for the square root of some other numbers. ........................................... 63

Exercise 5-1 Store calculation process in a list .................................................................... 75

Exercise 5-2 Store estimated accuracy in a list ................................................................... 75

Exercise 6-1 Apply 'for' statement to the program of solving square root .............................. 78

Exercise 6-2 Checking the block ......................................................................................... 79

Exercise 6-3 Prank ............................................................................................................. 80

Exercise 6-4 Experience errors (2) ...................................................................................... 80

Exercise 6-5 Experience errors (3) ...................................................................................... 81

Exercise 6-6 Explanation of continue and break .................................................................. 81

Exercise 6-7 range() function .............................................................................................. 82

Exercise 6-8 Calculation of sum .......................................................................................... 83

Exercise 6-9 Nested for-loops ............................................................................................. 83

Exercise 6-10 Solving for averages ..................................................................................... 85

Exercise 6-11 Change access to list elements ..................................................................... 85

13
Table of Exercises Next Chapter Table of Contents

Exercise 6-12 Write and run Program 6-6 ............................................................................ 86

Exercise 6-13 Experience errors (4). ................................................................................... 90

Exercise 6-14 Input number form terminal ........................................................................... 92

Exercise 6-15 Reviewing Error Handling ............................................................................. 92

Exercise 6-16 Use of math module ...................................................................................... 94

Exercise 7-1 Creating a table of Kyoto intersections ............................................................ 99

Exercise 7-2 Outputting lists of lists .................................................................................. 101

Exercise 8-1 Fine tuning the square root calculation ......................................................... 102

Exercise 8-2 Calculating Pi using the Leibnitz formula ....................................................... 103

Exercise 8-3 Generating a deck of cards ........................................................................... 103

Exercise 8-4 Generating Heian-kyō intersections .............................................................. 106

Exercise 9-1 Create an absolute value function ................................................................. 109

Exercise 9-2 Experience errors (5). ................................................................................... 109

Exercise 9-3 Create a function to solve squate root ............................................................ 112

Exercise 9-4 Create a function to solve squate root (2 nd ) .................................................... 112

Exercise 10-1 Draw a regular polygon with n faces ............................................................ 119

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-1 Create an Addition Calculator with Tkinter ................................................... 147

Exercise 11-2 Configuring the appearance of a widget ...................................................... 147

Exercise 11-3 Extending the Calculator to Four Arithmetic Operations (Skill Test) .............. 147

Exercise 11-4 Management of Widgets with List (Skill Test) ............................................... 148

Exercise 11-5 Differences with an actual calculator ........................................................... 148

Exercise 12-1 Reviewing the methods to be used .............................................................. 162

Exercise 12-2 Modifying the analog clock .......................................................................... 162

Exercise 12-3 Improving the display .................................................................................. 163

Exercise 13-1 Extention of Calculator Class ...................................................................... 167

Exercise 13-2 Creation and Utilization of Multiple Objects ................................................. 167

14
Table of Exercises Next Chapter Table of Contents

Exercise 13-3 User Calculator Class in the Tkinter Program .............................................. 167

Exercise 14-1 Square wave approximation ........................................................................ 180

Exercise 14-2 Implementation of the list from Example 1 ................................................... 180

Exercise 15-1 Programming Branching with Complicated Condition ................................... 190

Exercise 15-2 Relationship of functions in tic-tac-toe program ........................................... 205

Exercise 15-3 Getting the game record ............................................................................. 205

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.

0.1 Learning goals of this chapter


The objectives and goals of this course are as outlined below.

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.

0.2 Reasons for writing an entirely new textbook


This text was based on the courses from the 2018-2022 academic years. There are already a large
number of introductory texts for Python, however, due to the reasons detailed below, it was decided
to add yet another text into the mix.
 This course does not aim to introduce the reader to Python, but rather to teach students how to
write (to become able to write) their own programs in Python. Many texts have the tendency
to merely be an introduction to the language itself.
 For beginners, learning a programming language is simply the overcoming of various
mistakes. Even mistakes that seem severe when you are a beginner are often completely
forgotten once you have gained some programming experience. Through practical exercises,
this course aims to keep the spots that beginners tend to make mistakes in mind, and to tailor
the explanations in a manner that helps them overcome these mistakes.
 Related to the above, learning a programming language consists of writing and executing
actual programs by yourself. This text includes directions for actual programming exercises.
While this text serves as a guide for beginners that explains the fundamentals of programming using
Python, it is not a comprehensive introduction of Python’s language specifications. It is
recommended for students to prepare other learning materials on Python and take them to classes.

16
0 Foreword Next Chapter Table of Contents

0.3 Humanities majors: you can do it!


It seems that there are many humanities students that think of programming as something that should
be left for the science majors. Programming is indeed a technique to control the complex machines
known as computers, and source code can often look like numerical formulas. However, in actuality,
programming merely delegates to machines work that humans can perform themselves. It is
important to firmly understand the actions performed by humans because in this respect humanities
students can gain an edge. Many humanities students have taken this course in the past and received
passing grades.

0.4 Regarding the organization of this text


This text was organized based on the courses from the 2018-2020 academic years. As such, it is
structured such that you can work through the exercises in order from the front of the book. Topics
from the classes that represent a digression from the topic at hand are compiled as independent
“Columns.”

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.

0.6 Warning regarding copying and pasting


The source code that appears in this text was formatted in Word before being converted to PDF
17
0 Foreword Next Chapter Table of Contents

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.

0.7 Edits for later versions (2023 and later)


In the 2023 version, some misprints were corrected, some hard-to-read portions were edited, and
some additional explanations given during the 2022 course were added. The square root calculation
that was used as an exercise in Chapter 3 has been improved and added as its own section in Chapter
4. In addition, portions on Python program termination were added to the chapter on control flow
(Chapter 6), and various practical exercises covering material through Chapter 7 were added as
Chapter 8. Furthermore, ways of defining the turtle shape in the turtle graphics chapter (Chapter 10)
have been added, and a simple exercise to help introduce tkinter was added to chapter 11 alongside
improvements to the explanation. Image display has also been added to the widget. An example of an
error that can occur during function calls was added to chapter 19.

Notes for English Version


This textbook is a translation of the Japanese version referred to as “Puroguramingu-Enshuu Python
2023 (プログラミング演習 Python 2023).” The original version cited several Japanese references.
We have retained some quotes and references in Japanese.

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

1. Computers and Programming


1.1 Learning goals of this chapter
 Understand how computers operate in general, and how programs factor in.
 Learn about the role of programming languages in programming.

 Learn about various uses and applications for writing programs.


 Learn about how to study programming.

Exercise 1-1 Motives for taking this course


Please answer the following questions.
1. Why did you decide to take this course?
2. Why do you want to learn programming?
3. Why do you want to learn Python?
4. Please indicate whether you have any previous experience with studying programming (Yes
or no). If yes, how much?
5. For those with previous experience studying programming, what programming language(s)
did you use?

1.2 Computers and programs

Machines that are run by programs


You have probably heard of the Jacquard machine sometime in a history course. Textiles are woven
by passing a weft thread through a warp thread. One can weave a specific design by varying which
warps are run on top of the weft and which are run beneath. A Jacquard machine is a machine that
can correctly weave the thread provided it is given instructions regarding which way to run the
thread in the form of paper with holes punched into it (referred to as punch cards). By binding
together many punch cards and feeding them into the machine in order, one can create complex
designs. In order to create a different pattern, one simply needs to swap out the punch cards.
One can still find Jacquard machines actively used in the Nishijin district in Kyoto, where weaving is
a booming local industry. Figure 1-1
Charles Babbage (1791-1871) was an inventor from Great Britain who set out to develop a
mechanized calculator. Starting with a mechanism that automatically generated number tables from
sequences of differences, Babbage took inspiration from the Jacquard machine and attempted to
create a mechanized calculator (The Analytical Engine) that is run by a program. Unfortunately, he
was never able to complete it; however, he is viewed as a pioneer in the field of computer science for
his attempts to make a mechanism that performs calculations according to a program.

19
1 Computers and Programming Next Chapter Table of Contents

Jacquard machines and punch cards Babbage’s Analytical Engine


Taken at Fukuoka Weaving in Kyoto

Figure 1-1 Jacquard machine and Analytical Engine


https://commons.wikimedia.org/wiki/File:AnalyticalMachine_Babbage_London.jpg

Computers are composed of “switches” that run by


electricity

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

Increase in speed due Increase in Less parts


to lack of mechanical lifespan Reduction in size,
components Reduction in size increase in speed,
Less power reduction in cost
ti
Figure 1-2 Progression of logic gates
Next, we will take a look at the amazingly rapid progression of the number of transistors that could
be integrated onto a single semiconductor chip (degree of integration), which has increased by over a
million times in 40 years. Technological innovations that improve efficiency by orders of magnitude
effected not only integrated circuits, but storage capacity and communication speed as well. It is
through technological innovations like this that you are able to use your smartphone to enjoy
YouTube videos in the modern era.

Figure 1-3 Microprocessor transistor counts


https://en.wikipedia.org/wiki/Transistor_count#Microprocessors
Plot of a selection of Intel processors (Accessed Jan. 2, 2017)

1.3 Computer structure

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

giant supercomputers, are stored-program computers.


By changing programs according to the type of work that needs to be done, the same computer
(hardware) can be used to accomplish a wide variety of tasks.
Programming is the act of writing out, in the form of a program, the data processing steps that you
wish to perform.

The Components of Computers and Their Functions


The main components of a computer’s hardware are the CPU and the memory.
The CPU contains the following major elements of a computer.
 Mechanism(s) to take in and parse commands from the memory
 Counters that point to the memory addresses of the program(s) that are currently being run
 Device(s) to preserve data (registers)
 An arithmetic-logic unit (ALU) that functions to perform arithmetic and logical operations on
variables

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

Figure 1-4 Computer (hardware) organization


In order for the hardware (CPU + memory) to be able to easily process commands at high speeds, the
commands that can be executed in actual computers are limited to extremely simple ones. These
commands are referred to as machine code.

1.4 Programming languages


Programming complex actions in machine code is profoundly difficult. Programming languages were
the solution devised in order to solve this problem, and they are created in the following manner.
 Determine rules that enable you to write programs in a manner that are more easy-to-
understand for people (decide upon programming language specifications). Generally
something that looks less like machine code and closer to numerical formulas
 Create a program that can execute any program (source code) written in accordance with the
rules of the language (build a language processor)
Essentially, you write a program in the programming language, and the written program is executed
using the language processor. In simpler terms, an language processor + a computer effectively
yields a virtual computer that can execute any program written in a programming language.

23
1 Computers and Programming Next Chapter Table of Contents

Code in accordance with Programming


Programming
the specifications language
language
specifications
specifications

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

Figure 1-5 Programming languages and language processors

Various programming languages


As shown in the table below, many programming languages have been created and are in common
use.
FORTRAN COBOL ALGOL Pascal PL/I
BASIC C, C++, C# Java Go Swift
Perl Ruby Python JavaScript LISP
Haskel R Matlab ProLog Scratch

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.

Composition of a language processor


There are a few different ways to compose programs (language processors) that can process and
execute programs (source code) written in a programming language. The three variations are as
follows:

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.

3) Intermediate representation (IR)


Lying somewhere in between compilers and interpreters, IR translates the source code not into the
CPU’s machine code, but rather into machine code (intermediate representation) for a hypothetical
virtual computer used for that language. This IR is then executed using an interpreter (virtual
machine). Java and Python use this type of translator.

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

Figure 1-6 Types of language processors

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.

Python distribution packages


There are several Python language processors in development, and as a result there are many
packages that contain different combinations of things such as development environments, and
libraries. For this class, we will use the following two packages:
 Python: A distributable from the designers of Python; uses CPython, which is coded in the C
language, as its language processor.
 Anaconda: Contains modules for scientific computing wrapped into CPython as a single
package. We assume that you will be using this package in this class.

1.6 Various applications


There are likely some of you who have specific applications in mind as reasons for why you want to
learn Python. Let’s look at some of its various potential usages.

Applications for personal computers (PCs)


Programs that run on PCs can largely be divided into two groups based on their operating
environments.

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.

1.7 How to learn programming

Reasons why programming is difficult


Computer programming can be difficult for a variety of reasons. Understanding how and why it is
difficult will likely help you in your journey to learn programming.

1) The concepts that compose programming languages are hard to


understand
Even the natural languages that you use every day require complex grammar and diction in order to
express complex ideas. Similarly, programming languages require you to employ various concepts
and contrivances in order to skillfully express complex programs.
There is no need for you to try to understand all of these concepts at once. You can gradually work
your way up from the simplest ones.

2) Unable to deal with errors


In programming, various errors (called bugs to liken them to metaphorical bugs eating away at the
program) arise from mistakes and typos. It is important to go into programming with the

27
1 Computers and Programming Next Chapter Table of Contents

understanding that you will frequently encounter bugs, however:


 You should understand that accurate typing in accordance with the syntax of the source code
is necessary.
 Syntax errors aside, there will be times when misconceptions about the program lead to it
operating in a manner that defies expectations.
 The vast majority of bugs are due to human error. It is important for you to gradually build up
experience recognizing and dealing with various errors.
 Dealing with errors involves backtracking from the result of “an error has occurred” to the
root problem that is causing it. You will need to come up with various hypotheses about the
cause of the error that correspond to the type of error you have encountered and then
investigate to determine whether or not it is actually the cause.
 There are times when the computer’s response (when the computer has been rendered unable
to process) does not match up with the actual mistakes in the program.

3) Unable to add the feature that you wish to implement


Even if you learn the components that make up a programming language, it can often be difficult to
figure out how to combine them in a manner that produces the desired result. Just like how even if
you know how to use a hammer and saw, you cannot build a house unless you know how a house is
built.
It is necessary to thoroughly analyze what you wish to do in plain words and then to write the
program after getting a clear understanding of the procedure. You can start by learning from
examples of relatively simple applications and gradually working your way up.

4) The program becomes too complicated to understand


When a program becomes very long it gets more and more complex and it can suddenly become
difficult to make sense of just what you are programming. For beginners, even a 100 line program
can seem very daunting. Learners should work towards a goal of writing a 100 line program as they
gradually pick up methods of coding in a way that makes longer programs much easier to navigate.

5) There are techniques for writing large programs


Some of the largest programs in the world can reach hundreds of millions of lines. Naturally, a single
person cannot write these programs on his/her own, nor can he/she know all of the lines of code they
contain. There are certain methods and tools for writing such huge programs. Some examples can be
seen below.
 Create a thorough plan for the entire program
 Partition it into modules so that the work can be divided
 Write and test the program module by module.
 Test the entire program after putting it all together
Once you are able to write programs of around 100 lines, it is a good idea to challenge yourself to
write a larger program with these techniques in mind.

28
1 Computers and Programming Next Chapter Table of Contents

How to learn programming


As with all subjects, it is essential for you to learn how to learn.
 How do you pick up a foreign language?
 How do you learn mathematics?
Programming is the skill of actually writing programs with your own hands, so in that sense, it is
similar to other practical skills like math and foreign languages. However, programs can be tested as
you write them, and they can have all sorts of interesting applications, so they should not be as
intimidating as math or foreign languages.

1) Motivation: you should work with things that interest you


 Your motivation for learning is critical if you wish to be able to persist in their studies. There
are many people who say vague things like “I want to learn how to program.” However, this
alone is too vague to serve as a concrete goal, which makes it easy for you to lose motivation.
Fixating on something more concrete, even something more difficult like “I want to make a
game” is usually more effective. Choosing a certain subject or application that you are
interested in makes it easier for you to preserve your motivation to learn.

2) Lots of reading and writing is fundamental to learning programming


 Type out and execute a bunch of exercises.
 “Understand through doing” rather than “do after understanding”
 Learn the patterns in vocabulary, symbols, and notations. It’s important to learn common
patterns as a single unit.
 Typing source code more quickly and accurately helps raise your learning efficiency.

3) Reading aloud/Read while interpreting


 Reading the symbols in the source code out loud while interpreting their meaning is an
important ability that helps to facilitate effective communication in class.

4) Tinkering: play around with programming exercises.


 Make small changes to programs found in exercises to gain a feel for what is possible.
 Try combining multiple exercises. Doing so will help you understand what adjustments are
necessary when combining programs.

5) Tracing
 Follow a program manually by hand in order to see how it will function (called tracing)

6) Become able to deal with errors


 When programming, you are constantly dealing with errors. Becoming able to do so is an
important goal in and of itself.
 Actual programming requires you to be able to deal with unforeseen errors, but intentionally

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.

Characters used in programs


Most programming languages are designed with English as a basis, so you will need to keep this in
mind when dealing with characters and character encoding. Reference the column titled
"Programming & Japanese - The Never-ending Battle against Character Encoding."
 Python (and most programming languages) uses half-width alphanumeric characters.
 Full-width characters are only used in strings and comments 1.
 Python distinguishes between uppercase and lowercase letters (it is “case sensitive”).
 Various symbols are used in programming.
 It is important to learn the appropriate names for these symbols,
 not just their location on the keyboard. This ensures you can communicate about these
symbols with others.
 In addition, you will need to be able to press keys, such as the C key, while holding down the
Ctrl key. This is written as Ctrl-C. The same is true for the Alt key.

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

Figure 1-7 JIS keyboard layout


Various symbols are arranged differently than in an English keyboard (ASCII layout).

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

Table 1-1 Symbols used in programming and their pronunciations

Symbol Pronunciation Notes


␣ Space Denoted as ␣ in the symbol column for
ease of understanding.
Programs use half-width spaces. Note that
using full-width spaces in anything other
than strings of Japanese text will result
in an error that will be difficult to
troubleshoot.
! Exclamation mark

" 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

< Less than


> Greater to
= Equals, equal sign
? Question mark
@ At sign, at
\ Yen symbol In JIS encoding, ¥ is assigned the same
\ Backslash code as \. The Unicode (UTF-8) encoding
used in Python assigns these symbols
different codes, but many Windows
Japanese fonts display ¥ in place of \.
Mac users can simply just use a
backslash.
^ Caret, free-standing circumflex
_ Underscore, underline In Python, you will often use underscores
by combining two in a row like so: __

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)

<= Less than or equal to 2 characters


>= Greater than or equal to 2 characters
!= Not equal to 2 characters

== Double equal sign, equal-to 2 characters


operator

Exercise 1-2 Symbols used in Programming


Review the names of the symbols used in programming as well as their locations on the keyboard.

1.8 The fundamental concepts used in programming


The following are the fundamental concepts that make up programs, both in Python and in most
other programming languages.
 Arithmetic, strings, logical (true or false) operators
 Variables, variable assignment, evaluating variables (using the assigned value)
 Switching how the program functions based on various conditions (branching)
 Repeating certain lines of the program
 Coding for and calling a fixed set of operations (defining and calling functions)
 Managing complex data
 Input/output (computer terminals, GUIs, files, networks)

1.9 What part of the program do you write?


Nowadays, it is extremely rare for anybody to write an entire application all by themselves. You
should understand that coding generally consists of programming things that fall in between the two
categories below.
 Framework: The GUIs used by applications on personal computers as well as the web
servers that web applications run on are almost always pre-existing programs. A program like
this is called a framework.
 Library: On the other hand, mathematical functions like sine and cosine that many people
will find useful are generally used as part of a pre-existing library.
That is to say, you code the specific operations of their program within a framework while using a

33
1 Computers and Programming Next Chapter Table of Contents

library that suits your programming needs.

Library

Use as needed

Parts you write yourself

Framework
(The framework within which GUIs and web server programs operate)

Figure 1-8 Frameworks and libraries

References
喜多 一,岡本雅子,藤岡健史,吉川直人:写経型学習による C 言語プログラミングワーク
ブック,共立出版(2012, in Japanese

34
2 Python: Execution Environment and How to Use It Next Chapter Table of Contents

2. Python: Execution Environment and How to


Use It
2.1 Learning goals of this chapter
 Learn how to start Python’s integrated development environment, IDLE.
 Learn how to operate the Python Shell within IDLE.
 Learn how to use the editor to edit Python programs (scripts) in IDLE.

2.2 Assumptions regarding the learning environment


This text was written with the assumption that Kyoto University’s dedicated learning computers
would be used. As such, it assumes Python learning will occur in the following environment.
 Operating system: Windows 11
 Python distributable: Anaconda (made with Python 3)
 Python integrated development environment: IDLE (included with Anaconda)
Learners should install Anaconda on their own PCs. In the case that you do not intend to use the
numerical calculation modules introduced in Chapter 16 (NumPy, matplotlib, pandas), the original
Python package will suffice.
There are various integrated development environments for Python aside from IDLE, including
Jupyter Notebook and Spyder. IDLE is used as the integrated development environment for this text
because its functions are limited and thus it is easier for beginners to understand (easier for
instructors to teach with). In addition, it is easier to operate the turtle graphics that will be used as
examples. However, you should note that its startup method and behavior is slightly different
depending on whether you are using Windows or macOS. Important points regarding its use in
macOS will be presented later on.

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

Figure 2-1 Creating a folder to hold your programs

2.4 Launching IDLE


From the start menu, select the 'Anaconda Prompt' found within the 'Anaconda3' folder and double
click to start it. Once it starts, launch IDLE by typing idle (in uppercase or lowercase letters) into the
window and pressing the ENTER key.

Figure 2-2 Starting IDLE from the Anaconda Prompt

2.5 Python Shell

Confirming that it launched


When you launch IDLE, a Python shell like the one shown in the figure below will appear. This is an
environment in which Python can be executed in an interactive manner. Please check the following
two things:
 Double check the window title. The currently running Python version (IDLE Shell 3.10.12 in
this case) is displayed in the window title. When you have multiple versions of Python installed,

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.

Figure 2-3 IDLE’s Python Shell

Executing Python commands


Input
1+2
after the prompt in the Python shell and press the ENTER key. Henceforth, commands to be written
into the prompt will be shown in red text. This is a full-fledged Python program that gives the
answer to 1+2. The shell should execute this and return
3
in response. Results returned from the prompt will be written below in blue text.
Arithmetic operations in Python can be performed as shown in the table below. Multiplication uses
“*” and division uses “/.” Just like in mathematics, multiplication and division will be prioritized
over addition and subtraction. In addition, you can use () in order to specify the desired computation
sequence.
It is worth noting that in Python 3, “/” yields a float variable even when used on two integers. When
an integer is needed, you should use “//.” Also, there are many cases in which you would need to use
37
2 Python: Execution Environment and How to Use It Next Chapter Table of Contents

the remainder of a division operation in their program. The “%” operator can be used to obtain this
remainder.

Table 2-1 Arithmetic operations in Python

Operator Operation Notes


+ Addition
- Subtraction
* Multiplication
/ Division Returns a float variable in
Python
// Integer
division
% Remainder Gives the remainder of a division
operation
** Exponent Note that this is 2 characters.
( ) Prioritized Other types of brackets cannot be
operations used for this purpose.

Exercise 2-1 Reviewing arithmetic operations


Practice arithmetic operations in the Python Shell.

Input each of the next two lines (one at a time).


Reference the figure to the right.
a = 1 + 2
a
The first line is a command that assigns the value of
the equation “1+2” on the right-hand side of the “=” to
the variable “a” on the left-hand side. The shell will
not display anything after this command and will
simply request the next input.
The second line confirms the value of the variable a.
3
should be what the shell displays. Next, try
inputting Figure 2-4 Operating the Python Shell
print(a)
into the prompt. print() is a function that outputs the expression within the () onto the shell as
characters. As you would expect,
3
is displayed.

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.

2.6 Writing and running scripts


Next, we will learn how to write a multiline Python script and execute it all at once. To do this, you
will use the IDLE Editor to edit the commands.

Creating a new file


To create a new program, select “New File” from the “File” menu in the shell window. This should
launch the IDLE Editor.

Verifying the IDLE editor


The IDLE Editor and the Python shell look very similar. Use the three points detailed below in order
to tell them apart.
 The title of the window will be the name of the file that you’re editing. If you have selected
“New File,” the window title will be “Untitled.”
 The menus in this window are different than those in the Python shell. Make sure that there is
a menu called “run.”
 The interior of the window is blank. There is no “>>>” prompt like in the shell.
 The line and column of the cursor should be displayed in the bottom right if you are using
Windows.

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.

Coding, saving, and running a Python program


It’s only a two line program, but please input the text found in the yellow section of the table below
into the IDLE Editor.

Program 2-1 (p2-1.py)

Row Source code Notes


1 a␣=␣1␣+␣2 Assigns the result of the equation "1+2" on the right-hand side
2 print(a) to the variable a.
Outputs the value of the variable a to the screen.

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

Python Shell Launch

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

Figure 2-6 Interactions between IDLE shell and Editor


When you tell the Idle Editor to run something, the program is saved in the file, the Python shell is
reset, and the program is run 1. When the program has finished running, the Python shell will revert
2F

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.

Exercise 2-3 Confirmation of thr result after execution of Program 2-1


Once p2-1.py has finished running, run the following command to check the value of a.
print(a)

2.7 Setting the working directory with the Anaconda


Prompt
We created a folder to store our Python programs, so let’s set it so that this folder is opened by
default. You are not able to specify a working directory in IDLE, so you will just set one in the
Anaconda Prompt that runs IDLE. Set the working directory using the following procedure.

1. Create a shortcut for the Anaconda Prompt on the desktop


1) Right click on the Anaconda Prompt in the Start Menu

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) Select “More” => “Open file location”

3) Right click on the Anaconda Prompt icon in the explorer


4) Select “Send to” => “Desktop (create shortcut)”

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.

2.8 IDLE keyboard shortcuts


IDLE’s Python shell and IDLE Editor are very simple, however they come with some several useful
keyboard shortcuts. These can be read in IDLE’s online manual, but the most commonly used ones
are listed in 18 Appendix: Useful notes on Python and IDLE.

2.9 Executing Python commands


Python programs can also be run directly via the Anaconda Prompt. Please go through the following
steps.
1. Close any sessions of IDLE and Anaconda Prompt that are currently open.
2. Specify the working directory as described in the previous section.
3. Launch the Anaconda Prompt from the shortcut on the Desktop.
4. Input “cd” and press the ENTER key to confirm that the working directory has been set
properly.
5. Input “dir” and press the ENTER key to see a list of the files that are saved in this folder.
Check to make sure that p2-1.py is listed.
6. Input “python” and confirm that the Python shell is launched in the Anaconda Prompt. For the
time being, you are merely confirming that it launches, so either input “exit()” or input “C”

43
2 Python: Execution Environment and How to Use It Next Chapter Table of Contents

while holding the CTRL key to close the shell.


7. Specifying the name of a Python program (script) by inputting “python p2-1.py” and running
the Python command will execute the program. Please confirm that this command runs as
intended.
8. Specifying the -i option by inputting “python -i p2-1.py” causes it to revert to interactive
mode after running the program (as it does when running the program in IDLE)

Figure 2-7 Running Python in interactive mode

44
2 Python: Execution Environment and How to Use It Next Chapter Table of Contents

Figure 2-8 Running Python via a specified script

Figure 2-9 Using the -i option to stay in interactive mode once the program is
finished running

2.10 Creating a good environment for learning Python


• Python language processor: install Anaconda on your computer
• Look over the Python Language Reference
• Keep a book on Python (one that suits your learning style) on hand
• English dictionary (data confirmation, function and variable names)
• Notebook and writing utensil (PC notepad works too): write down things that spring to mind

Exercise 2-4 Prepare your own Python learning environment and report it.

Exercise 2-5 Redo today’s exercise in your personal learning environment.

45
2 Python: Execution Environment and How to Use It Next Chapter Table of Contents

Figure 2-10 Launching the online manual from IDLE

Figure 2-11 Python online manual (the right side is after selecting Japanese)

2.11 For Mac users


This text explains how to use Python in Windows. There are a few differences to consider when
using it with a Mac. Please reference the list below.

Installing Python and launching IDLE on Mac

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.

4) Japanese input in IDLE


Please note that using Japanese input in IDLE can cause it to become slow and unstable. At present
(9/29/2020), using Google Japanese input can lead to problems inputting characters. If this happens,
it is recommended to use Mac’s standard Japanese input.
For comments and other parts that don’t affect the program’s operation, one method is to simply
avoid using Japanese altogether.

5) Inputting backslashes in IDLE


In this textbook, there are sections in Chapters 11 and 12 in which yen symbols “¥” are input into the
programs. Mac users should input backslashes “\”
To input the backslash symbol “\” on Mac, hold down the bottom left “option” key and press the “¥”
key.

Figure 2-12 Inputting backslash on Mac


Press the ¥ key while holding the “option” key.

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

Problems with Tkinter on Mac.


Aside from the above, there are some things that rely on the operating system in which Mac users
will see some differences from Windows users. Some examples include the GUI environment
Tkinter, which uses a package called Tcl/Tk, and the handling of Japanese fonts in the graphing
module matplotlib.

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

3. Assigning and Operating on Variables

3.1 Learning goals of this chapter


 Understand the flow of execution and the flow of information in Python. Learn about sequential
execution.
 Learn about naming, assigning, and evaluating variables in Python.
 Learn about the basic data types in Python.
 Learn about the type() function which looks up data (object) types, and the id() function which
looks up the location of an object.

3.2 Flow of execution and information in programs

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

Exercise 3-1 Programs and sheet music


Computer programs share many similarities with sheet music. A fundamental characteristic of sheet
music is that the notes are played in order from the beginning (although they are read from left to
right which differs from top to bottom in programs). Also, note that there is notation that enables you
to change how certain parts are played or repeat certain parts.

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

Flow of information through variables


Meanwhile, in programs, information is processed at each step in the form of numbers or strings that
have been assigned to variables. As such, when compared to the flow of execution, the flow of
information can be quite difficult to follow, despite occurring through the assigning and checking of
the same variables. For example, in the code above, the value of the variable a that was set in the first
line is used by the print function in line 2.
How about in the following example?
a = 1 + 2
a = 3 + 4
print(a)

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

3.3 Variable naming

Programs also use variable names with multiple


characters
The variable name used in the previous example was 'a.' In mathematics, letters of the alphabet (and
even Greek letters) are often used. However, programming languages, which handle various types of
data, can use longer variable names. For example,
a
x
x2
root
square_root
and so on.

Variable naming rules


Please learn the following rules.
 You can use only uppercase letters, lowercase letters, numbers, and underscores.
 Uppercase and lowercase letters are treated as different characters.

50
3 Assigning and Operating on Variables Next Chapter Table of Contents

 A number cannot be used as the first character in a name.


 Reserved keywords used in Python syntax (words such as “if;” reserved keywords will be
displayed in red when using the IDLE Editor) cannot be used.
Variable names can use Japanese (kanji, etc.), however this is not common practice.

Use variable names that are easy to understand

1) Taking mathematics as an example


Using appropriate names facilitates smoother thinking and communication. For example, in
mathematics, if you write a linear function as
y = ax + b
you can immediately understand that y is a linear function of x, the slope is a, and the intercept is
b. This is because it is the standard convention to use x and y as variables, to have y be a function
of x, and to use a and b as parameters.
However,
b = xa + y
is the same equation that merely switches x and y with a and b. Suddenly it becomes much more
difficult to understand.

2) How to name variables in Python programs


In programs, good variable naming can go a long way towards making a program easier to
understand. Please try to keep the following things in mind.
 Try to choose variable names that represent what the variable does within the program. 1 2 F3 F

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

Exercise 3-2 Practice using various variable names


Run the program shown in Program 2-1 via the shell and practice changing the variable names to
various things.
 Please note that you need to change the variable in both the first and second lines to the same
thing.
 Try using a variable name of multiple words connected by an underscore.
 Also, see what error messages result from using variable names with reserved keywords or
names starting with a number.

3.4 Variable assignment and evaluation


Run the following program using the Python shell.
a = 1
print(a)
a = a + 1
print(a)
The variable 'a' is assigned the value of 1 in the first line.
In the third line, 'a' appears on both the left and right hand sides of the equation, so be careful when
reading it. In Python, this program does the following:
1. First, the expression on the right-hand side (a + 1) of the assignment operator (=) is
calculated.
 The variable 'a' is already assigned the value of 1, so the right-hand side will use “the
result of evaluating the value of a,” which is one. This gives us 1 + 1, yielding 2 as the
result of the calculation.
2. Next, this result is assigned (overwritten) to 'a,' the variable on the left-hand side.
Variables can be thought of as boxes with names.

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

Figure 3-1 Visual representation of variable assignment and evaluation

Exercise 3-3 Explaining the behavior of variables


Below is a program that calculates the price of a ¥1000 product at 15% off.
 This program contains a single error which causes it to yield an error message when run.
Please locate and explain the error.
 After correcting the error, explain how the program behaves.
kakaku = 1000
nebikiritsu= 15
kakaku = Kakaku*(100-nebikiritsu)/100
print(kakaku)

3.5 Assignment operators


In programs, you frequently need to add or subtract a fixed number (for example, 1) to a variable.
You can make use of the operators below (beyond just the assignment operator “=”) in order to
perform such operations more conveniently.

53
3 Assigning and Operating on Variables Next Chapter Table of Contents

Table 3-1 Python assignment operators

Operator Example Meaning

+= 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.

3.6 Data types used in Python


The previous examples dealt with integers. Python programs can make use of many other data types
(seen in the table below), including floating-point numbers, which contain numbers after a decimal
point, strings, and Booleans (True and False). One feature of Python is that integers are not limited to
a certain number of digits (although at some point they are limited by computer memory and
calculation speed). For example,
2**200
evaluates to
1606938044258990275541962092341162602522202993782792835301376
As for numerical data types, complex numbers can also be used.

Table 3-2 Data types used in Python

Type Explanation Constant Notes


Function used (literal)
to convert notation example
Integer 12345 No digit limit in Python
int()
Floating-Point A number that 1.0 Has a size limit (of significant
Numbers has values 2.99792458E8 digits and the range that can be
float() after the expressed). E8 means x108.
decimal point
String A sequence of 'aaa' Strings are surrounded by single or
str() characters "日本語" double quotes

Boolean Used to True The first letters of constants are


bool() 1 evaluate False uppercase.
conditions

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?”

Exercise 3-4 Confirmaton of data type


Run the following in the Python shell.
a = 1
b = 1/2
c = “ABC”

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

Figure 3-2 In Python, a variable can have any type

55
3 Assigning and Operating on Variables Next Chapter Table of Contents

3.7 A more accurate understanding of Python


variables
In reality, variables in Python do not directly hold data (objects) themselves, rather they contain
information (a reference) that points to the whereabouts of the object. You do not need to worry
about this very much right now, however it will become important down the line when learning
about how complex data like lists are handled.
The information that points to data locations that are held by a variable can be looked up using the
id() function.
a = 1
b = 2
print(id(a), id(b))

10 0.3 'Japanese' True

Here Here

Z U
Here Here

ⅹ Y

Figure 3-3 Python variables contain information on data (object) location

3.8 Assigning multiple variables


In Python, multiple variables can be assigned in one line by separating variables and expressions
with “,” on both the left and right sides of the equation. 1
a = 1
b = 2
c, d = a*2, b*2
print(c, d)
Running this gives

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

4. Exercise: Find the Square Root


4.1 Learning goals of this chapter
 For this exercise, we will deal with sequential execution and handle variables in order to find an
approximation for the square root of a given number. While the calculation method introduced
in this chapter is quite simple, it requires division of numbers with many digits. As such, it is
difficult to perform by hand, but computers can carry it out with ease.

4.2 The square root hiding in plain sight


This textbook is designed to be able to be printed on A4 paper. Take a sheet of A4 paper and fold the
bottom right corner so it overlaps with the left side . The triangle that results from this is an isosceles
right triangle.

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.

4.3 Calculation procedure


In order to solve for the square root √2 of a given number, follow the procedure below.
 Let the approximation of the square root be r. It can be initialized to the number whose square
root you want to find (2 in this example), or it can even be set to 1. In this case, let r = 2 .
 As another approximation of the square root, divide the number whose square root you wish to
find by the approximation r. In this example, that would give 2/r = 2/2 = 1. If the

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

The square root of x is in between r1


and r2

x r1 = rnew The average of r1 and


r2 is closer to the square
Repeat to get even closer
root
to the square root
r1 = rnew = (r1 + r2)/2
r1 = rnew = (r1 + r2)/2
r2 = x/r1

r2 = x/r1

Figure 4-1 Intuitive explanation of square root approximation

x Updating overall rnew value

Approximate square root


Initial Value r1= rnew

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

Figure 4-2 Calculation steps

4.4 Python program


Exercise 4-1 Creation and execution of a program to obtain square root

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)

Row Source code Notes


1 #␣Find␣the␣square␣root␣of␣x Lines starting with # are
2 x␣=␣2 comments
3 #
4 rnew␣=␣x
5 # Initial assumption for the
6 r1␣=␣rnew approximation
7 r2␣=␣x/r1
8 rnew␣=␣(r1␣+␣r2)/2
9 print(r1,␣rnew,␣r2)
10 #
11 r1␣=␣rnew
12 r2␣=␣x/r1 The code below this section
13 rnew␣=␣(r1␣+␣r2)/2 simply repeats the red
14 print(r1,␣rnew,␣r2) portion 3 times.
15 #
16 r1␣=␣rnew
17 r2␣=␣x/r1
18 rnew␣=␣(r1␣+␣r2)/2
19 print(r1,␣rnew,␣r2)
20 #
21 r1␣=␣rnew
22 r2␣=␣x/r1
23 rnew␣=␣(r1␣+␣r2)/2
24 print(r1,␣rnew,␣r2)

If you obtain the following result, the program ran as expected.


2 1.5 1.0
1.5 1.4166666666666665 1.3333333333333333
1.4166666666666665 1.4142156862745097 1.411764705882353
1.4142156862745097 1.4142135623746899 1.41421143847487

With 4 repetitions, you will obtain the result of 1.4142135623746899.


If you calculate the root by using
2**(1/2)
you will get
1.4142135623730951
Note that the result of the program is accurate to the 11th digit after the decimal point.
An intuitive explanation of this approximation method is given above, however this is simply an
application of what is known as Newton’s method to solving for square roots. For more details,
reference the column titled “Newton’s Method.”

62
4 Exercise: Find the Square Root Next Chapter Table of Contents

Exercise 4-2 Experience errors (1)

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.

4.5 Be careful when using division


In programs, you will frequently run into situations where a variable is used as a divisor. Among the
four basic arithmetic operations, division has the unique feature in which it cannot work if 0 is used
as the divisor. When programming, be constantly mindful of whether or not the divisor in a division
problem will be 0.

4.6 Notation to make equations easy to read


From the 8th line of p3-1.py, the equation
rnew = (r1 + r2)/2
uses the assignment operator (=), addition (+), division (/), and () which determine operation priority.
 Note that spaces are placed before and after = and + in order to make the equation easier to
read.
 On the other hand, spaces are not placed directly within the () or on either side of the /.
Removing all of the spaces yields
rnew=(r1+r2)/2
which looks pretty cramped and is difficult to read.
 A general principle to follow would be to forego spaces before and after high priority operations
like * and /, while adding spaces before and after low priority operation like +, -, and =.

63
5 Lists Next Chapter Table of Contents

5. Lists

5.1 Learning goals of this chapter


Until now, we’ve dealt with simple numbers and simple strings. In Python, there are multiple ways to
handle batches of data all at once. Lists are one of these methods. In this chapter, you will learn the
following things about using lists in Python.
1. What is a list?
2. How is a list created?
3. Learn how to access the elements of a list.
4. Learn about assigning and copying lists
5. Learn the basics about tuples and dictionaries, which are alternative ways to handle a bunch of
data all at once.

5.2 Learning with the Python shell


This chapter is going to have a lot of short code. Rather than inputting it into the editor and running
it, you can learn more efficiently by inputting it into the Python shell and seeing what it does.
 Because the Python shell processes code line-by-line, you cannot just copy and paste multiple
lines into the shell and run them. Instead, input code one line at a time.
In order to limit the number of pages in this text, input will be printed in red font and output will
be printed in blue font below. Although the Python shell prompt is omitted, please proceed by
inputting the red text and confirming that it results in the outputted blue text.

5.3 What is a list?


In everyday life, if you mention a “shopping list,” this refers to a short memo containing a list of
items you intend to buy. In a similar manner, a Python list is a way for multiple pieces of data to be
handled all at once. By ascribing multiple pieces of data, a set order, you are able to handle them as a
single entity. For example, inputting
a = [5, 1, 3, 4]
and then
print(a)
prints the entire list.
[5, 1, 3, 4]
Inputting

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

5.4 Generating lists

Generation by specifying elements


Lists are generated by enclosing the elements within [] and separating them using “,” like this:
a = [5, 1, 3, 4]
Or this:
b = ['Sanjyo', 'Shijyo', 'Gojyo', 'Shichijyo']
As you can see, strings can be used as elements of a list. Also, variables and equations can be
included as elements of a list.
c = 5
a = [c, 1, 3, 4]
a
[5, 1, 3, 4]
A long list of the same elements can be made by multiplication of list and an integer:
a = [1]*4
a
[1, 1, 1, 1]
However, it should be noted that if the element in the list is a complex objects like a list,
multiplication makes not make a list of copies of the element but just a list of the identical elements.

Combining with the range() function


An empty list can be generated as an object of the list class like so:
e = list()
You can combine this with the range() function, which generates a series of numbers, like so:
n = list(range(5))

65
5 Lists Next Chapter Table of Contents

Printing this list using


print(n)
will show a list of numbers from 0 to 4.
[0, 1, 2, 3, 4]

Generating lists from strings


It is possible to generate lists using strings instead of the range() function. Inputting
s = list('abcde')
and then
print(s)
Printing this list using
['a', 'b', 'c', 'd', 'e']
As you can see, you get a list containing the string ‘abcde’ split up into individual letters.
The string class contains a method called split() which can split a string into smaller segments using
a specified character to delimit the breaks 1. For example, inputting
t = "a textbook of Python"
tlist = t.split()
Printing this list using
print(tlist)
yields
['a', 'textbook', 'of', 'Python']
which is a word list generated by using spaces as the delimiter.

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

5.6 Accessing elements in a list


Elements of a list can be accessed by including the element’s index within [].
a = [5, 1, 3, 4]
print(a[0])
yields
5
Then, by inputting
a[1] = 2
print(a)
2 is assigned to the second slot (index 1) of a, yielding
[5, 2, 3, 4]

The length of a list can be obtained using the len() function.


print(len(a))
yields
4
Please note that this is a function, not a method that can be called by “a.len()”

5.7 Negative indices and slicing


Python allows for list indices to be described in a wide variety of ways.

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]

5.8 Adding to and combining lists


Lists come with various predetermined methods 1. In this section, we will introduce the append()
method, which adds elements to a list, and the extend() method, which combines multiple lists
together.

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]]

5.9 List assignment and duplication


First, try running the following program:
a = [1, 2, 3]
b = a
print(a)
print(b)
This should result in the following output:
[1, 2, 3]
[1, 2, 3]
Next, try to predict what the result will be from running a program like the one below.
b[0] = 0
a[1] = 0
print(a)
print(b)
This does not result in

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

Figure 5-1 List assignment

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.

Figure 5-2 Copying and assigning lists

5.10 Mutable and immutable objects


Everyone should now be able to correctly predict how a program with the following code will
behave.
a = 1
b = a
b = 2
71
5 Lists Next Chapter Table of Contents

print(a, b)
An important concept regarding data management in Python is the idea of mutable versus
immutable objects.

Numbers and strings are immutable (unchangeable)


objects
In Python, numbers and strings are what are known as immutable objects. This means that in the
third line of the program above, b = 2 does not overwrite the data (with a value of 1) currently
referenced by b. Rather, it creates an entire separate entity containing the data “2” and assigns the
location of this data to b. You can examine their locations in memory using the code below.
a = 1
b = a
print(id(a), id(b))
b = 2
print(id(a), id(b))
Running this gives the following:
>>> a = 1
>>> b = a
>>> print(id(a), id(b))
1434938848 1434938848
>>> b = 2
>>> print(id(a), id(b))
1434938848 1434938880

As you can see, a and b refer to the same location in line 3. However, by line 5 they refer to different
locations.

Lists are mutable objects


On the other hand, lists are mutable objects whose element can be changed. Because of this, when
there are two variables (a and b) containing references to the same list, any changes to the elements
of either of these variables will affect the other.

5.11 Shallow and deep copying


Unfortunately, there are additional issues to consider when using lists. What does variable b refer to
in the following program?
a = [[1, 2], [3, 4]]

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.

5.12 Visualizing lists


There is a website called Python Tutor (http://www.pythontutor.com) where you can input short
Python programs and see their behavior (variable usage) visualized. An example can be seen below.
Using it to see how lists behave can serve to greatly aid your understanding.

73
5 Lists Next Chapter Table of Contents

Figure 5-3 Checking how lists behave with Python Tutor

5.13 Keeping Calculation Results in a List


On calculation of square root studied in the previous chapter(p3-1.py), rewrite the
program so as to keep calculation process in a list.

Program 5-1, Keeping calculation process in a list (p5-1.py)

Row Source code Notes


1 #␣Find␣the␣square␣root␣of␣x Lines starting with # are
2 x␣=␣2 comments
3 #
4 rnew␣=␣x
5 rnew_list = [rnew] Create a list with rnew as
6 # an element
7 r1␣=␣rnew
8 r2␣=␣x/r1
9 rnew␣=␣(r1␣+␣r2)/2
10 print(r1,␣rnew,␣r2)
11 rnew_list.append(rnew)
12 # The code below this section
13 r1␣=␣rnew simply repeats the above 3
14 r2␣=␣x/r1 times.
15 rnew␣=␣(r1␣+␣r2)/2
16 print(r1,␣rnew,␣r2)
17 rnew_list.append(rnew)
18 #
19 r1␣=␣rnew
20 r2␣=␣x/r1

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

Exercise 5-1 Store calculation process in a list


Write Program 5-1 and execute it. After execution, examine the length and elements of rnew_list
with Python Shell.

Exercise 5-2 Store estimated accuracy in a 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.

5.14 Tuples and dictionaries


Aside from lists, two ways you can handle large amounts of data all at once in Python is by using
tuples and dictionaries.

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.

Notation for lists, tuples, and dictionaries


Lists, tuples, and dictionaries all use different types of brackets. The correct notation for each type
can be seen in the table below.

Table 5-1 Notation for lists, tuples, and dictionaries

Data type Brackets Example Accessing Mutable/


used elements Immutable
Lists [ ] d = [0, 1, 2] d[0] Mutable
Tuples ( ) d = (0, 1, 2) d[0] Immutable
Dictionaries { } d = {"a":1, "b":2, "c":3} d["a"] Mutable

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.

6.2 Repeated processing using for-loops


One of the main objectives of programming is to have computers automatically do things that are
difficult and/or repetitive for people to do by hand. for-loops are an important method for
programming the repetitive parts. Those of you who are familiar with C will notice Python's 'for'
statement has a slightly different syntax, but it is easier to use because you can easily write iterations
over elements of a list.

Performing a fixed number of repetitions using a for-


loop and the range() function
The times that computers can show their true might through programming is when they are able to
perform a lot of processing at a very high speed. However, using sequential execution learned in the
Chapter 3, you need to write each and every step that the computer executes. Program 4-1 for solving
square roots in Chapter 4 repeated the exact same code four times. Here you will learn how to use a
for-loop with the range() function to automate these repetitions.

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)

Row Source code Notes


1 #␣Find␣the␣square␣root␣of␣x Lines starting with # are comments
2 x␣=␣2
3 #
4 rnew␣=␣x
5 #
6 for␣i␣in␣range(10): Repeats the code below while iterating i from
7 ␣␣␣␣r1␣=␣rnew 0 to 9. Note the colon at the end of line 6.
8 ␣␣␣␣r2␣=␣x/r1 In Python, the repeated portion (block) is
9 ␣␣␣␣rnew␣=␣(r1␣+␣r2)/2 indented (the recommended amount is 4
10 ␣␣␣␣print(r1,␣rnew,␣r2) spaces).

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.

Exercise 6-2 Checking the block


Unindent line 10 from the block in the previous example (p6-1.py) as shown below. Check and
explain how the program behaves.

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)

Row Source code Notes


1 #␣Find␣the␣square␣root␣of␣x Lines starting with # are comments
2 x␣=␣2
3 #
4 rnew␣=␣x
5 #
6 for␣i␣in␣range(10):
7 ␣␣␣␣r1␣=␣rnew
8 ␣␣␣␣r2␣=␣x/r1
9 ␣␣␣␣rnew␣=␣(r1␣+␣r2)/2
10 print(r1,␣rnew,␣r2) Unindent this line from the block

Exercise 6-3 Prank


The repeated portion in the program above (p6-2.py) can be run very quickly because the part that
outputs to the terminal has been removed from the for-loop. Change the index of the range() function
on line 6 from 10 to 100, 1000, 10000, 100000, 1000000, and 10000000 to see how long it takes to
run. 1 6F7 F

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.

Exercise 6-4 Experience errors (2)


Statements such as 'for' statement that require a succeeding block have to end with a colon ":".
1 Modern personal computers clock in at the GHz level. At one instruction per clock cycle, this leads to extremely fast processing.
However, Python takes longer to process than most programming languages due to the fact that it is run via intermediate
representation.

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

Exercise 6-5 Experience errors (3)


In Program 6-1, lines 7 through 10 belong to a same block with a same indentation (four spaces).
Examine what will happen if you put less spaces (e.g., three spaces) or more spaces (e.g., five
spaces) in line 7, and run the program. See also "19 Appendix: How to Read Error Messages in
IDLE/Python."

Controlling the processing within a for-loop


‘Break’ and ‘continue’ statements can be used within for-loops in order to abort processing or to skip
processing at a specific repetition.
 break: Breaks out from the for-loop
 continue: Skips the remaining code in the block of the for-loop and continues to the next
iteration of the loop.
These statements are used in conjunction with 'if' statements, which enable conditional branching
and will be introduced later.

Program 6-3 continue and break (p6-3.py)

Row Source code Notes


1 for␣i␣in␣range(10):
2 ␣␣␣␣if␣i␣==␣1: Move to the next iteration
3 ␣␣␣␣␣␣␣␣continue if i is 1
4 ␣␣␣␣if␣i==␣8: Break from the loop if i is
5 ␣␣␣␣␣␣␣␣break 8
6 ␣␣␣␣print(i)

This program results in the output shown below.


0
2
3
4
5
6
7

Exercise 6-6 Explanation of continue and break


Explain the output seen above using the source code.

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)

Exercise 6-7 range() function


Practice the three usages of the range() function in the Python shell using list() as shown above.

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.

Program 6-4 Calculating sum (p6-4.py)

Row Source code Notes


1 sum␣=␣0 Sets sum to 0
2 for␣i␣in␣range(10): i goes from 0 to 9
3 ␣␣␣␣sum␣=␣sum␣+␣i adds i to the sum
4 print(sum) displays the sum

82
6 Control Flow Next Chapter Table of Contents

Exercise 6-8 Calculation of sum


Try running Program 5-4. Also, try changing the scope of the sum. Line 3 can also be written as sum
+= i. Try this out for yourself.

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,

Program 6-5 Nested for-loops (p6-5.py)

Row Source code Notes


1 for␣i␣in␣range(3):
2 ␣␣␣␣for␣j␣in␣range(3):
3 ␣␣␣␣␣␣␣␣print(i,j)
Running the code above yields the following output:
0 0
0 1
0 2
1 0
1 1
1 2
2 0
2 1
2 2
Please note that the target variable for the inner for-loop is different than that of the outer for-loop.

Exercise 6-9 Nested for-loops


Try and find out what happens when the variable i is used as the argument for the range() function
(change it to range(i)) in line 2.

Using for-loops to manage lists

1) How to combine list length with the range function


The elements of a list can be accessed in order with a for-loop by using range(len(a)) to generate

83
6 Control Flow Next Chapter Table of Contents

each element. For example:


a = [5, 1, 3, 4]
for i in range(len(a)):
print(i, a[i])
yields
0 5
1 1
2 3
3 4

2) How to directly use lists with a for-loop


If you simply desire to reference the element values, the code below would also suffice.
a = [5, 1, 3, 4]
for d in a:
print(d)
yields
5
1
3
4
In this case, the contents of the elements are passed to d, so changing d does not change the list’s
contents. When you wish to update the elements of a list, you can access them using their index.

3) How to use the enumerate function


The enumerate function is used in cases where you want to use both the index of an element and its
value.
a = [5, 1, 3, 4]
for i, d in enumerate(a):
print(i, d)
0 5
1 1
2 3
3 4
84
6 Control Flow Next Chapter Table of Contents

Exercise 6-10 Solving for averages


To solve for the average value of a list whose elements are numbers, you could use the following
code:
a = [5, 1, 3, 4]
sum = 0
for i in range(len(a)):
sum += a[i]
average = sum/len(a)
print(average)
The result of this code is:
3.25

Exercise 6-11 Change access to list elements


Rewrite the above program in a manner such that it uses a for-loop to use the list directly.

List comprehension using for-loops


Consider a list of numbers risen to the second power.
[0, 1, 4, 9, 16]
You can make this by explicitly writing it out, as done above, or you could use the following code:
a = []
for i in range(5):
a.append(i*i)
In addition, Python has another way to do this, called list comprehension, that entails including a for
-loop within the list.
a = [i*i for i in range(5)]

6.3 Repetition using while-loops

Calculating the square root with specified accuracy


Let’s try calculating square roots to a set level of accuracy. Because r1 and r2 lie on opposite sides of
the true value, the absolute value of the difference between them, |r1 - r2|, can be taken to be the

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)

Row Source code Notes


1 #␣Find␣the␣square␣root␣of␣x
2 x␣=␣2
3 #
4 rnew␣=␣x
5 #
6 diff␣=␣rnew␣-␣x/rnew Takes the difference between the two
7 if␣diff␣<␣0: approximations (x and 1 (=x/x))
8 ␣␣␣␣diff␣=␣-diff Changes the sign if negative
9 while␣(diff␣>␣1.0E-6): Repeats if the difference is larger
10 ␣␣␣␣r1␣=␣rnew than 10-6
11 ␣␣␣␣r2␣=␣x/r1
12 ␣␣␣␣rnew␣=␣(r1␣+␣r2)/2
13 ␣␣␣␣print(r1,␣rnew,␣r2)
14 ␣␣␣␣diff␣=␣r1␣-␣r2
15 ␣␣␣␣if␣diff␣<␣0: Recalculates the difference
16 ␣␣␣␣␣␣␣␣diff␣=␣-diff

Exercise 6-12 Write and run Program 6-6

Running the program should yield the following result:


2 1.5 1.0
1.5 1.4166666666666665 1.3333333333333333
1.4166666666666665 1.4142156862745097 1.411764705882353
1.4142156862745097 1.4142135623746899 1.41421143847487
1.4142135623746899 1.414213562373095 1.4142135623715002

Calculating the square root with an infinite loop


A program that solves for square roots using an infinite loop is shown in Program 6-7. It calculates
accuracy and uses an 'if' statement to determine whether or not to exit the loop via a ‘break’
statement. This program differs from p6-6.py in two ways.
 An end condition is not specified at the beginning of the loop.

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)

Row Source code Notes


1 #␣Find␣the␣square␣root␣of␣x
2 x␣=␣2
3 #
4 rnew␣=␣x
5 #
6 while␣True: Infinite loop repetition
7 ␣␣␣␣r1␣=␣rnew
8 ␣␣␣␣r2␣=␣x/r1
9 ␣␣␣␣rnew␣=␣(r1␣+␣r2)/2
10 ␣␣␣␣print(r1,␣rnew,␣r2)
11 ␣␣␣␣diff␣=␣r1␣-␣r2
12 ␣␣␣␣if␣diff␣<␣0:
13 ␣␣␣␣␣␣␣␣diff␣=␣-diff
14 ␣␣␣␣if␣diff␣<=␣1.0E-6: break if the absolute value
15 ␣␣␣␣␣␣␣␣break of the difference is less
than or equal to 10-6

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.

6.4 Branching using 'if' statements

Structure of an 'if' statement


'if' statements can be used in a few different ways. The most basic is to execute a block of code if the
condition in the 'if' statement is met. In addition to this, you can include a block of code to execute if
the condition is not met (else), and you can even include yet another condition to evaluate if the
initial condition is not met (elif, meaning else if).
if conditional expression:
Block to be executed if the condition is true

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.

How to write conditional expressions

1) Comparing numerical values


Perhaps the most common condition is a comparison of numerical values. The operators that can be
used to compare numerical values can be seen in the table below.

88
6 Control Flow Next Chapter Table of Contents

Table 6-1 Comparison operators in Python

Operator Meaning Notes


== Equivalent Two equals signs. This is to
differentiate it from the
assignment operator, which is a
single equals sign.
!= Not equivalent 2 characters
> Greater than
< Less than
>= Greater than or equal to 2 characters
<= Less than or equal to 2 characters

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.

4) Prioritizing operations with ()


Python has a defined order of operations:
 Arithmetic operations are prioritized over comparison operations
 Comparison operations are prioritized over logical operations
It is good practice to use () in order to make your programs easier to read by explicitly stating the
order of operations. For example:
a == 1 and b != 0
The code above behaves exactly the same as the code below, but the latter is easier to read.

89
6 Control Flow Next Chapter Table of Contents

(a == 1) and (b != 0)

Nested 'if' statements


Just like how 'for' statements are often nested within other 'for' statements, 'if' statements are also
frequently used in this manner. The following two programs make the same determinations but are
written in different ways.

Program 6-8 Forking using multiple conditions (p6-8.py)

Row Source code Notes


1 a␣=␣1
2 b␣=␣0
3 if␣(a␣==␣1)␣and␣(b␣==␣0): Forking with multiple
4 ␣␣␣␣print("YES␣a==1␣and␣b␣==␣0") conditions

Program 6-9 Forking with nested 'if' statements (p6-9.py)

Row Source code Notes


1 a␣=␣1
2 b␣=␣0
3 if␣a␣==␣1: Forking with nested "if"
4 ␣␣␣␣if␣b==0: statements
5 ␣␣␣␣␣␣␣␣print("YES␣a==1␣and␣b␣==␣0")

Exercise 6-13 Experience errors (4).


It is a common mistake of writing an assignment operator "=" instead of the comparison operator
"==" in a "if" statement. Examine what will happen if you write "if a = 1: " in the third line of
Program 6-9 and run it. See also "19 Appendix: How to Read Error Messages in IDLE/Python."

6.5 Termination of the Python program


Python programs terminate upon executing the final row, but one can use the exit() function from
the sys module in the manner seen below if one wishes to end a program partway through. One can
return a termination code to the location that called the program by passing an argument through the
exit function. Generally, a value of 0 is used for normal termination and other values are used for
abnormal termination. The function defaults to 0 if no argument is specified.
It is worth noting that the exit() function called without the module stops execution in the Python
shell.

90
6 Control Flow Next Chapter Table of Contents

Program 6-10 Termination of the Python program (p6-10.py)

Row Source Code Notes


1 import sys import sys module
2 for i in range(5):
3 ␣␣␣␣print(i)
4 ␣␣␣␣if i==3: If i is 3, terminate
5 ␣␣␣␣␣␣␣␣sys.exit() program using
6 print("end") sys.exit()
Executing this gives the result below. One can see that the program terminates when i is 3.
0
1
2
3

6.6 Input from the terminal


So far, we’ve built the number whose square root we want to find into the program itself. Let’s
consider adding input from the terminal. Below is the Python shell screen. Red text is input, and blue
text is output.
Python shell screen Notes
>>> a = input("*** ") Change the input prompt string to “***”
and then accept input via the input
*** sss function and assign it to a
>>> a Input sss
Evaluate a
'sss'
>>> type(a)
Retrieves the data type of a using the
<class 'str'> type function
>>>
Displays that a is a string (str)
The argument of the input function (the string within the parentheses) is the string that will be
displayed. The function’s return value (the result of the function call) is a string.
In order to obtain numerical data, convert it to the appropriate type using int() or float().
In the square root program from before, change the part that sets the value of x to
x = input("Find the square root of ")
x = float(x)
You could even write this in one line like so:
x = float(input("Find the square root of "))
This enables you to store the numerical value input into the terminal within the variable x.

91
6 Control Flow Next Chapter Table of Contents

Exercise 6-14 Input number form terminal


Modify p6-6.py so that it solves for the square root of the number input through the terminal.
Open p6-6.py or p6-7.py and select Save As in the File menu to create a new program named e.g.,
p6-6-1.py or p6-7-1.py.

6.7 Handling errors


When something that cannot be interpreted as a number is passed through the float() or int()
functions as an argument, it results in a ValueError. If you have not specified what should be done in
such a case, Python will suspend processing of the program at this point. You can make use of a 'try'
statement to deal with errors that may arise in a program.
The following program continuously accepts input and handles errors in order to only output
(print(x)) positive numbers. This program contains an infinite loop that lacks an explicit stoppage
condition. Input Ctrl-C to stop the program.

Program 6-11 Program that checks user input (input_check.py)

Row Source code Notes


1 while␣True: Infinite loop
2 ␣␣␣␣x␣=␣input("Enter positive number␣")
3 ␣␣␣␣try: Put the part that can give an
4 ␣␣␣␣␣␣␣␣x␣=␣float(x) error within the try block
5 ␣␣␣␣except␣ValueError: Handles a ValueError
6 ␣␣␣␣␣␣␣␣print(x,␣"can't be converted to a Make sure to capitalize
number") letters when appropriate
7 ␣␣␣␣␣␣␣␣continue Handles other errors
8 ␣␣␣␣except:
9 ␣␣␣␣␣␣␣␣print("Unecpected error") Ends the program. This is the
10 ␣␣␣␣␣␣␣␣exit() end of the try block.
11 ␣␣␣␣if␣x␣<=0: Checks whether the input is
12 ␣␣␣␣␣␣␣␣print(x,␣"is not positive") positive
13 ␣␣␣␣␣␣␣␣continue Continuation of the while-
14 #␣Below␣is␣the␣result␣of␣receiving␣a␣proper␣input loop
15 ␣␣␣␣print(x)

Exercise 6-15 Reviewing Error Handling


Run the above program and see how it responds after receiving various inputs.

Structure of a 'try' statement


Blocks that can generate exceptions are put within 'try' statements, and specified exceptions are
placed within 'except' statements with a corresponding block. An 'except' statement that does not
specify an exception type will activate for any exception that is encountered (except for exceptions

92
6 Control Flow Next Chapter Table of Contents

specified above it).


try:
Block which will require exception handling
except exception:
Block to be processed when the specified exception occurs
except:
Block designed to handle all exceptions besides the ones specified above it

Always be suspicious of external input


The programmer cannot control the external input that they receive. Programs that are only written to
be able to handle anticipated input are often unable to properly handle unexpected input. This often
leads to incorrect results. It is very important that you always distrust external input. You should
ideally always check its validity and include appropriate contingencies for any potential errors that
can arise from unanticipated input.

6.8 Mathematical functions in Python


In the examples thus far, I’ve been explicitly calculating the absolute value of the calculation error
diff by changing the sign if the number is negative, like so:
if diff < 0:
diff = -diff
Python is equipped with an absolute value function, so this can be written in just one line:
diff = abs(diff)

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

Exercise 6-16 Use of math module


Mimic the examples above and play around with the math module yourself within the Python shell.

6.9 Converting numbers and strings; Combining


strings
We have used the input() function to obtain a string followed by the int() or float() functions to
convert the string to a number. Additionally, you can also use the str() function to convert numerical
data to a string. The format() method, which will be explained below, can be used in cases when you
wish to specify the format. These conversion methods are summarized in the table below.

Table 6-2 Conversions between numbers and strings

Conversion Function Example Notes


String to Integer int() a = int("123") An improper string will result
in a ValueError
String to Floating- float() a = Same as above
point number float("123.4")
Integer / Floating- str() s = str(123.4) str() can also convert lists
point number to String and other various types of
objects into strings as well.
It is worth noting that numerical values and any other non-string values passed to the print function
are automatically converted into strings.
Strings can be connected by using the “+” operator. In addition, strings can be repeated by using the
“*” operator in conjunction with an integer. Also, you can combine a number with a string by using
the “+” operator and the str() function.

Table 6-3 Connecting and repeating strings

Operation Operator Example Result


Connecting strings + "abc" + "def" "abcdef"
Connecting strings and numbers "abc"+str(1.2) "abc1.2"
Repeating strings * "abc"*2 "abcabc"

6.10 Format specification when displaying a number


When Python’s print() function displays a numerical value, a number of digits that matches the
number is automatically selected. It is possible for the user to specify both the number of digits and
the format with which the number is displayed. A concrete example can be seen below:
c = 2.99792458E8

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

executing the above code, we obtain:

94
6 Control Flow Next Chapter Table of Contents

light speed is 2.9979246e+08 m/s, Avogadro's number is 6.0221408e+23 mol**(-1)

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

7. Making Kyoto Intersections

7.1 Learning goals of this chapter


In this chapter, we will use 'for' statements and lists to practice. we will be going through an example
that deals with Kyoto’s intersections, which have a grid-like structure.

7.2 Creating Kyoto’s intersections


Play around with the following example, which uses 'for' statements to handle lists. Be careful if you
decide to write the street names in Japanese characters, as the code will then mix half-width and full-
width characters. Note that aside from place names, everything is written using half-width characters
(including spaces).

Program 7-1 Making Kyoto intersections (p7-1.py)

Row Source code Notes


1 tozai␣=␣["Sanjyo",␣"Shijyo",␣"Gojyo"] Only the text in red font
2 nanboku␣=␣["Horikawa",␣"Karasuma",␣"Kawaramachi"] uses full-width characters
3 for␣i␣in␣tozai:
4 ␣␣␣␣for␣j␣in␣nanboku:
5 ␣␣␣␣␣␣␣␣cross␣=␣i+j Concatenate strings using the
6 ␣␣␣␣␣␣␣␣print(cross) + operation

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.

This will give the following result 1 7F8 F

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 ‘”三
条.’

7.3 List of lists and how to scan them


Lists in Python can actually contain lists as elements. This fact can be used to create a data

97
7 Making Kyoto Intersections Next Chapter Table of Contents

structure resembling a table.


a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Inserting line breaks to make this easier to read yields the following 1.
a = [[1, 2, 3],
[4, 5, 6],
[7, 8, 9]]
Display all of list a
print(a)
[[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Display the first element of a (the element is a list).
print(a[0])
[1, 2, 3]
Display index 1 of the first element of a.
print(a[0][1])
2
When tabular data is represented as a list of lists, referencing every element can be achieved through
nested 'for' statements. There are multiple ways to do this.

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

Handling the list directly with 'for' statements


For this example, we will only be referencing the values of the elements, so the code can be written
in the manner shown below. The target variable for the 'for' statement is the list itself this time rather

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)

Creating a table of Kyoto intersections


Exercise 7-1 Creating a table of Kyoto intersections
Use Program 7-1 as a reference to create the table below as a list of lists.
cross_table =[["SanjyoKawaramachi", "SanjyoKarasuma", "SanjyoHorikawa"],
["ShijyoKawaramachi", "ShijyoKarasuma", "ShijyoHorikawa"],
["GojyoKawaramachi", "GojyoKarasuma", "GojyoHorikawa"]]
This program can be written in a few different ways. For example:
 Assign the null string "" to each element beforehand, create a list of lists containing the
necessary number of elements, and assign each intersection name to an element.

Program 7-2 Making a table of Kyoto intersections (p7-2.py)

Row Source code Notes


1 tozai␣=␣["Sanjyo",␣"Shijyo",␣"Gojyo"]
2 nanboku␣=␣["Horikawa",␣"Karasuma",␣"Kawaramachi"]
3 cross_table␣=␣[["","",""],␣["",␣"",␣""],␣["",␣"",␣""]] Creates a list of the
4 for␣i␣in␣range(len(tozai)): required size
5 ␣␣␣␣for␣j␣in␣range(len(nanboku)):
6 ␣␣␣␣␣␣␣␣cross␣=␣tozai[i]+nanboku[j] Generates intersection
7 ␣␣␣␣␣␣␣␣cross_table[i][j]␣=␣cross names
Assigns intersection
names

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.

Program 7-3 Making a table of Kyoto intersections (p7-3.py)

Row Source code Notes


1 tozai␣=␣["Sanjyo",␣"Shijyo",␣"Gojyo"]
2 nanboku␣=␣["Horikawa",␣"Karasuma",␣"Kawaramachi"]
3 cross_table␣=␣[]
4 for␣i␣in␣range(len(tozai)):
5 ␣␣␣␣street␣=␣[] List of streets
6 ␣␣␣␣for␣j␣in␣range(len(nanboku)):
7 ␣␣␣␣␣␣␣␣cross␣=␣tozai[i]+nanboku[j] Generates intersection names
8 ␣␣␣␣␣␣␣␣street.append(cross) Appends intersection to
9 ␣␣␣␣cross_table.append(street) streets
Appends list of streets to
table

Displaying the table of intersections

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:

print(street[i]) # Line break at the end


While still a bit advanced at this point, you can also pass the entire list to the print function all at
once using “*” and specify the delimiter character with the sep option.
street = ["SanjyoKawaramachi", "SanjyoKarasuma", "SanjyoHorikawa"]
print(*street, sep=", ")

Exercise 7-2 Outputting lists of lists


Create a program that outputs the list of lists of intersection names created in the example above in a
manner that conforms to the following conditions:
 Output the intersection names for one east-west street on one line.
 Insert “, ” (a half-width comma and a space) in between the intersection names starting with
the same east-west street. However, do not put a comma at the end of each line.
Specifically, the program must yield the following output:
SanjyoKawaramachi, SanjyoKarasuma, SanjyoHorikawa
ShijyoKawaramachi, ShijyoKarasuma, ShijyoHorikawa
GojyoKawaramachi, GojyoKarasuma, GojyoHorikawa

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.

8.2 Fine tuning the square root calculation


Exercise 8-1 Fine tuning the square root calculation

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.

Calculating Pi using the Leibnitz formula


Exercise 8-2 Calculating Pi using the Leibnitz formula

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

8.4 Generating a deck of cards

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.

Generating a deck of cards


Exercise 8-3 Generating a deck of cards

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

Program 8-1 Card deck generation (incomplete, p8-1.py)

Raw Source Code Notes


1 import random import radom number
2 suits = ["♠","♥","♦","♣"] module
3 ranks = List of suits
["A","2","3","4","5","6","7","8","9","10","J","Q","K"] List of values
4 cards = []
#␣Generate␣a␣card␣with␣a␣suit␣and␣value List to hold the
#␣and␣append␣to␣cards generated cards
5
6
7 cards.append("Joker")
8 print(cards) Add the joker
9 #␣Shuffle␣cards␣and␣assign␣it␣to␣deck print cards
10 deck =
11 print(deck)
12 print deck

Random sorting of the list components


In order to get a random sorting of the list components, we will import the random module and use a
function from it called sample. The first argument will be the list itself and the second argument will
be the number of list components we want to sort. For example, use

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

8.5 Intersections in Heian-kyō

Oji (main streets) in Heian-kyō


When the capital was moved to Heian-kyō in 794 A.D., it was made up of Oji (main streets) and Koji
(minor streets). A figure depicting only the Oji (main streets) can be seen below. 1 The Suzaku-Oji
street, which ran through the center of Heian-kyō from north to south, was around where the Senbon-
dori street currently is. Heian-kyō expanded further to the west when compared to the present day
Kyoto metropolitan area.

Figure 8-1 Comprehensive diagram of Heian-kyō


(generated by the writer from Reference [14]図一 1 (Figure 1-1))

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

Ichijo Oji,Tsuchimikado Oji,Konoe Oji,Nakamikado Oji,Oimikado Oji,


Nijo Oji,Sanjo Oji,Shijo Oji,Gojo Oji,Rokujo Oji,Shichijo Oji,
Hajchijo Oji,Kujo Oji

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

Generating Heian-kyō intersections


Exercise 8-4 Generating Heian-kyō intersections

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

 Tsuchimikado Kogamon,Tsuchimikado Suzaku,Tsuchimikado Mibu,


 Konoe Kogamon,Konoe Suzaku,Konoe Mibu,
 Nakamikado Kogamon,Nakamikado Suzaku,Nakamikado Mibu,
 Oimikado Kogamon,Oimikado Suzaku,Oimikado Mibu
 Those who have time should try running the prompt below in Anaconda.
python heiankyo.py > heiankyo.csv
However, make the program name heiankyo.py. By doing so, a file called heiankyo.csv should be
created. One can open excel by double clicking on this file. The ">" in the command above is a
feature of the Anaconda prompt (or more specifically the Windows command prompt) called redirect
that takes the output to the console and inputs it into a file called heiankyo.csv.

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

9. Encapsulation of Processing Using


Functions
9.1 Learning goals of this chapter
1. In this chapter, we will use the exercise from Chapter 5 to learn how to take a batch of
commands and define it as a function so that it can be used when needed.
2. Learn how to pass values as arguments to functions.
3. Learn how to return a value from a function when it is called.
4. Learn about variables used within functions and the scope within which they have influence.
5. Learn about some general situations in which functions tend to be used.
As with Chapter 5, there is a lot to learn in this chapter. However, you will be able to use the material
covered in this chapter in concrete examples throughout the rest of the text. As such, you don’t need
to worry about learning all the fine details right away. Simply focus on learning what you can do
with the concepts learned in this chapter as well as on building experience writing code using
these concepts. It is always possible to look back through the text to review the fine details as the
need arises.

9.2 Let’s make an absolute value function


As a simple exercise in defining functions, let’s create our own absolute value function like the one
we used in a previous chapter.

Program 9-1 Example of an absolute value function (p9-1.py)

Row Source code Notes


1 def␣myabs(x): Definition of the myabs function, the
2 ␣␣␣␣if␣x<0: argument is x
3 ␣␣␣␣␣␣␣␣x␣=␣-x Flips the sign if x is negative
4 ␣␣␣␣return␣x Returns x
5
6 while␣True: This is the main program (the part that runs
7 ␣␣␣␣a␣=␣float(input(">␣")) first when the program is executed)
8 ␣␣␣␣print(a,␣myabs(a)) Calls myabs with a as the argument

Program 9-2 Example of an absolute value function (p9-2.py, returns when possible)

Row Source code Notes


1 def␣myabs(x): Definition of the myabs function, the argument
2 ␣␣␣␣if␣x<0: is x
3 ␣␣␣␣␣␣␣␣return␣-x if x is negative, flip the sign and return
4 ␣␣␣␣return␣x Returns x
5

108
9 Encapsulation of Processing Using Functions Next Chapter Table of Contents

6 while␣True: This is the main program (the part that runs


7 ␣␣␣␣a␣=␣float(input(">␣")) first when the program is executed)
8 ␣␣␣␣print(a,␣myabs(a)) Calls myabs with a as the argument

Exercise 9-1 Create an absolute value function


Write Program 9-1 and Program 9-2 and confirm that they behave as expected.

Exercise 9-2 Experience errors (5).


In Program 9-1 and Program 9-2, function "myabs" assumes that the given parameter is numeral. If
you forget calling float() function in line 7 and write as "a = input("> "), the input data is assigned to
variable a as string. Examine what will happen in this case. See also "19 Appendix: How to Read
Error Messages in IDLE/Python."

9.3 Format for function definitions


The general format for function definitions is given below.
def function name(parameters):
Explanatory string
Block executed by the function
return value returned by the function
 Function names are governed by the same rules as variable names (referred to as identifiers). As
functions tend to be accompanied by specific actions, verbs are often chosen as function names.
 Parameters are the values that the function receives. They are written using the variable names
(parameters) with which they will be referred to within the function. When multiple parameters
are specified, they must be separated using “,” 1. 9F1 0F

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

9.4 Parameters and arguments


The parameters where the function is actually called are arguments or actual parameters, and the

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

Function call Function definition

Parameters

m = 10 def f(x, y):


n=5 z = x*y
k = f(m, n) return z

Arguments

m (evaluated value) x's contents


n (evaluated value) y's contents

Figure 9-1 Arguments and Parameters

9.5 Return values


The calculated result of a function is returned using a 'return' statement.
 As seen in Program 9-2, it is possible to include multiple 'return' statements within a function
definition. However, splitting the return among multiple possible statements can make editing
the function difficult.
 In Python, it is possible to return multiple values by separating them with commas. When
calling the function, multiple variables can be listed, separated by commas, to accept multiple
return values. If multiple return values are accepted with a single variable, this variable will
contain multiple return values and become a data type known as a tuple.

9.6 From an exercise in a prior chapter


In a prior chapter, you learned how to write a program to solve for square roots as well as how to
accept the number whose root it would solve as input from the terminal. Combining these concepts,
we dealt with the problem of writing a program that would continually ask for numbers from the
terminal and solve for the square root of the inputted numbers. Two potential ways to write a
program that continually asks for input from the terminal are explained below.

1 Lists can be overwritten.

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.

9.7 Let’s write the square_root() function


Let’s take p6-6.py, which solves for square roots, and turn it into the square_root() function.

Program 9-3 Implementation of the square_root() function (p9-3.py)

Row Source code Notes


1 #
2 def␣square_root(x): A function that takes a parameter x
3 ␣␣␣␣'Calculate square root of explanatory string (docstring)
argument x'

111
9 Encapsulation of Processing Using Functions Next Chapter Table of Contents

4 ␣␣␣␣rnew␣=␣x The function definition block extends


5 ␣␣␣␣# until line 17. As with p6-6.py, be
6 ␣␣␣␣diff␣=␣rnew␣-␣x/rnew careful of the indentation.
7 ␣␣␣␣if␣diff␣<␣0:
8 ␣␣␣␣␣␣␣␣diff␣=␣-diff
9 ␣␣␣␣while␣(diff␣>␣1.0E-6):
10 ␣␣␣␣␣␣␣␣r1␣=␣rnew
11 ␣␣␣␣␣␣␣␣r2␣=␣x/r1
12 ␣␣␣␣␣␣␣␣rnew␣=␣(r1␣+␣r2)/2
13 ␣␣␣␣␣␣␣␣print(r1,␣rnew,␣r2)
14 ␣␣␣␣␣␣␣␣diff␣=␣r1␣-␣r2
15 ␣␣␣␣␣␣␣␣if␣diff␣<␣0:
16 ␣␣␣␣␣␣␣␣␣␣␣␣diff␣=␣-diff
17 ␣␣␣␣return␣rnew 'return rnew,' returns the calculated
18 #␣Main␣program␣from␣here value
19 v␣=␣2
20 r␣=␣square_root(v)
21 print("Result is␣",␣r)

The result of running this program is shown below.


If you include an explanatory string (docstring) with a function definition in Python, you can display
this string by calling the help function and passing the name of the function as the argument.
2 1.5 1.0
1.5 1.4166666666666665 1.3333333333333333
1.4166666666666665 1.4142156862745097 1.411764705882353
1.4142156862745097 1.4142135623746899 1.41421143847487
1.4142135623746899 1.414213562373095 1.4142135623715002
Result is 1.414213562373095
>>> help(square_root)
Help on function square_root in module __main__:

square_root(x)
Calculate square root of argument x

>>>

Exercise 9-3 Create a function to solve squate root


Make a program that continually solves for square roots with the function square_root().

Exercise 9-4 Create a function to solve squate root (2nd)


Define the function get_positive_numeral(), and make program that continually solves for square
roots with it as well as the function squate_root().

9.8 Treatment of variables within functions


Python treats variables within functions in the following manner. Reference the column titled "

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.

a = 10 'a' and 'b' are global variables


b=0

def f(): The global variable 'a' can only be read


'b' declared as global
global b Function 'c' is a local variable
c = a*a definition Variables used with a global statement
b= c can be assigned

f() Main program


print(b, a)

Figure 9-2 Global variables and local variables

9.9 Common uses of functions


Unlike mathematical functions, there are multiple ways in which Python functions are commonly
used. The information supplied to the function within () is called the argument, and the value
returned by the function is called the return value.
 Pass an argument and use the return value. Similar to how mathematical functions are used.
y = math.fabs(-2.0)
 Pass no arguments and do not use a return value. Used to execute a fixed set of commands.
For example, turtle’s up() function seen in the next chapter

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

Pass an argument and


receive a return value b = f(y) f(x) Calculates return value
from argument

Figure 9-3 Common uses of functions

a=0 Global variable

def f(): Function that operates on


global a global variable
a = a+1

def g(x): Function that operates on the contents of


x[0] = 0 a list argument

f() Main program


print(a)
By calling this function, the contents of
b = [1,2,3] both the global variable and the list
g(b) argument change
print(b)

Figure 9-4 Function calls and “side effects”

114
9 Encapsulation of Processing Using Functions Next Chapter Table of Contents

9.10 Function calls and passing function objects


When executing a function defined by a 'def' statement, you write something like f() regardless of
whether or not the function has arguments. Regarding this, in later chapters, you will run into the
function that runs when the mouse is clicked in turtle graphics, or the function that runs when a
button is pressed in a GUI program within tkinter in which solely the function name is written. Using
this notation does not run the function on the spot, rather it enables you to pass the function in its
entirety as an object that can be executed later. In the example below, the function f is passed as an
argument to the function F, and f runs within F.
def f():
print("f says Hello")
# Function that takes a function as an parameter and runs it
def F(y):
print("In F, ", end="")
y()
# runs f
f()
f says Hello
# passes f to F and runs F
F(f)
In F, f says Hello

9.11 Default parameters and keyword parameters

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. Playing with Turtle


10.1 Learning goals of this chapter
1. Learn how to use modules in Python with Turtle.
2. Learn how to use class objects in Python with Turtle
3. Review what you have learned so far through making graphical works with Turtle.
Independently learn how to use the libraries necessary to make these graphical works.

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.

Where to put 'import' statements


'import' statements are normally all listed at the beginning of a program.

Importing a module by specifying its name


The math module provides access to mathematical functions. To import it, we write:
import math
In order to call functions and constants from the module, first write the module name, followed by a
dot. For example, to call the “pi” constant, we write:
math.pi
All modules typically follow this style.

Importing a module using a custom name


An alias is used when you want to refer to a module name in a shortened form. For example, the
module tkinter, which will be discussed later, is often abbreviated to tk, as follows:
import tkinter as tk
Then, you can use the alias tk to refer to the module in your code.

Importing elements from within a module


We will import functions from the turtle module used in this chapter simply by writing:
from turtle import *
This allows us to use all the functions in a module just by calling the function name. However, it is
dangerous to overuse this method, because you may lose track of which module the function or
variable belongs to. Reference the column titled " Namespaces."
117
10 Playing with Turtle Next Chapter Table of Contents

Be careful not to name programs with the same file


name as a module
When Python reads the import command, it searches beforehand in the folder containing the libraries
and other files for Python programs with the specified module name.
When this occurs, the current working folder is searched first, so if you create a file called turtle.py,
for example, it will be interpreted as a module file and an error will occur. Be careful not to create a
Python script in the working folder with the same name as a module.

10.3 Turtle — The time-honored turtle


Turtle graphics allows you to give commands to a turtle (robot) on the screen to move forward,
rotate, and such, as well as create a graphical representation of its trajectory.
LOGO, a programming language developed at the Massachusetts Institute of Technology (MIT), has
integrated graphics functionality which allows for the visualization of the movement of programs for
learning. One of the developers of LOGO, Seymour Papert (1928-2016), is famous for his efforts in
teaching children programming. He is quoted as saying:
In many schools today, the phrase "computer-aided instruction" means making the
computer teach the child. One might say the computer is being used to program the child.
In my vision, the child programs the computer and, in doing so, both acquires a sense of
mastery over a piece of the most modern and powerful technology and establishes an
intimate contact with some of the deepest ideas from science, from mathematics, and from
the art of intellectual model building.
- Seymour Papert [10], emphasis in bold by the author.
In Japan, a teacher named Mr. Totsuka created a program to process LOGO by himself, and taught it
in elementary schools[11]. Other child-friendly programming languages include Squeak (developed
by Alan Kay), and Scratch 1, which was developed at MIT. Squeak and Scratch also have turtle
11F12 F

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.

10.4 Python’s turtle module


 In Python, turtle graphics is provided as the turtle module.
 It is based on the tkinter GUI environment 2. 1 2F1 3F

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

10.5 Let’s try it out


Write the program in the table below and try running it.

Program 10-1 Turtle usage example


(p10-1.py, Do not save this program as turtle.py)

Row Source code Notes


1 from␣turtle␣import␣* Calls the functions defined in the turtle module.
2 forward(100)
3 left(90)
4 forward(100)
5 left(90)
6 forward(100)
7 left(90)
8 forward(100)
9 left(90)
10 done() End
The forward() function makes the turtle move forward, and the left() function makes the turtle move
left.
The turtle holds a pen, and when the pen is pressed down (which is the default setting), it marks the
path that the turtle takes when it moves.

Exercise 10-1 Draw a regular polygon with n faces


Complete the following program so that it draws a regular polygon with n faces.

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)

Row Source code Notes


1 from␣turtle␣import␣* Calls the functions defined in the turtle module.
2 n␣=␣5 Draw a regular pentagon
3 for␣i␣in␣range(n): Repeat n times

done() End

Exercise 10-2 How can you draw a 5-pointed star?


Hint: for regular polygons, the direction the turtle was facing changed so that after completing its
circuit, it had made a single revolution. What is needed to draw a 5-pointed star?

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

10.6 The major functions in the turtle module


The following functions are available. For more details, see
24.1. turtle — Turtle graphics
in the Python documentation.
 forward(d): Move the turtle forward by the specified distance d. fd(d) is the same function.
 back(d), bk(d), backward (d):Move the turtle backward
 right(a), rt(a): Turn the turtle right by a degrees
 left(a), lt(a) :Turn the turtle left by a degrees
 goto(x, y), setpos(x, y), setposition(x, y): Move the turtle to the coordinates x, y
 setheading(a): Set the orientation of the turtle to a degrees
 pendown(), pd(), down(): Pull the pen down (draw when moving)
 penup(), pu(), up(): Pull the pen up
 position(), pos(): Return the turtle’s current location as a two-dimensional vector. Two variables
are output as return values, as shown below.
x, y = pos()
 heading(): Return the turtle’s current orientation
 isdown(): Returns True if the pen is down, False if the pen is up.

Exercise 10-4 Categorize the above functions following the usages shown in Section
9.9.

10.7 Moving multiple turtles

Example program
Program 10-3 Moving multiple turtles (p10-3.py)

Row Source code Notes


1 from␣turtle␣import␣* Calls the functions defined in the turtle module.
2 t1␣=␣Turtle() Creates the first turtle t1
3 t2␣=␣Turtle() Creates the second turtle t2
4 t1.color('red') Sets the color of t1 to red
5 t2.color('blue') Sets the color of t2 to blue
6 for␣i␣in␣range(180):

121
10 Playing with Turtle Next Chapter Table of Contents

7 ␣␣␣␣t1.forward(5) Moves t1 forward 5 steps


8 ␣␣␣␣t2.forward(3) Moves t2 forward 3 steps
9 ␣␣␣␣t1.left(2) Turns each turtle left twice
10 ␣␣␣␣t2.left(2)
11 done() End

Using Class Objects


In this example, each turtle is created as an object of the Turtle class.
A turtle has a number of attributes, such as “location” (coordinates), “direction,” “pen up” or “pen
down,” and “pen color.” In order to program a turtle, you need to know these attributes and be able to
change them.
Objects with a class type are a good way to describe such operations. By using multiple turtles, you
will be able to understand the key points of using class objects.

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

2) 2) Manipulating the Turtle


The way to know the state of the turtle, or to change its state, is to call a “method.” Methods are
invoked by writing “.” followed by the method name (and arguments) of the object variable. Think
of it like a function call, except that an object is the target.
t1.forward(10)

3) 3) Determining the Turtle's Attributes


To find out an attribute of the turtle, call a method that returns the attribute, and assign the result to
an appropriate variable.
x, y = t1.pos()
This can also be written as follows
(x, y) = t1.pos()

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

10.8 Tips for creating your project

Responding to Mouse Clicks


Define a function to be executed when the mouse is clicked, and pass the defined function object to
the onscreenclick() function.

Program 10-4 Responding to mouse clicks in turtle graphics (p8-4.py)

Row Source code Notes


1 from␣turtle␣import␣*
2 def␣come(x,y): Defines a function to be executed when
3 ␣␣␣␣(xx,yy)␣=␣pos() the mouse is clicked, with the parameters
4 ␣␣␣␣newxy␣=␣((xx+x)/2,(yy+y)/2) being the position of the mouse cursor
5 ␣␣␣␣print(x,y) when clicked.
6 ␣␣␣␣goto(newxy) The function definition ends here.
7 onscreenclick(come) Set up the function to be called when the
8 done() mouse is clicked (note that there is no
() after "come").

Converting Coordinates to Angles


To find the angle from the x and y coordinates in a given direction, Python provides a function called
atan2 in the math module 1. The argument is the previous vertical coordinate. The return value is in
1 3F14 F

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

Using Random Numbers


Random motion is another interesting thing to visualize.
• To use random numbers in Python, use the random module.
• Refer to the column titled "Random Numbers."
• Here is an example of turtle graphics using random numbers (see random_turtle.py for more
details).
• The turtle is stopped by a mouse click.

Figure 10-1 A result of executing random_turtle.py

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

Figure 10-2 A result of executing turtle-tree.py

Defining the shape of a turtle

1) The tortoise and the hare 1


The former Toyosato Elementary School building in Shiga Prefecture is famous due to William
Merrell Vories’ architecture, but a little known fact is that one can find a tortoise and hare engraved
into the banisters.

Figure 10-3 Former Toyosato Elementary School building and banister


(10/16/2016 Kita Photography)

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.

2) Example hare and card suits


By default, one has access to six shapes in Turtle Graphics: arrow, "turtle", "circle", "square",
"triangle", and "classic". One can register additional shapes by using the register_shape method seen
on the screen. In order to define the shape, one must supply a name and a tuple of x and y
coordinates that make up the outline of the shape. One can get the screen by using the getscreen

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

function. An example of a hare can be seen below.

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)

Program 10-5 Defining the shape of a turtle (p10-5.py)

Row Source Code Notes


1 #
2 #␣Output␣various␣turtle␣shapes
3 #
4 from␣turtle␣import␣*
5 #␣hide␣default␣turtle
6 ht()
7 #␣ Define␣a␣hare␣shape␣consisting␣of␣tuples␣with␣(x,␣y)␣coordinates
8 #␣rabbit␣shape␣data
9 rdata␣=␣((0,␣16),␣(-2,␣14),␣(-3,␣11),␣(-3,␣6),␣(-2,␣5),␣(-2,␣7),
10 ␣␣␣␣␣␣␣␣␣(-1,␣10),␣(-2,␣7),␣(-2,␣5),␣(-3,␣6),␣(-3,␣10),␣(-4,13),
11 ␣␣␣␣␣␣␣␣␣(-5,␣13),␣(-4,␣2),(-5,␣-10),␣(-4,␣-10),␣(-3,␣-4),
12 ␣␣␣␣␣␣␣␣␣(0,␣-5),␣␣(3,␣-4),␣(4,␣-10),␣(5,␣-10),␣(4,␣2),␣(5,␣13),
13 ␣␣␣␣␣␣␣␣␣(4,␣13),␣(3,␣10),␣(3,␣6),␣(2,␣5),␣(2,␣7),␣(1,␣10),
14 ␣␣␣␣␣␣␣␣␣(2,␣7),␣(2,␣5),␣(3,␣6),␣(3,␣11),␣(2,␣14))
15 #␣␣Register␣it␣under␣the␣name␣"rabbit"
16 getscreen().register_shape("rabbit",␣rdata)
17 #␣ Define␣card␣suit␣shapes
18 d␣=␣((0,␣16),␣(10,␣0),␣(0,␣-16),␣(-10,␣0),␣(0,␣16))
19 h␣=␣((0,␣6),␣(2,␣8),␣(4,␣9),␣(8,␣9),␣(10,␣8),␣(12,␣6),␣(13,␣4),
20 ␣␣␣␣␣(13,␣0),␣(12,␣-2),␣(11,␣-3),␣(0,␣-16),␣(-11,␣-3),␣(-12,␣-2),
21 ␣␣␣␣␣(-13,␣0),␣(-13,␣4),␣(-12,␣6),␣(-10,␣8),␣(-8,␣9),␣(-4,␣9),
22 ␣␣␣␣␣(-2,␣8),␣(0,␣6))
23 s␣=␣((0,␣16),␣(10,␣4),␣(12,␣2),␣(13,␣-2),␣(12,␣-6),␣(10,␣-8),
24 ␣␣␣␣␣(8,␣-9),␣(4,␣-9),␣(1,␣-8),␣(3,␣-16),␣(0,␣-16),␣(-3,␣-16),
25 ␣␣␣␣␣(-1,␣-8),␣(-4,␣-9),␣(-8,␣-9),␣(-10,␣-8),␣(-12,␣-6),␣(-13,␣-2),
26 ␣␣␣␣␣(-12,␣2),␣(-10,␣4),␣(0,␣16))
27 c␣=␣((0,␣16),␣(4,␣15),␣(6,␣13),␣(7,␣10),␣(7,␣8),␣(6,␣5),␣(4,␣3),
28 ␣␣␣␣␣(1,␣2),␣(1,␣-2),␣(2,␣-2),␣(3,␣1),␣(5,␣3),␣(7,␣4),␣(11,␣4),
29 ␣␣␣␣␣(13,␣3),␣(15,␣1),␣(16,␣-3),␣(15,␣-7),␣(13,␣-9),␣(11,␣-10),
30 ␣␣␣␣␣(7,␣-10),␣(5,␣-9),␣(3,␣-7),␣(2,␣-4),␣(1,␣-4),␣(1,␣-8),␣(3,␣-16),
31 ␣␣␣␣␣(0,␣-16),␣(-3,␣-16),␣(-1,␣-8),␣(-1,␣-4),␣(-2,␣-4),␣(-3,␣-7),
32 ␣␣␣␣␣(-5,␣-9),␣(-7,␣-10),␣(-11,␣-10),␣(-13,␣-9),␣(-15,␣-7),␣(-16,␣-3),
33 ␣␣␣␣␣(-15,␣1),␣(-13,␣3),␣(-11,␣4),␣(-7,␣4),␣(-5,␣3),␣(-3,␣1),
34 ␣␣␣␣␣(-2,␣-2),␣(-1,␣-2),␣(-1,␣2),␣(-4,␣3),␣(-6,␣5),␣(-7,␣8),␣(-7,␣10),
35 ␣␣␣␣␣(-6,␣13),␣(-4,␣15),␣(0,␣16))
36 #␣ Register␣them␣under␣the␣names␣"dia",␣"heart",␣"shade",␣"clover"
37 getscreen().register_shape("dia",␣d)
38 getscreen().register_shape("heart",␣h)

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)

Running this program displays the drawings shown below.

Figure 10-4 Execution result of Program 10-5

127
10 Playing with Turtle Next Chapter Table of Contents

10.9 Turtle Demo


Python provides a turtle graphics demo program that can be called from the IDLE menu.

Figure 10-5 How to run the Turtle Demo

10.10 Theme: Creating projects with turtle


To test your skills so far, please create a project using Turtle.
 You will submit the program, screenshots, and your notes.
 The program should be programmed by you.
 However, it is okay to ask for advice. Please include an acknowledgement of the advice you
receive in your notes.
 Submit your project as an attachment.
 The following information should be included in the memo.
 Name, affiliation
 Description of your project
 The functions of Python and turtle graphics that you have learned.
 Bibliographic information about any information you referred to, if applicable, and if it is a
website, the title, URL and access date of the website
 If there is someone who helped you, write the name of the person who helped you and a
description of the help you received in the acknowledgments.
 This should be written in Word etc. and submitted as a PDF file.

10.11 How to take a screenshot


 To obtain a screenshot of a specific window in Windows, follow the steps below.
 Select the window.
 Hold down the ALT key and press the PRTSC key.
If you press only the PRTSC key, a screenshot of the entire screen will be taken.

128
10 Playing with Turtle Next Chapter Table of Contents

 This will copy the screenshot to the clipboard.


 You can then save the screenshot by pasting the contents of the clipboard into a program
that can manipulate images, such as Paint.
 See [17] for more details about screenshots on a Mac.

Table 10-1 Key Operation to Take a Schreen Shot

The entire A specific window Location of the shot


desktop
Windows Print Screen key Alt + Print Screen key Clipboard (with copy)
Win + Print Win + Alt + Print Save the file in PNG
Screen key Screen key format in the Picture
Screenshot folder/Video
Capture folder
Mac Command + shift Command + shift + 4 + Save to Desktop as PNG
+ 3 space
In current Windows 11, a screen shot tool ‘Snipping tool’ is launched with Print Screen key
instead of taking the screen shot of the entire desktop.

Figure 10-6 Keys used to take a schreen shot in Windows

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

Program 10-6 random_turtle.py

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

Program 10-7 detour.py

Row Source code


1 from␣turtle␣import␣*
2 def␣detour(L):
3 ␣␣␣␣if␣L␣<␣10:
4 ␣␣␣␣␣␣␣␣forward(L)
5 ␣␣␣␣else:
6 ␣␣␣␣␣␣␣␣LL␣=␣L/3
7 ␣␣␣␣␣␣␣␣detour(LL)
8 ␣␣␣␣␣␣␣␣left(60)
9 ␣␣␣␣␣␣␣␣detour(LL)
10 ␣␣␣␣␣␣␣␣right(120)
11 ␣␣␣␣␣␣␣␣detour(LL)
12 ␣␣␣␣␣␣␣␣left(60)
13 ␣␣␣␣␣␣␣␣detour(LL)
14
15 for␣i␣in␣range(6):
16 ␣␣␣␣detour(100)
17 ␣␣␣␣left(60)

131
10 Playing with Turtle Next Chapter Table of Contents

Program 10-8 turtle_tree.py

Row Source code


1 from␣turtle␣import␣*
2
3 #␣Recursively␣draw␣a␣tree
4 def␣tree(n):
5 ␣␣␣␣#␣If␣parameter␣is␣less␣than␣or␣equal␣to␣1,␣go␣forward␣5␣steps.
6 ␣␣␣␣if␣n<=1:
7 ␣␣␣␣␣␣␣␣forward(5)
8 ␣␣␣␣else:
9 ␣␣␣␣␣␣␣␣#␣If␣the␣parameter␣is␣greater␣than␣1,
10 ␣␣␣␣␣␣␣␣#␣move␣(the␣trunk)␣forward␣according␣to␣the␣value␣of␣the␣parameter
11 ␣␣␣␣␣␣␣␣forward(5*(1.1**n))
12 ␣␣␣␣␣␣␣␣#␣Record␣the␣current␣position␣and␣orientation
13 ␣␣␣␣␣␣␣␣xx␣=␣pos()
14 ␣␣␣␣␣␣␣␣h␣=␣heading()
15 ␣␣␣␣␣␣␣␣#␣Rotate␣30␣degrees␣to␣the␣left
16 ␣␣␣␣␣␣␣␣left(30)
17 ␣␣␣␣␣␣␣␣#␣Draw␣a␣tree␣of␣size␣n-2␣(left␣branch)
18 ␣␣␣␣␣␣␣␣tree(n-2)
19 ␣␣␣␣␣␣␣␣#␣Raise␣the␣pen␣to␣stop␣drawing␣the␣trajectory
20 ␣␣␣␣␣␣␣␣up()
21 ␣␣␣␣␣␣␣␣#␣Return␣to␣the␣previously␣recorded␣position␣(top␣of␣the␣trunk)
22 ␣␣␣␣␣␣␣␣setpos(xx)
23 ␣␣␣␣␣␣␣␣setheading(h)
24 ␣␣␣␣␣␣␣␣#␣Pull␣the␣pen␣down
25 ␣␣␣␣␣␣␣␣down()
26 ␣␣␣␣␣␣␣␣#␣Go␣15␣degrees␣to␣the␣right
27 ␣␣␣␣␣␣␣␣right(15)
28 ␣␣␣␣␣␣␣␣#␣Draw␣a␣tree␣with␣size␣n-1␣(right␣branch)
29 ␣␣␣␣␣␣␣␣tree(n-1)
30 ␣␣␣␣␣␣␣␣#␣Pull␣pen␣up␣and␣go␣back
31 ␣␣␣␣␣␣␣␣up()
32 ␣␣␣␣␣␣␣␣setpos(xx)
33 ␣␣␣␣␣␣␣␣setheading(h)
34 ␣␣␣␣␣␣␣␣#␣Pull␣the␣pen␣down
35 ␣␣␣␣␣␣␣␣down()
36
37 #␣Use␣the␣fastest␣drawing␣speed,␣as␣it␣takes␣a␣long␣time␣␣␣␣␣␣␣
38 speed(0)
39
40 #␣Draw␣a␣tree␣of␣size␣12
41 tree(12)

132
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents

11. Creating a GUI Application with Tkinter (1)


11.1 Learning goals of this chapter
In this chapter, you will create a GUI application using tkinter, and learn:
 The role of frameworks in GUI applications, and learn about event-driven programming.
 The MVC architecture in GUI applications.
 To understand how to define functions in Python by implementing callback functions in tkinter.

11.2 GUIs and event-driven programming


In GUI applications, the user selects and uses various operations using menus and buttons. They also
expect the computer to respond appropriately to their actions.
 These user operations are called “events.”
 Many GUI applications use a GUI “framework.”
 The framework monitors the mouse and keyboard operations, detects events, and calls the event-
handling program set up by the programmer.
In a GUI application that uses a framework, the programmer is mainly responsible for programming
the following parts.
 Configuration of the screen where buttons, etc. are placed to be used as a GUI application
 Definition of the processes to be run when an event occurs
This type of programming is called event-driven programming because it mainly describes
responses to events.

Screen
User design
GUI
Framework

Processing
when an event
occurs

User-created
programs

Figure 11-1 Framework for event-driven programming

11.3 Separating the model and user interface


Let's say you want to write a calculator program that handles addition, subtraction, multiplication,

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

Figure 11-2 Model-View-Control Architecture

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

Figure 11-3 Tkinter system configuration

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.

11.5 A simple exercise


We will start with an easy exercise to make sure you understand the framework of programs using
tkinter as well as the concepts and terms associated with them. The
program below uses the “<-” and “->” buttons like the diagram on
the left to scroll through the displayed days of the week. The GUI
can be exited by pressing the “EXIT” button.
This is a simple exercise, so please use it to try out various
functionalities of tkinter.

135
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents

Program 11-1 Simple tkinter exercise (tkdemo.py)

Row Source Code Notes


1 #␣Simple␣tkinter␣exercise,␣scroll␣through␣the␣days
2 #␣of␣the␣week␣with␣a␣button
3 import␣tkinter␣as␣tk Import the tkinter module
4 #␣Number␣that␣denotes␣the␣days␣list␣and␣current␣display with the name tk.
5 dow␣=␣["SUN",␣"MON",␣"TUE",␣"WED",␣"THU",␣"FRI",␣"SAT"] dow stands for day of week.
6 current_dow␣=␣0 current_dow is a variable
7 that stores the index of
8 #␣call␣back␣function␣that␣moves␣the␣day␣forward the day that is being
9 def␣forward(): displayed.
10 ␣␣␣␣global␣current_dow current_dow is treated as a
11 ␣␣␣␣current_dow␣+=␣1 global variable,
12 ␣␣␣␣if␣current_dow␣==␣7:
13 ␣␣␣␣␣␣␣␣current_dow␣=␣0
14 ␣␣␣␣l_dow["text"]␣=␣dow[current_dow] Update the text attribute
15 of label l_dow.
16 #␣call␣back␣function␣that␣moves␣the␣day␣back
17 def␣backward(): Everything but lowering
18 ␣␣␣␣global␣current_dow current_dow is the same as
19 ␣␣␣␣current_dow␣-=␣1 the forward function.
20 ␣␣␣␣if␣current_dow␣==␣-1:
21 ␣␣␣␣␣␣␣␣current_dow␣=␣6
22 ␣␣␣␣l_dow["text"]␣=␣dow[current_dow]
23 #␣call␣back␣function␣that␣terminates␣tkinter
24 def␣fin(): The destroy method of root
25 ␣␣␣␣root.destroy() window is called to
26 #␣Window␣and␣widget␣creation,␣widget␣layout terminate.
27 root␣=␣tk.Tk() Generate window as a root
28 f␣=␣tk.Frame(root) with the Tk method.
29 f.grid() Generate Frame as f root as
30 # parent, and position via
31 l_dow␣=␣tk.Label(f,␣text=dow[current_dow]) grid() method.
32 l_dow.grid(row=0,␣column=0,␣columnspan=3) Generate a label that
33 # displays the day, position
34 b_backward␣=␣tk.Button(f,␣text="<-",␣command␣=␣backward) using three columns in 0th
35 b_forward␣=␣tk.Button(f,text="->",␣command␣=␣forward) row.
36 b_exit␣=␣tk.Button(f,␣text="EXIT",␣command␣=␣fin) Specify the call back
37 b_backward.grid(row=1,␣column=0) function with the text
38 b_forward.grid(row=1,␣column=1) attribute and command
39 b_exit.grid(row=1,␣column␣=␣2) attribute to generate 3
40 #␣Start␣GUI buttons, position in 1st
41 print("tkinter␣started") row
42 root.mainloop() Start GUI with the
43 #␣Confirm␣GUI␣termination mainloop() method
44 print("tkinter␣stopped") Confirm that it terminated

The tkinter program will be structured in the following way.

 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

Window Frame Widgets such as buttons


root = tk.Tk() f = tk.Frame(root) b_forward = tk.Button(f)

Figure 11-4 Object relationships in tkinter

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

Call Back Functions


def␣backward(): def␣forward():
␣␣␣␣global␣current_dow ␣␣␣␣global␣current_dow
␣␣␣␣current_dow␣-=␣1 ␣␣␣␣current_dow␣+=␣1
␣␣␣␣if␣current_dow␣==␣-1: ␣␣␣␣if␣current_dow␣==␣7:
␣␣␣␣␣␣␣␣current_dow␣=␣6 ␣␣␣␣␣␣␣␣current_dow␣=␣0
␣␣␣␣l_dow["text"]␣=␣dow[current_dow] ␣␣␣␣l_dow["text"]␣=␣dow[current_dow]

Execute with Variable current_dow


Update Value
Button Click Update 'text' attribute
List dow = ["SUN", "MON", ...]

l_dow Global Variables

b_backward b_forward b_exit


Widgets

Figure 11-5 Behavior carried out by the widgets, call back functions, and global
variables

11.6 tkinter example of calculator (tkdemo_2term.py)


Consider the following addition-only calculator.
• It consists of 10 keys (0-9), 3 buttons (C (clear), + (add), =
(calculate)),
• and a single line of character input/output for numerical values.
• The 0 to 9 buttons insert a digit at the least significant digit of the
number being entered, just like a calculator. (Multiply the number
entered thus far by 10 and add the number of the pressed key to
it.)
• C sets the numerical value to 0.
• The + key registers the input number as the first term of a binary operation and then sets the
input number to 0 again.
• The = key registers the second input number as the second term of the binary arithmetic
operation, executes the addition, prints the result, and zeros the input number.
Program 11-2 is an example implementation of this.

138
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents

Program 11-2 Calculator for addition only (tkdemo_2term.py)

Row Source code Notes


1 import␣tkinter␣as␣tk Import tkinter using its
2 short form tk
3 #␣Defines␣variables␣for␣calculation␣functions␣and␣fu
nctions␣for␣events.
4 Note that there is no
5 #␣Model␣for␣binary␣operations dependency on variables,
6 #␣Number␣being␣entered functions, or GUIs to
7 current_number␣=␣0 handle binary operations
8 #␣First␣number
9 first_term␣=␣0
10 #␣Second␣number
11 second_term␣=␣0
12 #␣Result
13 result␣=␣0
14
15 def␣do_plus():
16 ␣␣␣␣"calculation␣when␣+␣key␣was␣pressed,␣set␣the␣fir
st␣term␣and␣clear␣the␣current␣input"
17 ␣␣␣␣global␣current_number
18 ␣␣␣␣global␣first_term
19
20 ␣␣␣␣first_term␣=␣current_number
21 ␣␣␣␣current_number␣=␣0
22
23 def␣do_eq():
24 ␣␣␣␣"calculation␣when␣=␣key␣was␣pressed,␣set␣the␣sec
ond␣term,␣executeaddition,␣clear␣the␣current␣input"
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 #␣Number␣key␣callback␣function The definition of the
33 def␣key1(): widget's callback function
34 ␣␣␣␣key(1) starts here
35 ␣␣␣␣
36 def␣key2():
37 ␣␣␣␣key(2)
38
39 def␣key3():
40 ␣␣␣␣key(3)
41
42 def␣key4():

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

11.7 Basic structure of a program using tkinter


Importing the module
import tkinter as tk # Import tkinter as the shorter custom name of tk

141
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents

Define the callback function


def key1():
Contents of key1
Create the window
root = tk.Tk()
Create and allocate a frame. A frame is a kind of container that stores widgets inside it.
f = tk.Frame(root) # Create a frame with root as its parent,
f.grid() # and allocate it to a location with grid()
Creating a widget (button)
b1 = tk.Button(f, text=ʻ1ʼ, command=key1)

# 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()

11.8 Layout on a grid


A widget in tkinter can be assigned to a window or container after specifying a layout manager to
manage the layout. There are several layout managers, but one of the simplest is grid, which provides
a grid for positioning widgets. It can be used as follows.
 Define a grid layout by specifying its position
b1.grid(row=3,column=0)
 It is also possible to specify how many columns there will be
e.grid(row=0,column=0,columnspan=4)

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

Widgets f = tk.Frame(root) root = tk.Tk()

Figure 11-6 Layout with grid

11.9 Writing a callback function using a lambda (λ)


notation
In the previous example, the contents of the functions key0() to key9() are calls to the function key()
with different arguments. In the definition of the widget, the command=key1 argument on the right
side of
b1 = tk.Button(f,text='1', command=key1)
must be a "function object," and if you write
b1 = tk.Button(f,text='1', command=key(1)) # This is wrong
then the argument of the key() function will be set to 1, the function is called, and into the command,
the return value is assigned. If you designate an argument of 1 to the key() function, it will not be
called as a callback function. On the other hand, the function key1() is a dedicated callback function
for button b1, and is not used for any other purpose. In this sense, it would be convenient to directly
link the definition of the function key1() with the specification of the callback function for button b1,
eliminating the need for the name key1.
Python uses the lambda notation 1 to achieve this, where a function is defined and assigned to a
14F15 F

variable without naming it on the fly. In the example of b1,


b1 = tk.Button(f,text='1', command=lambda:key(1))
The key(1) following lambda: is the content of the ad hoc function definition, which is essentially the
same as the key1() function.

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)

Row Source code Notes


1 import␣tkinter␣as␣tk Import
2 tkinter
3 #␣Defines␣variables␣for␣calculation␣functions␣and␣those for␣events. using
4 #␣Model␣for␣binary␣operations its
5 #␣Number␣being␣entered short
6 current_number␣=␣0 form tk
7 #␣First␣number
8 first_term␣=␣0
9 #␣Second␣number
10 second_term␣=␣0
11 #␣Result
12 result␣=␣0
13
14 def␣do_plus():
15 ␣␣␣␣"calculation␣when␣+␣key␣was␣pressed,␣set␣the␣first␣term␣and␣clear␣
the␣current␣input"
16 ␣␣␣␣global␣current_number
17 ␣␣␣␣global␣first_term
18
19 ␣␣␣␣first_term␣=␣current_number
20 ␣␣␣␣current_number␣=␣0
21
22 def␣do_eq():
23 ␣␣␣␣"calculation␣when␣=␣key␣was␣pressed,␣set␣the␣second␣term,␣executea
ddition,␣clear␣the␣current␣input"
24 ␣␣␣␣global␣second_term
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 #␣Functions␣for␣batch␣processing␣number␣keys
33 def␣key(n):
34 ␣␣␣␣global␣current_number
35 ␣␣␣␣current_number␣=␣current_number␣*␣10␣+␣n
36 ␣␣␣␣show_number(current_number)
37
38 def␣clear():
39 ␣␣␣␣global␣current_number
40 ␣␣␣␣current_number␣=␣0
41 ␣␣␣␣show_number(current_number)

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

11.10 Configuring the appearance of a widget


There are several ways to configure the color, size, font, etc. of a widget, such as a button.

How to set an argument when creating the widget


You can specify arguments when generating the widget. It is convenient to use keyword arguments.
 font=('Helvetica', 14) Text font and size
 width=2 The size of the widget
(For buttons, the number of characters)
 bg = ‘#ffffc0’ Background color, two hexadecimal digits each in
RGB 00 is darker, ff is lighter
Note that bg does not currently change the color on the Mac, so if you set the argument
highlightbackground instead of bg, the color of the button itself will not change, but the color around
the button will. Please substitute highlightbackground in for bg if you are doing this exercise on a
Mac.

Table 11-1 Specifying colors with tkinter

Notation Red Green Blue Color


'#ffffff' ff ff ff White
'#000000' 00 00 00 Black
'#ff0000' ff 00 00 Red
'#00ff00' 00 ff 00 Green
'#0000ff' 00 00 ff Blue

146
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents

Configuring the Appearance of a Generated Widget


(Part 1)
To change the appearance of a generated widget while it is running, use the configure() method of
the widget. The arguments are allocated in the same way as the keyword arguments are at the time of
generation. For example, suppose b is a button widget as follows:
b.configure(size=2)

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

Configuring the Appearance of the Generated Widget


(Part 2)
The appearance of the widget can also be set and referenced in the following way. Note that the
settings in square brackets must be a string (enclosed by quotation marks, etc.). Settings are
performed by substitution.
b["size"] =2
print(b[“size”])

Exercise 11-1 Create an Addition Calculator with Tkinter


Write a program like Program 11-2 or Program 11-3 and see how it works.

Exercise 11-2 Configuring the appearance of a widget


 Set the font size of the addition calculator and the color of the widget as follows. Set the
background color to '#ffffc0' (light yellow) for the frame, white for numeric keys, red for clear
keys, and green for + and = keys.
 The size of the button should be 2 (the length in characters).
 The font and size of the button and entry should be ('Helvetica', 14).

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

 Add a button widget to specify the four arithmetic operations.


(This should not be too difficult.)
 Set up a callback function for when the arithmetic operator button or the “=” button is
pressed.
Consider the following hints.
 In a calculator, when an operation key such as + is pressed, the operation is not
performed; it is performed when the = key is pressed. Thus, when an arithmetic key (for
addition, subtraction, multiplication, or division) is pressed, the calculator stores the
operation to be performed in a variable until it is executed. For example, you could set up
a variable called “operation” and set it to 1 for addition, 2 for subtraction, 3 for
multiplication, 4 for division.
 When the = key is pressed, you need to change the operation that is actually performed to
match the stored operation. For example, your code may look like this:
if operation == 1:
Block that performs addition
elif operation == 2:
Block that performs subtraction
elif operation == 3:
Block that performs multiplication
else:
Block that performs division

Exercise 11-4 Management of Widgets with List (Skill Test)


In Program 11-2 and Program 11-3, we use many Button widgets. Try to manage them by using
these objects as members of a list. With this list, try to rewrite the program using 'for' statement.
Note: we use a lambda expression in Program 11-3 (for example, command=lambda:key(1)).
Here, the argument of function key(1) is given as a constant, but with this expression, we can't use a
variables (for example, i) whose value should be exaluated at the definition of the lambda
expression. It can be written using lambda expression with an argument having a default value like
the following:
command=lambda x = i:key(x)

Exercise 11-5 Differences with an actual calculator


Look for differences in behavior between your program and an actual calculator (or calculator
application). For example, what happens when you press an arithmetic key such as + instead of =?
You will find that actual calculator products are well designed.

11.11 How to close tkinter


In an application using tkinter, calling mainloop() will result in an infinite loop that waits for user
action and then calls the callback function. Methods of closing tkinter other than exiting with the exit

148
11 Creating a GUI Application with Tkinter (1) Next Chapter Table of Contents

button of the window are as follows.


 To escape from mainloop(), call the quit() or destroy() method of the object created by tk.Tk()
(e.g., root) in a given callback function. The difference in the behavior of these methods is as
follows:
 quit(): The program exits the loop, but the window or widgets remain.
 destroy(): exits the loop and removes the window or widgets altogether.

11.12 How to extend the Frame class


In the previous program, Frame and widgets such as the Button widget were configured separately.
However, in practical examples of tkinter, Frame is often implemented as an extended class and
widgets are generated during its initialization. In this section, we show an example of this. For more
information about classes, please refer to the explanation in a later chapter.

Program 11-4 How to extend the Frame class in tkinter


(tkdemo-2term_frame_extention.py)

Row Source code Notes


1 import␣tkinter␣as␣tk
2
3 #␣Defines␣variables␣for␣calculation␣functions␣and␣those␣for␣events
.
4 #␣Example␣using␣Frame␣subclasses
5
6 #␣Model␣for␣binary␣operations
7 #␣Number␣being␣entered
8 current_number␣=␣0
9 #␣First␣number
10 first_term␣=␣0
11 #␣Second␣number
12 second_term␣=␣0
13 #␣Result
14 result␣=␣0
15
16 def␣do_plus():
17 ␣␣␣␣"calculation␣when␣+␣key␣was␣pressed,␣set␣the␣first␣term␣and␣cl
ear␣the␣current␣input"
18 ␣␣␣␣global␣current_number
19 ␣␣␣␣global␣first_term
20 ␣␣␣␣first_term␣=␣current_number
21 ␣␣␣␣current_number␣=␣0
22
23 def␣do_eq():
24 ␣␣␣␣"calculation␣when␣=␣key␣was␣pressed,␣set␣the␣second␣term,␣exec
uteaddition,␣clear␣the␣current␣input"

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

11.13 Utilizing images with tkinter

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.

Handling images with tkinter


Here we will make use of tkinter's PhotoImage class. The image formats supported by this class are
PGM, PPM, GIF, and PNG (Tkinter version 8.6 and on). The well-known JPEG image format cannot
be used as-is. To use it, one would need to convert to a different format in advance or concurrently
use a different module for image handling.

Program that displays card images


Create a folder called Cards within the folder where this program is saved and store the card images
inside it.
As seen in Program 11-5 below,
 First, create a list of the image filenames and store it in cardImages,
 Then create a PhotoImage class object list that has read the image files and assign it to
cardImageWidgets.
 After this, we convert the image attributes of the labels for displaying images using the call back
functions “back” and “forward.”

Program 11-5 Program that displays card images: tkdemo-show_cards.py

Row Source Code Notes


1 #␣Show␣Card␣Images␣with␣tkinter
2 import␣tkinter␣as␣tk
3
4 #␣Components␣that␣make␣up␣card␣filenames
5 backs␣=␣["blue",␣"green",␣"red"]
6 suits␣=␣["Clubs",␣"Diamonds",␣"Hearts",␣"Spades"]

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

60 #␣Label␣widget␣that␣displays␣card␣images Create and position the


61 l␣=␣tk.Label(f,␣text␣=␣"card") label widget that
62 bb.grid(row=0,␣column=0) displays the forward and
63 l.grid(row=0,␣column=1) backward buttons and
64 bf.grid(row=0,␣column=2) images.
65 #␣Set␣the␣first␣image
66 l["image"]␣=␣cardImageWidgets[cardIndex] Set the first image
67
68 root.mainloop()

Running the program results in the display shown below (examples of a few cards are shown).

Figure 11-7 Execution of Program 11-5

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

12. Creating a GUI Application with Tkinter (2)


12.1 Learning goals of this chapter
In this chapter, you will learn the following skills by creating an analog clock with tkinter:
 How to use autonomous programs such as animations together with a GUI, and
 How to draw graphics using the Canvas widget.

12.2 Conflicts between autonomous programs and


GUIs
GUI frameworks such as tkinter observe user operations and delegate processing to a set callback
function when an event such as a mouse click occurs. At that time, the callback function is expected
to terminate promptly. It waits for the callback function to finish, then goes back to observing,
waiting for an event to occur.
At the same time, if the program itself operates continuously (as is the case with an animation) and if
the callback function is then called, the observation of events will stop.
In tkinter, there is a method called after that executes the specified callback function after a given
period of time to meet both of these needs. Using the after method allows tkinter to register the
process after the specified time and terminate the callback function so that the GUI event observation
loop is not stopped for a long period of time.
Can’t run at the same time

Call_back process Waiting for Displaying


Waiting for input
the time the time

mainloop() Clock behavior

Using after

Time display
Waiting for input Call_back process Register after

mainloop() Clock behavior


プ グ グ演 第

Figure 12-1 Use of 'after' in tkinter

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.

12.3 Analog clock program using tkinter


In this section, you will create an analog clock as shown in Figure 12-2. It displays the hour, minute,
155
12 Creating a GUI Application with Tkinter (2) Next Chapter Table of Contents

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.

Figure 12-2 The analog clock you will create

12

x = x0 + r * cos(θ)
(x0, y0)
9 3
θ = (seconds/60)*360-90
r
y = y0 + r * sin(θ)
y 6
(x, y)

Figure 12-3 Calculation of the position of the hands of the clock

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.

Program 12-1 Analog clock with tkinter (without a date button,


tkdemo_simple_clock.py)

Row Source code Notes


1 #
2 #␣Analog␣clock␣with␣no␣date␣button␣using␣tkinter␣canvas
3 #
4 import␣tkinter␣as␣tk Import time to
5 import␣math handle time
6 import␣time
7
8 #
9 #␣Extend␣the␣Frame␣class
10 #
11 class␣MyFrame(tk.Frame): Two underscores on
12 ␣␣␣␣def␣__init__(self,␣master␣=␣None): each side
13 ␣␣␣␣␣␣␣␣super().__init__(master)
14 #
15 #␣Create␣a␣canvas
16 #
17 ␣␣␣␣␣␣␣␣self.size␣=␣200
18 ␣␣␣␣␣␣␣␣self.clock␣=␣tk.Canvas(self,␣width=self.size,␣heigh Widget for drawing
t=self.size,␣background="white")
19 ␣␣␣␣␣␣␣␣self.clock.grid(row=0,␣column=0)
20 #
21 #␣Draw␣the␣dial
22 #
23 ␣␣␣␣␣␣␣␣self.font_size␣=␣int(self.size/15)
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␣instance␣variables␣to␣check␣for␣the␣passage␣of␣tim
e
30 #
31 ␣␣␣␣␣␣␣␣self.sec␣=␣time.localtime().tm_sec
32 ␣␣␣␣␣␣␣␣self.min␣=␣time.localtime().tm_min

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

Program 12-2 Analog clock with tkinter


(with a date button, tkdemo_clock_with_button.py)

Row Source code Notes


1 #
2 #␣Analog␣clock␣with␣a␣date␣button␣using␣tkinter␣canvas
3 #
4 import␣tkinter␣as␣tk
5 import␣math
6 import␣time Import time to
7 handle time
8 #
9 #␣Extend␣the␣Frame␣class
10 #
11 class␣MyFrame(tk.Frame):
12 ␣␣␣␣def␣__init__(self,␣master␣=␣None):
13 ␣␣␣␣␣␣␣␣super().__init__(master)
14 #
15 #␣Create␣a␣canvas
16 # Widget for
17 ␣␣␣␣␣␣␣␣self.size␣=␣200 drawing
18 ␣␣␣␣␣␣␣␣self.clock␣=␣tk.Canvas(self,␣width=self.size,␣heigh
t=self.size,␣background="white")
19 ␣␣␣␣␣␣␣␣self.clock.grid(row=0,␣column=0)
20 #
21 #␣Draw␣the␣dial
22 #
23 ␣␣␣␣␣␣␣␣self.font_size␣=␣int(self.size/15)

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

Key points of this program


 You will need to import modules other than tkinter, including the time module, which is
imported to handle time, and the math module, which is imported to use trigonometric functions.
 This program defines the MyFrame class, which is an extension of Frame, then creates widgets,
assigns them, and defines callback functions within it.
 The __init__() method of the MyFrame class is automatically called when the class object is
created. In this method, the necessary widgets are created. There are two underscores on
each side of the method name.
 The Canvas widget is created for drawing
 The dial is drawn by calling the create_text() method of the Canvas widget.
 A button is created to toggle the display of the time in text. (Only for the code that
includes the button)
 Instance variables are allocated for time elapsing, display switching, etc., and set the
values using the seconds, minutes, hours, etc., in the time.localtime() function.
 A callback function is defined for when the button is pressed. The b.configure() method is
called to switch the text displayed on the button (b), and set the variable representing the
state. (Only in the code with the button)
 Method to draw the clock face:
 When using Canvas to draw, you can attach a “tag” to the drawn object, so that you can
delete it later. First you will need to delete the old drawing (clock hand).
 The coordinates of the clock hands are calculated from the time using a trigonometric
function, and drawn using the create_line() method.
 At the end of this method, the after method is set to make this method call itself 100
milliseconds later to continuously draw the clock.
 Finally, there is the main program. The program creates a window with the Tk() method, creates
a MyFrame class object, draws the first instance of the clock with f.display(), and then passes
control of the program to tkinter with mainloop().

Exercise 12-1 Reviewing the methods to be used


List the methods of the time module, math module, and tkinter Canvas class that are called in this
program, and look over these methods in detail in the Python online documentation.

Exercise 12-2 Modifying the analog clock


Make the following modifications to the analog clock program.
1. For the date display, have it display the date and the time using a.m. and p.m. instead of just
the date and time.

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.

Exercise 12-3 Improving the display


This program redraws the clock hands and the date every 100 milliseconds, but it also redraws things
that do not change. The date and position of the second hand change every second, but the minute
hand and hour hand only change every minute. Think about how you can make it so the minute and
hour hands are only redrawn if there has been a change since the last time it was drawn. Also, think
about how to avoid the roughly second long delay that occurs when the screen is first displayed or
when a button is pressed.

12.4 Coordinating actions using variables


In Program 12-2, when the button to turn on/off the date display is pressed, the value of the
show_date variable is simply switched using the toggle() method that is set as the callback function.
On the other hand, the display() method, which runs continuously on a timer, looks at the show_date
variable and toggles the date display on and off.
You can use variables to create settings that coordinate the behavior of methods that work
independently of each other. Variables such as show_date are called flags because they are used to
raise and lower flags.

toggle display

Redraw the second, minute, and hour hands


Toggle button display

Button

Remove the date


Invert self.show_date

If self.show_date

Yes
Draw the date

Register in after

show_date

Figure 12-4 Coordinating actions using variables

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.

13.2 Object-oriented programming


To handle multiple turtles in turtle graphics, we did the following.
 Generate as many turtles as needed.
 Call methods on individual turtles to tell them what to do and query their status.
Each turtle had its own state, which included its position, orientation, pen color, and whether or not
the pen was down.
Objects are things like these turtles that have their own internal state and can be instructed to behave
by calling methods from outside. Programming with objects is called object-oriented programming.
In the tkinter analog clock example, programming was done by extending the Frame class of tkinter.
A “class” is a description of a type that can be used to generate objects with unique states and
methods. Each object generated from a class is called an “instance.”
In short:
 An object (of a class type) is an element of a program with its own state (variables) and
methods, like a robot that you can order around (as we did with the turtles).
 A class is a description of what variables and methods an object of that type has; it is a type
used to create objects.
 An instance is an individual object generated with a class as its type.
 Object-oriented programming is a method of creating programs by defining classes and using
generated instances of them. It is a concept that can be described as writing programs to
coordinate the behavior of robots.

13.3 How to write and use classes in Python


As in the tkinter example, we will create a character user interface (CUI) type program that performs
binary operations. we will use a class to organize the variables that hold the first and second terms,
the result of the operation, the operator, and the method that actually performs the operation.

164
13 Classes Next Chapter Table of Contents

Source code
Program 13-1 CUI calculator program (p13-1.py)

Row Source code Notes


1 class␣Calculator():
2 ␣␣␣␣def␣__init__(self): Initialization
3 ␣␣␣␣␣␣␣␣self.first_term␣=␣0 method
4 ␣␣␣␣␣␣␣␣self.second_term␣=␣0
5 ␣␣␣␣␣␣␣␣self.result␣=␣0
6 ␣␣␣␣␣␣␣␣self.operation␣=␣"+"
7 ␣␣␣␣␣␣␣␣
8 ␣␣␣␣def␣do_operation(self):
9 ␣␣␣␣␣␣␣␣if␣self.operation␣==␣"+": Method to perform
10 ␣␣␣␣␣␣␣␣␣␣␣␣self.result␣=␣self.first_term␣+␣self.second_term operations
11 ␣␣␣␣␣␣␣␣elif␣self.operation␣==␣"-":
12 ␣␣␣␣␣␣␣␣␣␣␣␣self.result␣=␣self.first_term␣-␣self.second_term
13
14 #␣Main␣program␣starts␣here
15 calculator␣=␣Calculator() Create an object
16 while␣True:
17 ␣␣␣␣f␣=␣int(input("First␣term␣"))
18 ␣␣␣␣calculator.first_term␣=␣f
19 ␣␣␣␣o␣=␣input("Operation␣")
20 ␣␣␣␣calculator.operation=o
21 ␣␣␣␣s␣=␣int(input("Second␣term␣"))
22 ␣␣␣␣calculator.second_term=s
23 ␣␣␣␣calculator.do_operation()
24 ␣␣␣␣r␣=␣calculator.result
25 ␣␣␣␣print("Result␣",␣r)

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

Overview of the program


 Class definition block (lines 1-12): classes are defined as follows.
class ClassName ():

Definition of methods, etc.

 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 ()

 Manipulation of instance variables and methods of class-type objects (lines 18-24). By


appending a “.” followed by an instance variable name or method name to the class object
variable, you can call these methods or variables. Note that the do_operation() method requires
the parameter self in the definition, but does not require it when it is called.

166
13 Classes Next Chapter Table of Contents

Exercise 13-1 Extention of Calculator Class


Extend the Calculator class to handle multiplication and division. You may return just an integer
quotient for division.

Exercise 13-2 Creation and Utilization of Multiple Objects


Create a program that generates and uses multiple objects of the Calculator class. Think about what
you can do if you are able to utilize many robots that do addition. For example, how about a robot
that does addition and another that monitors it, then checks the figures (does subtraction)?

Exercise 13-3 User Calculator Class in the Tkinter Program


Modify the calculator program created by tkinter so that it uses the Calculator class

13.4 Class variables and access restrictions


We mentioned earlier that Python programs have global variables that are valid for the entire
program and local variables that are valid only while executing within a function. You also need to
learn about class variables and instance variables when working with classes.

 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

Program 13-2 Class variables and instance variables (p13-2.py)

Row Source code Notes


1 #␣Class␣practice
2 class␣MyClass(): Class Definition
3 ␣␣␣␣#␣The␣following␣are␣class␣variables
4 ␣␣␣␣a␣=␣"My␣Class" __b is an access-
5 ␣␣␣␣__b␣=␣0 protected variable
6 ␣␣␣␣
7 ␣␣␣␣#␣The␣following␣is␣the␣function␣called␣to␣create␣mydata,
␣giving␣the␣initial␣value␣of␣the␣mydata␣as␣a␣parameter This is an
8 ␣␣␣␣ initialization
9 ␣␣␣␣def␣__init__(self,␣data): method that takes
10 ␣␣␣␣␣␣␣␣#␣__number␣is␣a␣serial␣number␣given␣to␣the␣instance parameter data
11 ␣␣␣␣␣␣␣␣self.__number␣=␣MyClass.__b
12 ␣␣␣␣␣␣␣␣self.mydata␣=␣data
13 ␣␣␣␣␣␣␣␣print("MyClass␣Object␣is␣created,␣number:␣",␣
self.__number)
14 ␣␣␣␣#␣Increase␣the␣value␣of␣the␣class␣variable␣by␣1
15 ␣␣␣␣␣␣␣␣MyClass.__b␣+=␣1
16
17 ␣␣␣␣#␣Method␣that␣displays␣the␣serial␣number␣␣␣␣
18 ␣␣␣␣def␣show_number(self):
19 ␣␣␣␣␣␣␣␣print(self.__number)
20
21 #
22 #␣Main␣program␣from␣here
23 #
24 if␣__name__␣==␣"__main__": Does not execute
25 ␣␣␣␣print("Class␣Variable␣a␣of␣MyClass:␣",MyClass.a) when imported as a
26 module, according
27 ␣␣␣␣instance1␣=␣MyClass(1) to the instructions
28 ␣␣␣␣instance2␣=␣MyClass(10) in line 24
29
30 ␣␣␣␣instance1.show_number()
31 ␣␣␣␣instance2.show_number()
32
33 ␣␣␣␣print("mydata␣of␣instance1:␣",␣instance1.mydata)
34 ␣␣␣␣print("mydata␣of␣instance2:␣",␣instance2.mydata)
35 ␣␣␣␣instance1.mydata␣+=␣1
36 ␣␣␣␣instance2.mydata␣+=␣2
37 ␣␣␣␣print("mydata␣of␣instance1:␣",␣instance1.mydata)
38 ␣␣␣␣print("mydata␣of␣instance2:␣",␣instance2.mydata)

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 Variable a of MyClass: My Class


MyClass Object is created, number: 0
MyClass Object is created, number: 1
0
1
mydata of instance1: 1
mydata of instance2: 10
mydata of instance1: 2
mydata of instance2: 12
Also, the following operation will cause an error in the shell. You can see that instance variables that
start with “__” are protected.
>>> print(instance1.__number)
Traceback (most recent call last):
File "<pyshell#46>", line 1, in <module>
print(instance1.__number)
AttributeError: 'MyClass' object has no attribute '__number'

Note that the line:


if __name__ == “__main__”:
in the source code indicates that this code will only be executed when the current file is run as the
main program. It is possible to import this source code as a module, but in that case, anything below
this line will not be executed.

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

The only shared variable


in the class

Figure 13-1 Class and 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.

13.6 Designing classes starting from instances


Classes are a powerful tool for creating programs that do complex things. As we saw earlier, a class
is a “type” that creates objects of a class type (instances). However, it is difficult to think of things
in terms of types.
When actually designing a class, it is best to think in terms of specific instances, as shown below.
 Consider the data (candidates for instance variables) and operations (candidates for methods)
that you want to handle together as a single object.
 Consider a class for each such object.
 Make the classes more widely available.
 If multiple objects (classes) are the same, then the same class can be used for those objects.
 If the only difference is values that are set, consider assigning the value to an instance
variable and giving it as an argument when the object is created.
 If shared methods and individual methods are mixed, consider inheritance.

170
14 File Input/Output Next Chapter Table of Contents

14. File Input/Output

14.1 Learning goals of this chapter


1. Learn about text files as they are used in Python.
2. Learn how to use spreadsheet software dealing with CSV files to handle the results of Python
calculations.
3. Learn how to read and write text files in Python.
4. Learn about filedialog in tkinter to assist in selecting files.

14.2 How to store data permanently


In conventional programs, data set to variables in the program is retained only while the program is
running, and is erased when the program is terminated.
In addition, the input and output of a program, whether GUI or CUI, is input by a human, and the
results are read by a human.
In order to use data permanently in a program, it is necessary to write and read data in a form that
can be saved outside the program. Candidates for this are as follows:
• A file on the computer
• A database on a computer
• A service on a network

In this section, you will learn how to handle files on a computer, which is the basis of all of these
methods.

14.3 Regarding files

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

Use of Raw String


When you write file path directly in a source code, you should know Python treats '\' for
special meaning, e.g, '\n' means newline. Since a filepath often uses '\' for separator of
folders, you have to write two '\'s for each '\'
filepath = "M:¥¥documents¥¥python scripts¥¥p3-1.py"
or use prefix 'r' to treat the string as it is:
filepath = r"M:¥documents¥python scripts¥p3-1.py"
Reference the column titled " Escaping."

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.

Character Encoding Issues


Due to the historical nature of the Japanese language, there are several different character encodings
that are used on different operating systems. For example, the character codes used for Japanese file
names are as follows
• Mac, Linux: Unicode
• Windows: Shift-JIS
In text files, in addition to the above differences in character encoding, there are also differences in
the code used to represent a line break.
- Python 3 uses UTF-8 internally, which is one of the Unicode representations. Python programs
(scripts) created in IDLE are coded and stored in UTF-8 as well. If you are running Python on a
single OS, you don't need to worry too much about the differences between OSes, as Python will
adjust accordingly. You need to be careful when running the program on different operating systems,
however.

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

14.4 Let's try to run the code below first.

Source code
Program 14-1 Example of File Input/Output (p14-1.py)

Row Source code Notes


1 #␣Import␣the␣OS␣module␣to␣find␣out␣the␣current␣working␣
directory␣(the␣folder␣where␣you␣are␣working)
2 import␣os
3
4 #␣Get␣the␣current␣working␣directory␣and␣print␣it␣on␣the␣screen
5 print(os.getcwd())
6 #␣Create␣a␣file␣named␣'Japanese␣file.txt'␣and␣write␣fill␣it␣in
7 f␣=␣open('Japanese-File.txt','w')
8 f.write('日本語\n 日本語\n 日本語\n') Write text in
9 f.close() Kanji. On
10 #␣Open␣Japanese␣file.txt␣for␣reading␣to␣display␣its␣contents Windows, "\"
11 f␣=␣open('Japanese-File.txt','r') may be shown as
12 s␣=␣f.read() "\"
13 f.close()
14 print(s)

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)

14.5 Reading and writing files in Python

Using the open Function


Files can be manipulated as per the following procedure.

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

file = open("filename", "r")


for line in file:
A block that works on each line one line at a time

Using the 'with' statement - Automating close()


A file opened with the open() function must be closed with the close() method, but in the following
cases, the close() function may not be performed.
 You simply forgot to call the close() method.

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

14.6 Example 1 Wave approximation

Key points in the example below


• Since it is cumbersome to input the exact file path from a terminal, tkinter (only the filedialog
module) is used.
• The calculation results are output in CSV format and linked to spreadsheet software.
• As an example, we will use an example that expresses a periodic function as a sum of
trigonometric functions.

Approximation of Periodic Function by Sum of


Trigonometric Functions
It is known that a periodic function (a function whose value repeats with a certain period) can be
approximated by the sum of sine (sin) and cosine (cos) functions that are integer multiples of the
frequency. A sawtooth wave can be approximated as follows (see also the column titled
“Trigonometric Functions”).
sin(𝑥𝑥) sin(2𝑥𝑥) sin(3𝑥𝑥) sin(4𝑥𝑥)
𝑓𝑓(𝑥𝑥) = + + + …
1 2 3 4
The figure below plots the sum of the first through fifth terms.

Figure 14-1 Approximation of a sawtooth wave by summing trigonometric functions

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

Figure 14-2 Approximation of a sawtooth wave by summing trigonometric functions


(with positive slope at the origin)

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)

Row Source code Notes


1 import␣tkinter␣as␣tk
2 import␣tkinter.filedialog Import filedialog as
3 import␣math well
4 #
5 #␣Example␣of␣using␣only␣tkinter's␣filedialog
6 #
7 #␣Hide␣the␣root␣window␣by␣reading␣the␣withdraw()␣method
8 root␣=␣tk.Tk()
9 root.withdraw()
10 #
11 #␣Read␣the␣filedialog␣for␣writing␣and␣get␣the␣file␣name.
12 #
13 filename␣=␣tkinter.filedialog.asksaveasfilename() Get the file name
14 # from the dialog and
15 #␣Close␣tkinter go back.
16 # tkinter is no longer
17 root.destroy() used, so it is
18 # closed.
19 #␣If␣you␣don't␣get␣a␣file␣name,␣close␣it
20 #
21 if␣filename:
22 ␣␣␣␣pass pass is a command
23 else: that does not do
24 ␣␣␣␣print("No␣file␣specified") anything.
25 ␣␣␣␣exit()␣␣␣␣
26 #
27 #␣Approximate␣a␣saw␣wave␣by␣superimposing␣sine␣waves␣upon
␣one␣another
28 #
29 #␣w␣=␣sin(t)␣+␣sin(2t)/2␣+␣sin(3t)/3␣+␣sin(4t)/4␣...
30 #
31 #␣2␣periods␣worth,␣1000␣steps␣overall,␣harmonics␣up␣to␣th
e␣5th
32 #
33 cycles␣=␣2
34 steps␣=␣1000
35 harmonics␣=␣5
36 #␣Error␣handling␣when␣a␣file␣cannot␣be␣opened
37 try:
38 #␣Open␣the␣file
39 ␣␣␣␣with␣open(filename,'w')␣as␣file:
40 ␣␣␣␣␣␣␣␣for␣i␣in␣range(steps):
178
14 File Input/Output Next Chapter Table of Contents

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

1) Use of tkinter's filedialog (lines 1-25)


 When you open or save a file in a Windows application, you can find or specify the file in a
separate window. tkinter provides a filedialog mechanism for this purpose. In this program, the
main window of tkinter is created in line 8. Because we use only the filedialog function, the
main window of tkinter is hided in line 9. Also note that the mainloop() method is not called.
 There are several formats for filedialog depending on the intended use, but in this case, the
asksaveasfilename() method for "save as" is called in line 13, and the filename is set to the file
name (path name) obtained by the return value.
 Since tkinter is not needed when coming back from filedialog, root.destroy() terminates tkinter.
 If the user does something such as cancel the program, the filename will be empty, so the
program will be terminated when the if statement is false.
 For more information on using filedialog for reading, refer to the following example.

2) Calculation and file output (lines 23 to 53)


 This part calculates the superposition of trigonometric functions and outputs it in CSV format.
 For file handling, it is necessary to deal with an error such as when the program is not able to
open the file. In line 37, a block that manipulates the file with a try statement handles this. The
corresponding error handling is in lines 52 and 53.
 In line 40, a with statement is used to open a file with filename obtained from filedialog, and the
opened file is handled by the variable file.
 One line of computation and output is as follows:
angle, first term, sum up to second term, sum up to third term, sum up to fourth term, sum up to fifth
term.

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 “¥.”

Exercise 14-1 Square wave approximation


A square wave (a periodic function that alternates between values of ±1) can be approximated by a
trigonometric function as follows 2
sin(𝑥𝑥) sin(3𝑥𝑥) sin(5𝑥𝑥) sin(7𝑥𝑥)
𝑓𝑓(𝑥𝑥) = + + + …
1 3 5 7

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.

Figure 14-3 Approximation of a square wave by summing trigonometric functions

Exercise 14-2 Implementation of the list from Example 1


In the program in Example 1, the results of the calculations were concatenated as strings and written
to a file one line at a time. Reimplement this program as follows, separating the calculation and
1Turing part of a program that could otherwise be executed into a comment is called “commenting out,” and is often used to check the
operation of a program.
2 For a square wave of amplitude 1, a factor of 4/π is applied to the whole wave.

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.

[ [time(0), term 1(0), sum(0) up to term 2, sum(0) up to term 3, sum(0) up to term 4] ,


[time(1), term 1(1), sum(1) up to term 2, sum(1) up to term 3, sum(1) up to term 4]
,
[time(2), term 1(2), sum(2) up to term 2, sum(2) up to term 3, sum(2) up to term 4] ,
[time(3), term 1(3), sum(3) up to term 2, sum(3) up to term 3, sum(3) up to term 4] ]

Figure 14-4 Using a “list of data at different time points”


Series of sums up to

Series of sums up

Series of sums up
to the fourth term
Series of times

to the third term


the second term
Series of the
first term

Figure 14-5 Using a “list of each series’”

14.7 Example 2 Text Editor


You can create a simple text editor using tkinter. tkinter has all the features you have learned so far,
as well as the messagebox dialog for displaying messages, the filedialog method for reading files, the
tkinter Menu widget, Text widget, etc. For the geometry manager, we will use 'pack' instead of 'grid'
for simplicity.
The Kanji encoding for the files is not specified, so Python assumes the standard encoding for each
OS. On Windows, it is assumed that Shift-JIS code (cp932) is used.

Program 14-3 A simple text editor using tkinter (p14-3.py)

Row Source code


1 import␣tkinter␣as␣tk
2 import␣tkinter.messagebox
3 import␣tkinter.filedialog
4 #␣messagebox␣and␣filedialog␣need␣to␣be␣imported␣explicitly

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

15. Learning Program Development with Tic-Tac-


Toe
15.1 Learning goals of this chapter
In this chapter, you will do the following to learn how to develop a program, using tic-tac-toe as an
example.
1. Analyze how to play tic-tac-toe, and identify what needs to be expressed in the program.
2. Prepare a game record for testing the program.
3. Create the data and functions that make up the program, starting with the smallest.
4. Assemble the whole program to complete the tic-tac-toe program.

15.2 Developing a program


As seen in the previous programs, it is difficult for beginners to create a program when given a
specific task. This is because being able to use the various elements of a programming language and
developing a coherent program from scratch are two different skills. For example, just because you
can use a hammer and a saw doesn't mean you can build a house, because to build a house, you
need to know what it consists of and in what order it needs to be designed and constructed. The same
applies to programs.

15.3 Design procedure - what to do before using your


computer
You often see beginners open their computer to create a program only to end up getting stuck. Why
does that happen?
The procedure for designing and creating a program is as follows. You don't necessarily need the
computer at first, but because you are facing the computer screen, you may get stuck.
 What to do before using a computer
 Describe what you want to achieve in words
 Identify what you need the program to do
 What to express as variables
 What values each variable will have
 What should be expressed as a protocol (function)
 What should be expressed as an interaction with people

184
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents

 Decide the order in which to create the program


 Decide how to test it
 This is where the work on the computer begins
 Create the program (functions) starting with the parts that do not depend on others
 Test the functions you create (unit testing)
 Test the whole program (integration testing)

15.4 Designing a simple tic-tac-toe program

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

Creating a Game Record (to Prepare for Testing)


Before you build your program, you should make some test board game records. It is difficult to
cover all cases, but here are some cases to consider.
 Must include cases where player one wins, player two wins, and there is a draw
 Include all the different winning patterns (vertical (3 ways), horizontal (3 ways), diagonal (2
ways))
Preparing test cases first is called “test first programming;” it is more effective than “coding first,”
which is where you start building the program first, in the following reasons
 You're less likely to create test cases if you start later
 You can test these cases at any time during the creation of the program
 Test cases can help you to be aware of the need to test during coding

手番 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〇

Figure 15-1 Example tic-tac-toe game records

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

constants to consider the turn and result.


OPEN = 0
FIRST = 1
SECOND = 2
DRAW = 3

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.

Functions concerning the board and turns


Create functions to “operate” on the state, “check” the state, “display” it on the screen, initialize it (a
type of operation), etc.
The board and the turn are shared as global variables, so a global declaration is required to change
the values of variables outside the function from within a function. Functions such as those below
may be needed.

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.

4) Algorithm for determining the winner


If you try to explicitly write out a method of determining the winner of a game of tic-tac-toe as you
play it in your daily life, it would be as follows.
 Determine whether the turn (denoted by t) results in victory in a given row or column.
 If all the spots in the three positions in row/column of interest are t, then t wins.
 Otherwise, t does not win
 Determine if the game is won in a certain direction (horizontal, vertical, diagonal, reverse
diagonal)
 If horizontal or vertical
 if the game is won in row 0 (column 0), t wins
 If not, then if the game is won in row 1 (column 1), t wins
 If not, then if the game is won in row 2 (column 2), t wins
 Otherwise, t does not win
 If the game is won in the diagonal or reverse diagonal line, then t wins
 Determining victory based on the above
1. If the game is won horizontally, then t wins.
2. If not, then if the game is won vertically, t wins.
3. If not, then if the game is won diagonally, t wins.
4. If not, then if the game is won reverse diagonally, t wins.
5. Otherwise, t does not win
Also, while it is not possible on a board where victory is checked for every turn, on a randomly
generated board, it is possible to have a case where both player one and player two win.

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

If you have all of the


Victory in a column spaces in any of
these directions, you
Victory in a win
diagonal line
Victory in a reverse
diagonal line

Figure 15-2 Determining victory for the turn in question

 Determining the winner


Using the above procedure (function), you can determine the winner of a game of tic-tac-toe as
follows.
1. Check whether player one has won or not; if player one has won, then it is player one’s victory.
2. If not, then check whether player two has won or not; if player two has won, then it is player
two’s victory.
3. If not, then if there is still an empty space on the board, then the game is unfinished.
4. If not (if there are no empty spaces on the board), the game is a draw.

Determining
the winner

True
Player one wins?

False
True
Player two wins?

False
True
Are there empty
spaces?

False

Unfinished Draw Player two wins Player one wins

Figure 15-3 Determining the winner

189
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents

How to write complex conditional decisions


As explained in Section 4, the determination of the winner of a tic-tac-toe game is actually quite
complicated. For example, suppose you have three conditions: is_A, is_B, and is_C (think of these as
variables or functions that take a value of True or False). The part of the function that decides if all of
them are True is written as:
return is_A and is_B and is_C:
You could also nest the if statements as follows:
if is_A:
if is_B:
if is_C:
return True
return False
Also, you could write it as:
if not is_A:
return False
if not is_B:
return False
if not is_C:
return False
return True
If you use that last way of writing it, then you could also write it as:
conditions = [is_A, is_B, is_C]
for c in conditions:
if not c:
return False
return True
In the last method, even if the number of conditions to be checked increases, the decision part can be
written succinctly by using a for statement.

Exercise 15-1 Programming Branching with Complicated Condition


Based on the examples above, write a function that returns True if any of is_A, is_B, or is_C is True.

Progression of the game


Let's consider the flow of the main program. Input and output are done in the Python shell in the
form of characters. You'll see how easy it is to implement using the functions you defined earlier.

190
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents

 Initialize the game


 Display the board
 Repeat the following until the game is won, lost, or drawn:
 Prompt the user for the input of the active player until a valid input is obtained.
 Get input from the active player
 Update the board
 Display the board
 Determine if the game is won, lost, or drawn
 Show the result and escape the main loop if the game is over
 Change the player's turn

15.5 Implementation of the program


1) Source code structure
Once the design is complete, you can start fleshing out the program. Check to see that your Python
source code looks something like the following.

Import the necessary modules

Define constants and variables

Functions relating to the turn

Functions to test functions relating to the turn

Functions relating to the board

Functions to test functions relating to the board

Functions relating to board records

Functions to test functions relating to board records

Functions for game progression

Main program

Figure 15-4 Overall source code structure

2) Example code (tic_tac_toe.py)


An example implementation of the program is shown below. Some notes concerning the way things
were implemented and the notation are explained below.
 The program is implemented in the order shown in Figure 15-4.

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

Program 15-1 Tic-tac-toe program example (Part 1: Global variables)

Row Source code


1 #
2 #␣Tic-tac-toe
3 #
4 #␣There␣are␣no␣modules␣that␣need␣to␣be␣imported.
5 #
6 #␣Define␣constants
7 #
8 #
9 #␣Create␣a␣game␣record␣in␣play()␣(needs␣to␣be␣completed).
10 #
11 'This␣is␣a␣tic-tac-toe␣program'
12 OPEN␣=␣0
13 FIRST␣=␣1
14 SECOND␣=␣2
15 DRAW␣=␣3
16 #
17 #␣Constant␣variable
18 #
19 turn␣=␣FIRST
20 board␣=␣[[0,0,0],[0,0,0],[0,0,0]]
21 #
22 #␣Test␣board␣records
23 #
24 log1␣=␣[[0,␣0],␣[1,␣1],␣[1,␣0],␣[2,␣0],␣[0,␣2],␣[0,␣1],␣[2,␣1],␣[2,␣2],␣[1,␣2],␣
[DRAW]]
25 log2␣=␣[[0,␣0],␣[1,␣0],␣[1,␣1],␣[2,␣2],␣[0,␣1],␣[2,␣0],[FIRST]]
26 log3␣=␣[[0,␣1],␣[0,␣0],␣[2,␣1],␣[1,␣1],␣[2,␣2],␣[2,␣0],␣[1,␣0],␣[0,␣2],[SECOND]]

193
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents

Program 15-2 Tic-tac-toe program example (Part 2: Turn-related functions)

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

Program 15-3 Tic-tac-toe program, example (Part 3: Board-related functions part 1)

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

Program 15-4 Tic-tac-toe program, example (Part 4: Board-related functions part 2)

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

Program 15-5 Tic-tac-toe program, example (Part 5: Board testing functions 1)

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

Program 15-6 Tic-tac-toe program, example (Part 6: Board testing functions 2)

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

Program 15-7 Tic-tac-toe program example (Part 7: Game record-related functions)

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

3) Testing the program


After reading the above program and running it in the Python shell, run the test functions from the
shell to see how the program works. The test functions provided are as follows, in order from top to
bottom.
test_turn()
test_board1()
test_board2()
test_board3()
test_log()
test_all()

4) Running the program


After running the above program, call the play() function from the Python shell and try playing tic-
tac-toe.
play()

Exercise 15-2 Relationship of functions in tic-tac-toe program

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 ↑ ↑

Exercise 15-3 Getting the game record


Extend the above program to collect the game record of the game in the play() function. You can also
replay the game record after the winner is determined.

205
15 Learning Program Development with Tic-Tac-Toe Next Chapter Table of Contents

15.6 Test of skills


Using the methods you have learned so far, try the following as a test of your skills.
 Create a GUI-based tic-tac-toe game instead of a CUI based one, using tkinter.
 By using classes, implement functions to control the turn, the board, the game record, etc. as
methods in the classes.
 Extend the game to be played by a computer on one side of the board, rather than by two
humans.
 Develop a similar program for the game of Reversi instead of tic-tac-toe.

15.7 Various topics related to program development

What you can understand from a test


Computer programs usually have to work properly in a virtually infinite number of cases. For
example, the number of possible games of tic-tac-toe is quite large. For this reason, you must
consider the following points concerning tests:
 It is easy to see that a program that does not pass the test has a mistake in it; however,

 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

The V-model of software development


In the first half of the development of a program, even a small example like the tic-tac-toe program
you made above, the requirements of the final product (specifications) are clear. Then, you flesh out
the specifics of the program step by step, including the functions to be implemented. In the second
half of development, you repeatedly perform tests on non-interdependent functions in sequence,
which eventually leads to the conclusion of programming after many iterations.
This process is represented by a V-shape as shown in the figure below, and is called the V-model of
software development.
Because of the V-shape structure, the distance from design to implementation and testing is much
greater in the upper part of the V-shape. This means that inappropriate design in the upper part of the
V takes longer to be discovered in implementation and testing, and requires more diligent reworking.
There are two possible directions for successful software development detailed below. The latter is
called agile development.
 Define required specifications, and reduce reworking
 Narrow down the specifications and develop quickly, then add features if necessary.

It is not
Specifications supposed to be Creating value
(“This is the software I want”) like this through the
product

Backtracking: the further


up the line the greater
the impact
Design
Refinement in
stages Implementation
Build up from the bottom

Figure 15-5 The V-Model of Software Development

207
16 Academic Use of Python Next Chapter Table of Contents

16. Academic Use of Python


16.1 Learning goals of this chapter
One of the reasons why Python has attracted so much attention is that it offers a wide range of
libraries suitable for numerical computation, as well as for other academic applications. We will use
the following three libraries in this chapter to learn the basics of working with data (in NumPy and
pandas), as well as the basics of graphing (in Matplotlib).
Each of them is a quite sophisticated package, and you need to have some expertise in the fields in
which these packages are applied in order to fully utilize them, so you will learn only the basics here.
1. NumPy: A basic package for numerical computation in the field of science and technology
SciPy: A library for more advanced numerical computations
2. Matplotlib: A package for plotting data on graphs
3. pandas: a data analysis package
These are interrelated, as shown in the figure below.

Plotting with DataFrame and


other plot methods
pandas
Creating a
DataFrame from
Creating a Series or
a dictionary that
DataFrame from an ndarray
has lists as its NumPy
values Plotting with the plot
method in pyplot Matplotlib
Create an ndarray from a list

Python
Plot a list or other data with
the plot method in pyplot

Figure 16-1 The relationship between NumPy, Matplotlib and pandas

16.2 Using a custom name when importing


The following custom names are often used for importing packages such as NumPy, Pandas,
Matplotlib. You will use these custom names in this text.
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd

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.

Generating multi-dimensional arrays


While Python uses lists to group data together, NumPy uses its own data format, the ndarray (aka
array).

1) Generating from a list


import numpy as np
data1 = [1, 2, 3]
arr1 = np.array(data1) # 1-dimensional data
data2 = [[1,2,3],[4,5,6]]
arr2 = np.array(data2)

2) Create an array in which all elements are zero


np.zeros(5) # A 1D array of with 5 elements
array([0., 0., 0., 0., 0.])
np.zeros((2,2)) # A 2D array of with a size of (2,2); note the double
parentheses ()
array([[0., 0.],
[0., 0.]])
a = np.array([[1,2,3],[4,5,6]])
np.zeros_like(a) # Same size as array a
array([[0, 0, 0],
[0, 0, 0]])
An array consisting only of 1's can be created using ones and ones_like.

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.

Accessing ndarray elements


The elements of an ndarray can be accessed using [] in the same way as a list. These ndarrays also
start at an index of 0.
arr1 = np.array([1,2,3])
arr1[0]
1
arr1[1] = 1
arr1
array([1,1,3])
For multi-dimensional arrays you can also use [,] notation instead of [][].
arr2[0][0]
arr2[0,0]

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

Extraction of elements satisfying the conditions


You can extract the elements that satisfy the conditions in the following way.
arr1 = np.array([1,2,3,4,5])
cond = arr1 > 2 # Generate an array of elements that satisfy the
conditions
cond
array([False, False, True, True, True])
arr1[cond] # Slice based on the defined conditions
array([3, 4, 5])

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

backend: graph output environment


Matplotlib allows you to choose how to output the graph. In this section, we see how to use tkagg,
which is a tkinter-based environment for IDLE.
 In Matplotlib, the environment that actually outputs the graph is called a backend. There are
various backends available.
 tkagg is a backend that uses Tkinter to output graphs.
 In the IDLE environment, it is specified using the use() function after importing matplotlib.
import matplotlib
matplotlib.use('tkagg')
 The use() function must be specified before importing the matplotlib.pyplot plotting module.
 In IPython and Jupyter Notebook (which uses IPython), before using matplotlib, you can specify
the following, depending on the backend you want to use.
%matplotlib notebook
%matplotlib tk

212
16 Academic Use of Python Next Chapter Table of Contents

Text output in Japanese


 The standard matplotlib font does not support Japanese characters, so they will be displayed
as boxes (□).
 The ttc font can now be used in matplotlib version 3.1 or later. If you are using this version or
a newer one, you do not need to install additional fonts 1.
 There are several ways to specify fonts, but here we show how to specify them all at once in
the program.
 If you have installed additional fonts, first delete the fontList.json in the .matplotlib folder in
the user's folder if it is old.

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

Raw Source Code


1 import␣matplotlib
2 #␣Set␣tkinter␣as␣the␣output␣destination␣before␣importing␣pyplot
3 matplotlib.use('tkagg')
4 import␣matplotlib.pyplot␣as␣plt
5 #␣Enable␣matplotlib␣to␣display␣Japanese␣characters.
6 #␣Yu␣Gothic␣can␣be␣used␣in␣matplotlib␣version␣3.1␣or␣later
7 matplotlib.rc('font',␣**{'family':'Yu␣Gothic'})
8 #␣For␣Mac␣User,␣try␣the␣following␣instead␣of␣the␣above␣line
9 #␣matplotlib.rc('font',␣**{'family':'Hiragino␣Maru␣Gothic␣Pro'})
10 #␣The␣following␣is␣an␣example␣plot
11 data␣=␣[1,2,3]
12 plt.plot(data)
13 plt.title('タイトル')
14 plt.show()

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

Figure 16-2 Execution of Program 16-1

Setting the Title, Axis Labels, and Linestyle


 The function to set the title of the graph is title.
 The function to set the x-axis labels is xlabel.
 The function to set the y-axis labels is ylabel.
 The linestyle can be specified as an argument of the plot function.
 By specifying the color, and linestyle, and marker as strings
 By specifying the color, linestyle, linewidth, etc. as arguments.
 Example (the relevant part only)
plt.plot([1,2,3], 'k-') # A black solid line
plt.plot([2,3,4], 'r--') # A red dashed line
plt.plot([3,4,5], 'b--o') # A blue dashed line with circular markers (〇)
plt.title('Title')
plt.xlabel('Horizontal Axis ')
plt.ylabel('Vertical Axis ')
plt.show()

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

Figure 16-3 Example of Matplotlib usage

215
16 Academic Use of Python Next Chapter Table of Contents

Program 16-2 use_matplotlib.py

Row Source code


1 #
2 #␣The␣basic␣way␣to␣use␣matplotlib
3 #
4 import␣matplotlib
5 #
6 #␣set␣tkinter␣to␣use␣(as␣the␣output␣destination)␣before␣importing␣pyplot
7 #
8 matplotlib.use('tkagg')
9 import␣matplotlib.pyplot␣as␣plt
10 #
11 #␣Enable␣matplotlib␣to␣display␣Japanese␣characters.
12 #␣uncomment␣one␣apropriate␣for␣your␣environment
13 #
14 #␣For␣Windows
15 matplotlib.rc('font',␣**{'family':'Yu␣Gothic'})
16 #␣For␣Campus␣PC␣Terminal
17 #matplotlib.rc('font',␣**{'family':'IPAPGothic'})
18 #␣For␣macOS
19 #matplotlib.rc('font',␣**{'family':'Hiragino␣Maru␣Gothic␣Pro'})
20 #
21 #␣Draw␣a␣line␣graph␣with␣three␣lines
22 #
23 plt.plot([1,2,3],'k-',label='Series␣1')
24 plt.plot([2,3,4],'r--',label='Series␣2')
25 plt.plot([3,4,5],'b--o',label='Series␣3')
26 #
27 plt.title('Title')
28 plt.xlabel('Horizontal␣Axis␣')
29 plt.ylabel('Vertical␣Axis␣')
30 plt.legend()␣#␣Legend
31 plt.show()

2) Drawing a scatter plot


A scatter plot can be drawn by giving the x-axis data and y-axis data to the scatter function of pyplot.

• use_matplotlib_scatter.py

216
16 Academic Use of Python Next Chapter Table of Contents

Title

Data 1
Data 2

Vertic

• Horizontal axis

Figure 16-4 Drawing a scatter plot

Program 16-3 use_matplotlib_scatter.py

Row Source code


1 #
2 #␣Draw␣a␣scatter␣plot␣with␣matplotlib
3 #
4 import␣matplotlib
5
6 matplotlib.use('tkagg')
7 import␣matplotlib.pyplot␣as␣plt
8 import␣numpy␣as␣np
9 #
10 #␣Enable␣matplotlib␣to␣display␣Japanese␣characters.
11 #␣uncomment␣one␣apropriate␣for␣your␣environment
12 #
13 #␣For␣Windows
14 matplotlib.rc('font',␣**{'family':'Yu␣Gothic'})
15 #␣For␣Campus␣PC␣Terminal
16 #matplotlib.rc('font',␣**{'family':'IPAPGothic'})
17 #␣For␣macOS
18 #matplotlib.rc('font',␣**{'family':'Hiragino␣Maru␣Gothic␣Pro'})
19 #
20 #␣Create␣random␣data
21 #
22 datax␣=␣np.random.randn(100)
23 datay␣=␣datax␣+␣np.random.randn(100)*0.3
24 #
25 #␣Draw␣a␣scatter␣plot.
26 #
27 plt.scatter(datax,datay,label='Data1')
28 #
29 #␣Create␣another␣set␣of␣data

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

Figure 16-5 Drawing a Histogram

218
16 Academic Use of Python Next Chapter Table of Contents

Program 16-4 use_matplotlib_hist.py

Row Source code


1 #
2 #␣Draw␣a␣histogram␣with␣matplotlib
3 #
4 import␣matplotlib
5 #
6 #␣Set␣tkinter␣as␣the␣output␣destination␣before␣importing␣pyplot
7 #
8 matplotlib.use('tkagg')
9 import␣matplotlib.pyplot␣as␣plt
10 import␣numpy␣as␣np
11 #
12 #␣Enable␣matplotlib␣to␣display␣Japanese␣characters.
13 #␣uncomment␣one␣apropriate␣for␣your␣environment
14 #
15 #␣For␣Windows
16 matplotlib.rc('font',␣**{'family':'Yu␣Gothic'})
17 #␣For␣Campus␣PC␣Terminal
18 #matplotlib.rc('font',␣**{'family':'IPAPGothic'})
19 #␣For␣macOS
20 #matplotlib.rc('font',␣**{'family':'Hiragino␣Maru␣Gothic␣Pro'})
21 #
22 #␣Create␣a␣histogram
23 #
24 data␣=␣np.random.randn(1000)
25 plt.hist(data,bins=20)
26 #
27 #␣Set␣the␣title␣and␣axis␣labels
28 #
29 plt.title('Histogram')
30 plt.xlabel('Value of Data')
31 plt.ylabel('Data Frequency')
32 #
33 #␣Display
34 #
35 plt.show()

4) Drawing Multiple Graphs


Matplotlib allows you to draw multiple graphs side by side in the following manner.
 Obtain a Figure object using pyplot's figure function.
 Add a subplot to the Figure object with pyplot's add_subplot function. Save the result to a
variable.
 Adjust the spacing of the subplots with pyplot's subplots_adjust function.

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

Line graph Scatter plot

Data 1
Data 2

Attribute 2
Location

Time Attribute 1

Histogram
Frequency

Data value

Figure 16-6 Drawing multiple graphs

Program 16-5 use_matplotlib_subplot.py

Row Source code


1 #
2 #␣Example␣using␣subplot
3 #
4 import␣matplotlib
5 matplotlib.use('tkagg')
6 import␣matplotlib.pyplot␣as␣plt
7 import␣numpy␣as␣np
8 #
9 #␣Enable␣matplotlib␣to␣display␣Japanese␣characters.
10 #␣uncomment␣one␣apropriate␣for␣your␣environment
11 #
12 #␣For␣Windows
13 matplotlib.rc('font',␣**{'family':'Yu␣Gothic'})
14 #␣For␣Campus␣PC␣Terminal
15 #matplotlib.rc('font',␣**{'family':'IPAPGothic'})
16 #␣For␣macOS
17 #matplotlib.rc('font',␣**{'family':'Hiragino␣Maru␣Gothic␣Pro'})
18 #
19 #␣Create␣3␣subplots,␣and␣adjust␣the␣spacing

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

1) Create from an array in numpy


import numpy as np
import pandas as pd
d = np.array([[1,2,3],[4,5,6],[7,8,9]])
df = pd.DataFrame(d,columns=['a' ,'b' ,'c'])
df
a b c
0 1 2 3
1 4 5 6
2 7 8 9
The column and row names can be found using:
df.columns
df.index
respectively.

222
16 Academic Use of Python Next Chapter Table of Contents

2) Create from a dictionary where the values are lists.


df = pd.DataFrame({'a': [1,4,7], 'b':[2,5,8], 'c':[3,6,9]})
df
a b c
0 1 2 3
1 4 5 6
2 7 8 9
A dictionary is a Python data type that consists of a set of key-value pairs.
dic = {'a':1, 'b':2, 'c':3}
You can search for values using the keys.
dic['a']
1

Importing csv files


 You can create a DataFrame by reading data A a spreadsheet saved as a csv file.
df = pd.read_csv("file name")
 The first row is treated as the column name.
 If you want to read all the data, specify the following options.
header = None or names = [list of column names]
 To read a file containing Japanese characters on Windows, specify the Japanese character
encoding.
encoding = 'SHIFT-JIS'
 If you use Japanese character encoding for column names, an error will occur when specifying
data in column names.
 sample.csv is show below.

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.

Table 16-1 sample.csv

ID Japanese English Mathematics Science Social Studies


A 91 69 100 82 94
B 80 60 45 52 46
C 92 92 76 73 97
D 58 50 60 71 77
E 58 75 96 96 94
F 92 89 86 82 74
G 97 87 59 55 56
H 62 73 52 60 74
I 73 85 41 49 75
J 61 61 49 51 63
K 49 56 58 63 85
L 42 50 56 59 78
M 52 66 50 49 43
N 88 72 52 64 48
O 72 75 56 54 80
P 94 90 61 58 67
Q 95 85 72 68 43
R 70 85 68 62 81
S 74 85 96 96 53
T 65 53 64 67 75

By executing the program we obtain the following:


ID Japanese English Mathematics Science Social Studies Total
0 A 91 69 100 82 94 436
1 B 80 60 45 52 46 283
2 C 92 92 76 73 97 430
3 D 58 50 60 71 77 316
4 E 58 75 96 96 94 419
5 F 92 89 86 82 74 423
6 G 97 87 59 55 56 354

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

Program 16-6 use_read_csv.py

Row Source code


1 import␣numpy␣as␣np
2 import␣pandas␣as␣pd
3 import␣os
4 #
5 #␣Navigate␣to␣the␣folder␣with␣the␣data
6 #
7 #␣pandas␣does␣not␣handle␣Japanese␣file␣names␣well
8 #
9 print("Current folder: "+os.getcwd())
10 folderpath␣=␣input("Enter␣folder␣path:␣")
11 os.chdir(folderpath)
12 df␣=␣pd.read_csv("sample.csv")
13 #
14 #␣Sum␣horizontally␣(axis␣=␣1)␣and␣create␣a␣column␣called␣Total
15 df['Total']␣=␣df.sum(axis=1␣numeric_only=True)
16 #␣Display␣the␣DataFrame␣df
17 print(df)
18 #␣Display␣summary␣statistics␣for␣DataFrame␣df
19 print(df.describe())

Display summary statistics


The describe method can be used to display summary statistics.

Plotting Data in Pandas


Plotting in Pandas is done by calling the plot method in the DataFrame. (use_DadaFrame_plot.py)
df.plot() # Line graph
df.plot.bar(stacked=True) # stacked bar graph
df.plot.scatter('Japanese','English') # Scatter plot with defined columns
df['Japanese'].plot.hist() # Histogram with defined columns

226
16 Academic Use of Python Next Chapter Table of Contents

Figure 16-7 Graphing with pandas

Program 16-7 use_DadaFrame_plot.py

Row Source code


1 import␣numpy␣as␣np
2 import␣pandas␣as␣pd
3 import␣os
4 import␣matplotlib
5 matplotlib.use('tkagg')
6 import␣matplotlib.pyplot␣as␣plt
7 #
8 #␣Navigate␣to␣the␣folder␣with␣the␣data
9 #
10 #␣set␣adequate␣path␣for␣your␣environment
11 folderpath␣=␣input("Enter␣folder␣path:␣")
12 os.chdir(folderpath)
13 #
14 df␣=␣pd.read_csv("sample.csv")
15 #
16 #
17 #␣Line␣graph

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

16.6 Practice task


np_matplotlib.py is a program that uses Numpy and matplotlib to draw graphs of powers of 1 to 4.

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

Figure 16-8 A power graph and an approximation of a sawtooth wave by summing


trigonometric functions

Program 16-8 Drawing graphs of powers of 1 to 4 with Numpy and Matplotlib


(use_matplotlib_power_function.py)

Row Source code Notes


1 #␣Example␣of␣plotting␣data␣in␣Numpy
2 import␣matplotlib Preparing␣matplotlib
3 matplotlib.use('tkagg')
4 import␣matplotlib.pyplot␣as␣plt Preparing␣numpy
5 import␣numpy␣as␣np Setting␣the␣font␣in␣matpl
6 #␣For␣Windows otlib
7 matplotlib.rc('font',␣**{'family':'Yu␣Gothic'})
8 #␣For␣Campus␣PC␣Terminal
9 #matplotlib.rc('font',␣**{'family':'IPAPGothic'})
10 #␣For␣macOS
11 #matplotlib.rc('font',␣**{'family':'Hiragino␣Maru␣Go
thic␣Pro'})
12 #
13 #␣Plot␣x␣to␣the␣1st␣to␣4th␣power
14 #
15 steps␣=␣100
16 order␣=␣4
17 maxx␣=␣2
18 #
19 #␣Create␣a␣matrix␣with␣a␣steps␣row␣and␣order␣column␣
with␣element␣values␣set␣to␣0
20 #
21 datalist␣=␣np.zeros((steps,␣order))
22 #
23 #␣List␣for␣the␣legend
24 #
25 legend_label=[]

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. Review, and Where to Go From Here


17.1 Learning goals of this chapter
1. This is the last part of the course. In this chapter, we will look back at what we have learned so
far.
2. We learned how to use the IDLE integrated environment with Python exercises. We chose IDLE
because it has limited functionality and is easy to learn, but we will also learn about what else is
available here.
3. We will then think about how to apply what you have learned.

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?

17.3 Shuhari (three stages of mastery) - “Obey,


Digress, Separate”
At the end of the semester, we asked students who had taken this class for their opinions. Several of
them said, “I can read Python programs now, but I don't feel like I can write them myself.” In fact,
“being able to read” is a big step forward, and if you can run the program while understanding it, it
will be easy to modify it a little. As you gain more experience, you will gradually be able to write
your own programs.
In Japanese martial arts, we use the term Shuhari (lit. “Obey, Digress, Separate”). In programming, if
you read the programs written by your predecessors, execute them, play around with them by
changing them slightly, and apply them, you will accumulate knowledge and eventually be able to do
creative programming.

17.4 Python environments


In this class, we used IDLE as an integrated Python environment because of its simple structure and
ease of use for beginners. IDLE is said to be a “throw-away” environment because of its simplicity.
Python, on the other hand, has a variety of usage environments.
• Jupyter Notebook and Spider are included in Anaconda.
• These environments run in IPython, a more interactive execution environment than the
Python shell.
• A style of editors and command line execution suited to Python (python, IPython) is also

231
17 Review, and Where to Go From Here Next Chapter Table of Contents

used.

17.5 Adding modules


One of the main features of Python is that many people have developed a variety of libraries in the
language. There is a lot of information on the web and elsewhere about specific application
examples, but in order to use them you need to add live modules: in Anaconda you can use the conda
command to add modules that are not covered by anaconda, or the pip command if you use Python
as a distribution package. In Anaconda, use the conda command, and if you are using Python as a
distribution package, use the pip command to add modules.

17.6 Topics not covered in this book


Python is a programming language with a wide range of applications, but each application requires
knowledge of the relevant area of application. NumPy and pandas, which were introduced in this
book, cannot be used without knowledge of numerical computation and statistical processing. For
this reason, we have not covered some topics that require knowledge of related fields. The following
are some examples.
While the World Wide Web (WWW) is a very important area to apply one's programming skills, this
requires knowledge of different programming languages such as HTML to write Webpages or SQL
to manipulate databases. As such, WWW is not covered here as it can cause confusion for beginner
students learning Python.
When thinking of specific things related to programming, things like the following come to mind:
Python boasts a host of libraries with thorough and widely-publicized documentation and tutorials.
Students should study things that align with their interests.

 Network and web-related topics


 Multimedia topics such as image processing
 Topics related to databases
 Topics related to the IoT as it pertains to microcomputer boards and electronic manufacturing
 Programming for geographical information systems
 Topics related to artificial intelligence such as machine learning

17.7 Gratitude and repayment - how to make use of


what you have learned
There are many people who do carpentry at home. If you can do carpentry, you can solve problems
in your home by making simple furniture and other DIY things. On the other hand, working with
metal, which requires machines such as drilling machines, lathes, and milling machines, can be a bit
more challenging. So, there are not many people who try to make DIY metal products 1. 19F20F

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

18. Appendix: Useful notes on Python and IDLE


18.1 Useful notes on Python
 help() function:Allows you to read the description of a module or function supplied as an
argument.
 globals(): Displays globally defined variables and other information.
 id(x): Shows the identity of object x. You can check if different variables point to the same
object.
 type(x): Shows the type of object x. You can check what type of object is assigned to the
variable.

18.2 Pay attention to file names


Do not create files with file names that are the same as modules to be imported.
Python searches for modules in a specific folder. The same folder as the file to be executed is the
target of the module search. For example, if you are using the turtle module and you have a file
named turtle.py, Python will incorrectly assume that this file is a module.

18.3 IDLE notes: Python shell hotkeys


 Ctrl-C: Stop a running program
 Ctrl-D: (when input in the terminal) End file
 Note: In the shell interactive mode, this will exit the shell.
 TAB key:Smart indent
 If pressed after a character, it will display auto-complete suggestions
 ALT-P: Go back in history (you can reuse lines you have already typed, etc. P stands for
previous)
 ALT-N: Go forward in history (you can reuse lines you've already typed; N stands for next)
 Script execution
 After executing a script created in the editor, the environment will be in the interactive
mode. You can call functions and check global variables in the script.

18.4 IDLE notes: Editor


Hotkeys
 Ctrl-]: Indent the selected range
 Ctrl-[: Unindent the indentation of the selected range

234
18 Appendix: Useful notes on Python and IDLE Next Chapter Table of Contents

 ALT-3: Comment out the selected range


 ALT-4: Undo comment out for the selected range
 Ctrl-BS: Delete the word to the left
 Ctrl-Del: Delete the word to the right
The following hotkey operations generally available in Windows are also useful.
 Ctrl-X: Cut
 Ctrl-C: Copy
 Ctril-V: Paste

Show Line Number


Since Python 3.8, the IDLE editor can show line numbers next to the source code, by selecting Show
Line Number from either the Options menu, or by selecting it under the General tab in Configure
IDLE menu.

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

19. Appendix: How to Read Error Messages in


IDLE/Python
As a program gets more complex, even a simple mistake in copying and executing the source code
can result in a variety of errors. There are two ways that errors are displayed in IDLE:
 Syntax errors in the source code displayed by the IDLE editor
 Run-time errors displayed by the Python shell

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.

19.1 Errors displayed by the IDLE editor


Syntax errors are checked before execution and displayed by the IDLE editor.

Example Program 1 - Missing Colon


Program 19-1 missing_colon_error.py

Row Source code Notes


1 #
2 #␣This␣code␣will␣give␣you␣some␣experience␣with␣errors
3 #␣There␣is␣no␣colon␣(:)␣at␣the␣end␣of␣line␣11
4 #
5 def␣func1(x):
6 ␣␣␣␣x␣=␣x*x
7 ␣␣␣␣return␣x
8 #
9 #␣There␣is␣no␣colon␣(:)␣at␣the␣end␣of␣the␣next␣line
10 #
11 def␣func2(y,␣x) You need to use a colon
12 ␣␣␣␣xx␣=␣func1(x) (:) at the end here
13 ␣␣␣␣return␣y␣+␣xx
14
15 #␣Main␣from␣here
16 a␣=␣1
17 b␣=␣2
18 print(a,␣b,␣func2(a,␣b))
In this example, the dialog “expected ‘:’ ” will be displayed and the offending part of the code will be

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

shown in red, as shown in the following figure.

Example Program 2 - Missing Parentheses


Program 19-2 missing_parentheses_error.py

Row Source code Notes


1 #
2 #␣This␣code␣will␣give␣you␣some␣experience␣with␣errors
3 #␣Missing␣a␣closing␣parenthesis
4 #
5 def␣func1(x):
6 ␣␣␣␣x␣=␣x*x
7 ␣␣␣␣return␣x
8 #
9 #␣
10 #
11 def␣func2(y,␣x):
12 ␣␣␣␣xx␣=␣func1(x)
13 ␣␣␣␣return␣y␣+␣xx
14
15 #␣The␣main␣part␣starts␣here;␣the␣last␣line␣is␣missing␣a␣cl
osing␣parenthesis
16 a␣=␣1
17 b␣=␣2
18 print(a,␣b,␣func2(a,␣b) Missing a closing
parenthesis
In this example, the dialog “’(’ was never closed ” is shown, and the corresponding part is displayed
in red, as shown in the following figure.

237
19 Appendix: How to Read Error Messages in IDLE/Python Next Chapter Table of Contents

Example Program 3 - Indentation Offset (Insufficiency)


Program 19-3 insufficient_indentation_error.py

Row Source code Notes


1 #
2 #␣This␣code␣will␣give␣you␣some␣experience␣with␣errors
3 #␣Indentation␣offset
4 #
5 def␣func1(x):
6 ␣␣␣␣x␣=␣x*x
7 ␣␣␣␣return␣x
8 #
9 #␣The␣indent␣of␣line␣13␣is␣offset
10 #
11 def␣func2(y,␣x):
12 ␣␣␣␣xx␣=␣func1(x)
13 ␣␣␣return␣y␣+␣xx This indent needs one more
14 space
15 #␣Main␣from␣here
16 a␣=␣1
17 b␣=␣2
18 print(a,␣b,␣func2(a,␣b))
In this example, the indentation of line 13 is missing one character, so the message “unindent does
not match outer indentation level” is displayed. It warns that the indentation is insufficient, and that
there is no matching level.

238
19 Appendix: How to Read Error Messages in IDLE/Python Next Chapter Table of Contents

Example Program 4 - Indentation Offset (Excess)


Program 19-4 excess_indentation_error.py

Row Source code Notes


1 #
2 #␣This␣code␣will␣give␣you␣some␣experience␣with␣errors
3 #␣Indentation␣offset
4 #
5 def␣func1(x):
6 ␣␣␣␣x␣=␣x*x
7 ␣␣␣␣return␣x
8 #
9 #␣The␣indent␣of␣line␣13␣is␣offset
10 #
11 def␣func2(y,␣x):
12 ␣␣␣␣xx␣=␣func1(x)
13 ␣␣␣␣␣return␣y␣+␣xx There is an extra space
14 here
15 #␣Main␣from␣here
16 a␣=␣1
17 b␣=␣2
18 print(a,␣b,␣func2(a,␣b))
This time the indentation has one character too many, so the error says “unexpected indent.” This can
be interpreted to mean that the indentation is unexpected because there is no block that requires
further indentation.

239
19 Appendix: How to Read Error Messages in IDLE/Python Next Chapter Table of Contents

19.2 Errors displayed in Python shell when executing


code

Example Program 5 - Referencing an Undefined


Variable
Program 19-5 referencing_undefined_variable_error.py

Row Source code Notes


1 #
2 #␣This␣code␣will␣give␣you␣some␣experience␣with␣errors
3 #␣Line␣6␣refers␣to␣a␣variable␣that␣is␣not␣defined
4 #
5 def␣func1(x):
6 ␣␣␣␣x␣=␣xx␣#␣This␣variable␣does␣not␣exist Refers to undefined
7 ␣␣␣␣return␣x variable xx
8
9 def␣func2(y,␣x):
10 ␣␣␣␣xx␣=␣func1(x)
11 ␣␣␣␣return␣y␣+␣xx
12
13 #␣Main␣from␣here
14 a␣=␣1
15 b␣=␣2
16 print(a,␣b,␣func2(a,␣b))

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

Traceback (most recent call last):


File "M:\Documents\Python Scripts\error-ex1.py", line 16, in <module>
print(a, b, func2(a, b))
File "M:\Documents\Python Scripts\error-ex1.py", line 10, in func2
xx = func1(x)
File "M:\Documents\Python Scripts\error-ex1.py", line 6, in func1
x = xx # This variable does not exist
NameError: name 'xx' is not defined. Did you mean: 'x'?
>>>

Example Program 6 - Wrong Argument Type


Program 19-6 wrong_argument_type_error.py

Row Source code Notes


1 #␣This␣code␣will␣give␣you␣some␣experience␣with␣errors
2 #␣When␣calling␣math.sin(),␣the␣argument␣is␣a␣string
3 #
4 import␣math
5 def␣func1(x):
6 ␣␣␣␣xx␣=␣math.sin(x)
7 ␣␣␣␣return␣xx The value of x is the
8 string "2".
9 def␣func2(y,␣x):
10 ␣␣␣␣xx␣=␣func1(x)
11 ␣␣␣␣return␣y␣+␣xx
12
13 #␣Main␣from␣here
14 a␣=␣1
15 b␣=␣"2"
16 print(a,␣b,␣func2(a,␣b)) set b a string "2" and
pass to func2

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.

Traceback (most recent call last):


File "M:\Documents\Python Scripts\error-ex2.py", line 17, in <module>
print(a, b, func2(a, b))
File "M:\Documents\Python Scripts\error-ex2.py", line 11, in func2
xx = func1(x)
File "M:\Documents\Python Scripts\error-ex2.py", line 7, in func1
xx = math.sin(x)
TypeError: must be real number, not str
>>>

241
19 Appendix: How to Read Error Messages in IDLE/Python Next Chapter Table of Contents

Example Program 7 - Incorrect Indentation in a Class


Program 19-7 incorrect_indentation_in_class_error.py

Row Source code Notes


1 #
2 #␣This␣code␣will␣give␣you␣some␣experience␣with␣errors
3 #␣Indentation␣within␣a␣class
4 #
5 import␣math
6 import␣tkinter␣as␣tk
7 class␣MyFrame(tk.Frame):
8 ␣␣␣␣def␣__init__(self,␣master=None):
9 ␣␣␣␣␣␣␣␣super().__init__(master)
10 ␣␣␣␣␣␣␣␣self.b␣=␣tk.Button(self,␣text="Try!",command=self.do)
␣␣␣␣␣␣␣␣self.b.grid(row=0,␣column=0)
11 #
12 #␣The␣indent␣below␣is␣one␣level␣too␣deep
13 #
14 ␣␣␣␣␣␣␣␣def␣do(self):
15 ␣␣␣␣␣␣␣␣␣␣␣␣self.b.configure(text="Did") This method will
16 end up in the
17 definition of the
18 root=␣tk.Tk() __init__ method.
19 f␣=␣MyFrame(root)
20 f.pack()
21 tk.mainloop()

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.

Traceback (most recent call last):


File "M:/Documents/Python Scripts/error-ex3.py", line 20, in <module>
f = MyFrame(root)
File "M:/Documents/Python Scripts/error-ex3.py", line 10, in __init__
self.b = tk.Button(self, text="Try!", command=self.do)
AttributeError: 'MyFrame' object has no attribute 'do'. Did you mean: '_do'?
>>>

242
19 Appendix: How to Read Error Messages in IDLE/Python Next Chapter Table of Contents

Example Program 8 - Incorrect Optional Argument


Program 19-8 incorrect_optional_argument_error.py

Row Source code Notes


1 #
2 #␣This␣code␣will␣give␣you␣some␣experience␣with␣errors
3 #␣Incorrect␣widget␣option
4 #
5 import␣math
6 import␣tkinter␣as␣tk
7 class␣MyFrame(tk.Frame):
8 ␣␣␣␣def␣__init__(self,␣master=None):
9 ␣␣␣␣␣␣␣␣super().__init__(master)
10 ␣␣␣␣␣␣␣␣self.b␣=␣tk.Button(self,␣text="Try!",␣commend=self.do) it says "commend"
␣␣␣␣␣␣␣␣self.b.grid(row=0,␣column=0)
11 ␣␣␣␣def␣do(self):
12 ␣␣␣␣␣␣␣␣self.b.configure(text="Did")
13
14
15 root=␣tk.Tk()
16 f␣=␣MyFrame(root)
17 f.pack()
18 tk.mainloop()
This example uses a class definition that extends the Frame class in tkinter, but
the optional argument for the button widget in line 10 is spelled incorrectly. The
creation of the button widget b will fail, so only the tkinter window will be
displayed as shown in the figure on the right. It is difficult to see where the error
occurs because it is in the tkinter module, but from the error code ‘unknown
option “-commend”’ you can see that the error occurs when calling line 10, and
that an option is wrongly specified.

Traceback (most recent call last):


File "M:/Documents/Python Scripts/error-ex4.py", line 17, in <module>
f = MyFrame(root)
File "M:/Documents/Python Scripts/error-ex4.py", line 10, in __init__
self.b = tk.Button(self, text="Try!", commend=self.do)
File "M:\anaconda3\lib\tkinter\__init__.py", line 2645, in __init__
Widget.__init__(self, master, 'button', cnf, kw)
File "M:\anaconda3\lib\tkinter\__init__.py", line 2567, in __init__
self.tk.call(
_tkinter.TclError: unknown option "-commend"
>>>

Traceback (most recent call last):


File "M:/Documents/Python Scripts/error-ex4.py", line 17, in <module>
f = MyFrame(root)
File "M:/Documents/Python Scripts/error-ex4.py", line 10, in __init__

243
19 Appendix: How to Read Error Messages in IDLE/Python Next Chapter Table of Contents

self.b = tk.Button(self, text="Try!", commend=self.do)


File "M:\anaconda3\lib\tkinter\__init__.py", line 2645, in __init__
Widget.__init__(self, master, 'button', cnf, kw)
File "M:\anaconda3\lib\tkinter\__init__.py", line 2567, in __init__
self.tk.call(
_tkinter.TclError: unknown option "-commend"
>>>

Example Program 9 - Errors within Functions


Program 19-9 error-in-function.py

Row Source Code


1 #␣Error␣that␣occurs␣where␣the␣function␣is␣called
2 def␣fun1(x):
3 ␣␣␣␣"Returns␣the␣absolute␣value"
4 ␣␣␣␣return␣abs(x)
5 def␣fun2(x,␣y):
6 ␣␣␣␣"Returns␣the␣absolute␣value␣of␣the␣sum␣of␣the␣two␣arguments"
7 ␣␣␣␣z␣=␣x␣+␣y
8 ␣␣␣␣return␣fun1(z)
9 #␣Main␣program␣starts␣here
10 #␣This␣works␣properly
11 a␣=␣1
12 b␣=␣-5
13 print(a,␣b,␣fun2(a,␣b))
14 #␣The␣sum␣of␣a␣string␣of␣characters␣can␣be␣calculated,␣but
15 #␣one␣cannot␣take␣its␣absolute␣value
16 a=␣"X"
17 b␣=␣"Y"
18 print(a,␣b,␣fun2(a,␣b))

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

File "C:/Users/hjkit/Documents/Python Scripts/func-err.py", line 8, in fun2


return fun1(z)
File "C:/Users/hjkit/Documents/Python Scripts/func-err.py", line 4, in fun1
return abs(x)
TypeError: bad operand type for abs(): 'str'

>>>

245

You might also like