nes-num lines-num-old"> 19
+    "n = 10\n",
20
+    "r = 1 + 2 +  ... + n"
21
+   ]
22
+  },
23
+  {
24
+   "cell_type": "code",
25
+   "execution_count": 3,
26
+   "metadata": {},
27
+   "outputs": [
28
+    {
29
+     "name": "stdout",
30
+     "output_type": "stream",
31
+     "text": [
32
+      "enter a: 10\n",
33
+      "enter b: 30\n"
34
+     ]
35
+    },
36
+    {
37
+     "data": {
38
+      "text/plain": [
39
+       "'1030'"
40
+      ]
41
+     },
42
+     "execution_count": 3,
43
+     "metadata": {},
44
+     "output_type": "execute_result"
45
+    }
46
+   ],
47
+   "source": [
48
+    "a = input('enter a: ')\n",
49
+    "b = input('enter b: ')\n",
50
+    "c = a + b\n",
51
+    "c"
52
+   ]
53
+  },
54
+  {
55
+   "cell_type": "markdown",
56
+   "metadata": {},
57
+   "source": [
58
+    "# Lab 1.2\n",
59
+    "เขียน program ที่เก็บค่าส่วนต่างๆ ของรถยนต์ คันหนึ่งเช่น width, height, length , color และ เป็นสีแดงให้ print \"I love it\" ถ้าไม่ Goodbye\n",
60
+    "และถ้า width > 200 ให้ print \"very big car\""
61
+   ]
62
+  },
63
+  {
64
+   "cell_type": "code",
65
+   "execution_count": 8,
66
+   "metadata": {},
67
+   "outputs": [
68
+    {
69
+     "name": "stdout",
70
+     "output_type": "stream",
71
+     "text": [
72
+      "...\n",
73
+      "I love it\n"
74
+     ]
75
+    }
76
+   ],
77
+   "source": [
78
+    "car = {'w': 100, 'h':200, 'l':150, 'color': 'red'}\n",
79
+    "for k in car:\n",
80
+    "    if k == 'color':\n",
81
+    "        if car[k] == \"red\":\n",
82
+    "            print(\"I love it\")\n",
83
+    "        else:\n",
84
+    "            print(\"Goodbye\")\n",
85
+    "    if k == \"w\":\n",
86
+    "        if car[k] > 200:\n",
87
+    "            print(\"Very big car\")\n",
88
+    "        else:\n",
89
+    "            print(\"...\")\n",
90
+    "        "
91
+   ]
92
+  }
93
+ ],
94
+ "metadata": {
95
+  "kernelspec": {
96
+   "display_name": "Python 3",
97
+   "language": "python",
98
+   "name": "python3"
99
+  },
100
+  "language_info": {
101
+   "codemirror_mode": {
102
+    "name": "ipython",
103
+    "version": 3
104
+   },
105
+   "file_extension": ".py",
106
+   "mimetype": "text/x-python",
107
+   "name": "python",
108
+   "nbconvert_exporter": "python",
109
+   "pygments_lexer": "ipython3",
110
+   "version": "3.8.5"
111
+  }
112
+ },
113
+ "nbformat": 4,
114
+ "nbformat_minor": 4
115
+}

+ 44 - 0
README.md

@@ -0,0 +1,44 @@
1
+Python Crash Course
2
+===
3
+
4
+A Hands-On, Project-Based Introduction to Programming
5
+---
6
+
7
+This is a collection of resources for [Python Crash Course](http://www.nostarch.com/pythoncrashcourse/), an introductory programming book from [No Starch Press](http://www.nostarch.com) by Eric Matthes. Click here for a [much cleaner version](https://ehmatthes.github.io/pcc/) of these online resources.
8
+
9
+If you have any questions about Python Crash Course, feel free to get in touch:
10
+
11
+Email: ehmatthes@gmail.com
12
+
13
+Twitter: [@ehmatthes](http://twitter.com/ehmatthes/)
14
+
15
+<a href="setup_instructions"></a>Setup Instructions
16
+---
17
+Here you can find instructions for:
18
+
19
+- [Installing and configuring Python](http://ehmatthes.github.io/pcc/chapter_01/README.html) (Chapter 1)
20
+- [Installing and using pip](http://ehmatthes.github.io/pcc/chapter_12/installing_pip.html) (Chapter 12)
21
+- [Installing Pygame](http://ehmatthes.github.io/pcc/chapter_12/README.html) (Chapter 12)
22
+- [Installing matplotlib and Pygal](http://ehmatthes.github.io/pcc/chapter_15/README.html) (Chapter 15)
23
+- [Creating a Virtual Environment](http://ehmatthes.github.io/pcc/chapter_18/README.html) (Chapter 18)
24
+- [Deploying a Project to Heroku](http://ehmatthes.github.io/pcc/chapter_20/README.html) (Chapter 20)
25
+- [Installing Python](http://ehmatthes.github.io/pcc/appendix_a/README.html) (Appendix A)
26
+
27
+<a href="source_code"></a>Downloading source code
28
+---
29
+The simplest way to get the online resources for the book is to click on the [*Download ZIP*](https://github.com/ehmatthes/pcc/archive/master.zip) button on the upper right side of [this page](https://github.com/ehmatthes/pcc), which will download the source code files (and other resources) for the entire book.
30
+
31
+[Cheat Sheets](http://ehmatthes.github.io/pcc/cheatsheets/README.html)
32
+---
33
+
34
+Cheat sheets can be really helpful when you're working on a set of programming exercises or a project. This set of [cheat sheets](http://ehmatthes.github.io/pcc/cheatsheets/README.html) will help remind you of the concepts you're learning, as well as the Python syntax for these concepts.
35
+
36
+[Updates](http://ehmatthes.github.io/pcc/updates.html)
37
+---
38
+
39
+Some of the libraries featured in the book have been updated recently, which is a good thing - it means you're learning to use Python packages that are steadily being improved.
40
+
41
+When packages are updated you have the option of using the version that was featured in the book, which lets you run code exactly as it's written in the book. You can also choose to install the latest version of each package, and modify the code in the book slightly. Each approach is outlined clearly in these updates.
42
+
43
+A list of updates is kept [here](http://ehmatthes.github.io/pcc/updates.html).
44
+

+ 19 - 0
UPDATES.md

@@ -0,0 +1,19 @@
1
+Updates
2
+===
3
+
4
+Some of the libraries featured in the book have been updated recently, which is a good thing - it means you're learning to use Python packages that are steadily being improved. When packages are updated you have the option of using the version that was featured in the book, which lets you run code exactly as it's written in the book. You can also choose to install the latest version of each package, and modify the code in the book slightly. Each approach is outlined clearly in these updates.
5
+
6
+Chapter 15
7
+---
8
+
9
+Pygal has been updated to version 2. You can install a version of Pygal that runs the code exactly as it's written in the book, or you can install the latest version of Pygal and modify what's in the book slightly. See [installing Pygal](chapter_15/README.md#installing-pygal), and see the [updates to Chapter 15](chapter_15/README.md#updates) to make tooltips appear on charts.
10
+
11
+Chapter 16
12
+---
13
+
14
+Pygal's world map and internationalization features have been moved to a separate module. See the section on [installing Pygal](chapter_15/README.md#installing-pygal), and see the specific [updates for Chapter 16](chapter_16/README.md#updates).
15
+
16
+Chapter 17
17
+---
18
+
19
+The [updates to Chapter 17](chapter_17/README.md#updates) allow tooltips to show on charts generated with Pygal.

+ 154 - 0
Untitled.ipynb

@@ -0,0 +1,154 @@
1
+{
2
+ "cells": [
3
+  {
4
+   "cell_type": "code",
5
+   "execution_count": 1,
6
+   "metadata": {},
7
+   "outputs": [
8
+    {
9
+     "name": "stdout",
10
+     "output_type": "stream",
11
+     "text": [
12
+      "Happy 23rd Birthday!\n"
13
+     ]
14
+    }
15
+   ],
16
+   "source": [
17
+    "age = 23\n",
18
+    "message = \"Happy \" + str(age) + \"rd Birthday!\"\n",
19
+    "\n",
20
+    "print(message)"
21
+   ]
22
+  },
23
+  {
24
+   "cell_type": "code",
25
+   "execution_count": 4,
26
+   "metadata": {},
27
+   "outputs": [
28
+    {
29
+     "name": "stdout",
30
+     "output_type": "stream",
31
+     "text": [
32
+      "Hello, Ada Lovelace!\n"
33
+     ]
34
+    }
35
+   ],
36
+   "source": [
37
+    "# %load chapter_02/name.py\n",
38
+    "first_name = \"ada\"\n",
39
+    "last_name = \"lovelace\"\n",
40
+    "full_name = first_name + \" \" + last_name\n",
41
+    "\n",
42
+    "message = \"Hello, \" + full_name.title() + \"!\"\n",
43
+    "print(message)\n"
44
+   ]
45
+  },
46
+  {
47
+   "cell_type": "code",
48
+   "execution_count": null,
49
+   "metadata": {},
50
+   "outputs": [],
51
+   "source": []
52
+  },
53
+  {
54
+   "cell_type": "code",
55
+   "execution_count": null,
56
+   "metadata": {},
57
+   "outputs": [],
58
+   "source": []
59
+  },
60
+  {
61
+   "cell_type": "code",
62
+   "execution_count": 2,
63
+   "metadata": {},
64
+   "outputs": [
65
+    {
66
+     "data": {
67
+      "text/plain": [
68
+       "14"
69
+      ]
70
+     },
71
+     "execution_count": 2,
72
+     "metadata": {},
73
+     "output_type": "execute_result"
74
+    }
75
+   ],
76
+   "source": [
77
+    "def sum(a,b):\n",
78
+    "    return a + b\n",
79
+    "sum(12,2)"
80
+   ]
81
+  },
82
+  {
83
+   "cell_type": "code",
84
+   "execution_count": 5,
85
+   "metadata": {},
86
+   "outputs": [
87
+    {
88
+     "name": "stdout",
89
+     "output_type": "stream",
90
+     "text": [
91
+      "['honda', 'yamaha', 'suzuki', 'ducati']\n",
92
+      "['honda', 'yamaha', 'suzuki']\n",
93
+      "\n",
94
+      "A Ducati is too expensive for me.\n"
95
+     ]
96
+    }
97
+   ],
98
+   "source": [
99
+    "motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] \n",
100
+    "print(motorcycles)\n",
101
+    "\n",
102
+    "too_expensive = 'ducati'\n",
103
+    "motorcycles.remove(too_expensive)\n",
104
+    "print(motorcycles)\n",
105
+    "print(\"\\nA \" + too_expensive.title() + \" is too expensive for me.\")\n"
106
+   ]
107
+  },
108
+  {
109
+   "cell_type": "code",
110
+   "execution_count": 6,
111
+   "metadata": {},
112
+   "outputs": [
113
+    {
114
+     "name": "stdout",
115
+     "output_type": "stream",
116
+     "text": [
117
+      "['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']\n",
118
+      "['dog', 'dog', 'goldfish', 'rabbit']\n"
119
+     ]
120
+    }
121
+   ],
122
+   "source": [
123
+    "pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']\n",
124
+    "print(pets)\n",
125
+    "\n",
126
+    "while 'cat' in pets:\n",
127
+    "    pets.remove('cat')\n",
128
+    "    \n",
129
+    "print(pets)\n"
130
+   ]
131
+  }
132
+ ],
133
+ "metadata": {
134
+  "kernelspec": {
135
+   "display_name": "Python 3",
136
+   "language": "python",
137
+   "name": "python3"
138
+  },
139
+  "language_info": {
140
+   "codemirror_mode": {
141
+    "name": "ipython",
142
+    "version": 3
143
+   },
144
+   "file_extension": ".py",
145
+   "mimetype": "text/x-python",
146
+   "name": "python",
147
+   "nbconvert_exporter": "python",
148
+   "pygments_lexer": "ipython3",
149
+   "version": "3.8.5"
150
+  }
151
+ },
152
+ "nbformat": 4,
153
+ "nbformat_minor": 4
154
+}

File diff suppressed because it is too large
+ 132 - 0
appendix_a/README.md


+ 3 - 0
appendix_b/Python3.sublime-build

@@ -0,0 +1,3 @@
1
+{
2
+    "cmd": ["/usr/local/bin/python3", "-u", "$file"],
3
+}

+ 1 - 0
appendix_b/hello_world.py

@@ -0,0 +1 @@
1
+print("Hello Python world!")

+ 1 - 0
appendix_d/.gitignore

@@ -0,0 +1 @@
1
+__pycache__/

+ 1 - 0
appendix_d/hello_world.py

@@ -0,0 +1 @@
1
+print("Hello Git world!")

+ 11 - 0
chapter_01/README.md

@@ -0,0 +1,11 @@
1
+Chapter 1
2
+===
3
+
4
+Setting Up
5
+---
6
+
7
+Python runs on all modern operating systems, but the setup process is slightly different on each operating system:
8
+
9
+- [Linux](linux_setup.md)
10
+- [OS X](osx_setup.md)
11
+- [Windows](windows_setup.md)

BIN
chapter_01/figures/crash_course01-01.png


BIN
chapter_01/figures/crash_course01-02.png


BIN
chapter_01/figures/crash_course01-03.png


+ 1 - 0
chapter_01/hello_world.py

@@ -0,0 +1 @@
1
+print("Hello Python world!")

+ 91 - 0
chapter_01/linux_setup.md

@@ -0,0 +1,91 @@
1
+Setup Instructions: Linux
2
+===
3
+
4
+- [Checking your current version of Python](#current_version)
5
+- [Installing Python 3.5](#python3.5)
6
+- [Installing Geany](#installing_geany)
7
+    - [Configuring Geany](#configuring_geany)
8
+
9
+<a name='current_version'></a>Checking your current version of Python
10
+---
11
+
12
+Python is probably already installed on your system. Find out which version is your default by issuing the command `python --version`:
13
+
14
+    $ python --version
15
+    Python 2.7.6
16
+
17
+If you see something like this, Python 2.7 is your default version. You should also see if you have Python 3 installed:
18
+
19
+    $ python3 --version
20
+    Python 3.4.0
21
+
22
+If you have Python 3.4 or later, it's fine to start out by using the installed version. If you have Python 3.3 or earlier, it's probably worth installing Python 3.5.
23
+
24
+[top](#)
25
+
26
+<a name='python3.5'></a>Installing Python 3.5
27
+---
28
+
29
+The following instructions should work on Ubuntu, and most Debian-based systems that use the apt package manager.
30
+
31
+Add the *deadsnakes* package, and then install Python 3.5:
32
+
33
+    $ sudo add-apt-repository ppa:fkrull/deadsnakes
34
+    $ sudo apt-get update
35
+    $ sudo apt-get install python3.5
36
+
37
+You can confirm that the installation was successful:
38
+
39
+    $ python3.5 --version
40
+    Python 3.5.0
41
+
42
+Now to start a Python terminal session, you'll use the command `python3.5`:
43
+
44
+    $ python3.5
45
+    Python 3.5.0 (default, Sep 17 2015, 00:00:00) 
46
+    [GCC 4.8.4] on linux
47
+    Type "help", "copyright", "credits" or "license" for more information.
48
+    >>>
49
+
50
+You'll use this command when you configure your text editor, and when you run programs from the terminal.
51
+
52
+[top](#)
53
+
54
+<a name='installing_geany'></a>Installing Geany
55
+---
56
+
57
+On Ubuntu and other systems that use the apt package manager, you can install Geany in one line:
58
+
59
+    $ sudo apt-get install geany
60
+
61
+If this doesn't work, you can see the instructions at [http://geany.org/Download/ThirdPartyPackages/](http://geany.org/Download/ThirdPartyPackages/).
62
+
63
+[top](#)
64
+
65
+<a name='configuring_geany'></a>
66
+### Configuring Geany
67
+
68
+If you use the simple command `python` to start a terminal session on your system, you shouldn't have to configure Geany at all. But if you use a command like `python3` or `python3.5`, you'll have to modify Geany slightly so it uses the correct version of Python to run your programs.
69
+
70
+Open an empty file and save it as *hello_world.py*. The file should have one line in it:
71
+
72
+    print("Hello Python world!")
73
+
74
+Go to **Build>Set Build Commands**. You should see the word *Compile*, and a command next to the word *Compile*. Change this to
75
+
76
+    python3 -m py_compile "%f"
77
+
78
+If you use a command like `python3.5`, make sure you use that command instead.
79
+
80
+Next to the word *Execute*, enter the following command:
81
+
82
+    python3 "%f"
83
+
84
+Again, if you use a command like `python3.5`, make sure you use that command.
85
+
86
+Now you can run programs by selecting **Build>Execute**, clicking the Execute icon with a set of gears on it, or by pressing **F5**.
87
+
88
+[top](#)
89
+
90
+
91
+

+ 93 - 0
chapter_01/osx_setup.md

@@ -0,0 +1,93 @@
1
+Setup Instructions: OS X
2
+===
3
+
4
+- [Checking your current version of Python](#current_version)
5
+- [Installing Python 3.5](#python3.5)
6
+- [Installing Sublime Text](#installing_st)
7
+    - [Configuring Sublime Text](#configuring_st)
8
+
9
+<a name='current_version'></a>Checking your current version of Python
10
+---
11
+
12
+Python is probably already installed on your system. To check if it's installed, go to **Applications>Utilities** and click on **Terminal**. (You can also press command-spacebar, type *terminal*, and then press Enter.)
13
+
14
+Find out which version of Python is installed by issuing the command `python --version`:
15
+
16
+    $ python --version
17
+    Python 2.7.5
18
+
19
+If you see something like this, Python 2.7 is your default version. You should also see if you have Python 3 installed:
20
+
21
+    $ python3 --version
22
+    Python 3.4.0
23
+
24
+If you have Python 3.4 or later, it's fine to start out by using the installed version. If you have Python 3.3 or earlier, it's probably worth installing Python 3.5.
25
+
26
+[top](#)
27
+
28
+<a name='python3.5'></a>Installing Python 3.5
29
+---
30
+
31
+Install [Homebrew](http://brew.sh/), which makes it easy to install the most recent version of Python. Start out by installing some of Apple's xcode tools:
32
+
33
+    $ xcode-select --install
34
+
35
+The installation may take a while, depending on the speed of your connection. Next, install Homebrew:
36
+
37
+    $ ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
38
+
39
+If you run the command **brew doctor**, you can verify that the installation was successful:
40
+
41
+    $ brew doctor
42
+    Your system is ready to brew.
43
+
44
+Now you can install Python packages through Homebrew. To install Python 3, enter the following command:
45
+
46
+    $ brew install python3
47
+
48
+You can verify that Python 3 was installed correctly:
49
+
50
+    $ python3 --version
51
+    Python 3.5.0
52
+
53
+You'll use the **python3** command when you configure your text editor, when you start a Python terminal session, and when you run programs from the terminal.
54
+
55
+[top](#)
56
+
57
+<a name='installing_st'></a>Installing Sublime Text
58
+---
59
+
60
+You can download an installer for Sublime Text by clicking on the OS X link at [http://www.sublimetext.com/3](http://www.sublimetext.com/3). Sublime Text has a liberal licensing policy; it's free as long as you want to use it, but the author requests that you purchase a license if you like the program and want to continue using it.
61
+
62
+After you've downloaded the installer, open it and then drag the Sublime Text icon into your *Applications* folder.
63
+
64
+[top](#)
65
+
66
+<a name='configuring_st'></a>
67
+### Configuring Sublime Text for Python 3
68
+
69
+If you use the simple command `python` to start a terminal session on your system, you shouldn't have to configure Sublime Text at all. But if you use a command like `python3` or `python3.5`, you'll have to modify Sublime Text slightly so it uses the correct version of Python to run your programs.
70
+
71
+Find the path to your Python interpreter:
72
+
73
+    $ type -a python3
74
+    python3 is /usr/local/bin/python3
75
+
76
+Open an empty file in Sublime Text and save it as *hello_world.py*. The file should have one line in it:
77
+
78
+    print("Hello Python world!")
79
+
80
+Go to **Tools>Build System>New Build System**, which will open a new configuration file. Delete what you see, and enter the following:
81
+
82
+    {
83
+        "cmd": ["/usr/local/bin/python3", "-u", "$file"],
84
+    }
85
+
86
+This tells Sublime Text to use your system's **python3** command when running programs. Make sure you use the path you found when running **type -a python3**, not necessarily the path you see here. Save the file as *Python3.sublime-build* in the directory that Sublime Text opens when you choose Save.
87
+
88
+Now you can run programs by selecting **Build>Execute**, clicking the Execute icon with a set of gears on it, or by pressing **F5**.
89
+
90
+[top](#)
91
+
92
+
93
+

+ 0 - 0
chapter_01/untitled


+ 106 - 0
chapter_01/windows_setup.md

@@ -0,0 +1,106 @@
1
+Setup Instructions: Windows
2
+===
3
+
4
+- [Checking your current version of Python](#current_version)
5
+- [Installing Python 3.5](#python3.5)
6
+- [Adding Python to Your Path Variable](#path_variable)
7
+- [Installing Geany](#installing_geany)
8
+    - [Configuring Geany](#configuring_geany)
9
+
10
+<a name='current_version'></a>Checking your current version of Python
11
+---
12
+
13
+Python may already installed on your system. Open a command window by right-clicking on the Desktop while holding the shift key, and then select "Open Command Window Here". You can also search for "command" in the task bar. Find out which version is your default by issuing the command `python --version`:
14
+
15
+    > python --version
16
+    Python 2.7.6
17
+
18
+If you see something like this, Python 2.7 is your default version. You should also see if you have Python 3 installed:
19
+
20
+    > python3 --version
21
+    Python 3.4.0
22
+
23
+If you have Python 3.4 or later, it's fine to start out by using the installed version. If you have Python 3.3 or earlier, it's probably worth installing Python 3.5.
24
+
25
+If you get an error message for both of these commands, Python is not installed on your system, and you should install Python 3.5.
26
+
27
+[top](#)
28
+
29
+<a name='python3.5'></a>Installing Python 3.5
30
+---
31
+
32
+Go to [https://www.python.org/downloads/](https://www.python.org/downloads/) and click the button labeled "Download Python 3.5". Download the installer, and when you run it make sure to check the *Add Python to PATH* option:
33
+
34
+![Add Python to PATH box checked](figures/crash_course01-02.png)
35
+
36
+Checking this button ensures that you'll be able to use the simple command **python**. If you missed this step, see [Adding Python to Your Path Variable](#path_variable).
37
+
38
+You can confirm that the installation was successful:
39
+
40
+    > python --version
41
+    Python 3.5.0
42
+
43
+Now to start a Python terminal session, you'll use the command `python`:
44
+
45
+    > python
46
+    Python 3.5.0 (v3.5.0:374f501f4567, Sep 13 2015, 02:16:59) [MSC v.1900 32 bit (Intel)] on win32
47
+    Type "help", "copyright", "credits" or "license" for more information.
48
+    >>>
49
+
50
+You'll use this command when you configure your text editor, and when you run programs from the terminal.
51
+
52
+[top](#)
53
+
54
+<a name='path_variable'></a>Adding Python to Your Path Variable
55
+---
56
+If you checked *Add Python to PATH* when you installed Python and the command **python** works, you can skip this step.
57
+
58
+To find the path to Python on your system, open Windows Explorer and look in your C:\ drive. Look for a folder starting with *Python*; you might need to enter *python* in the Windows Explorer search bar to find the right folder. Open the folder, and look for a file with the lowercase name *python*. Right-click this file and choose **Properties**; you'll then see the path to this file under the heading Location.
59
+
60
+In a terminal window, use the path to confirm the version you just installed:
61
+
62
+    > C:\\Python35\python --version
63
+    Python 3.5.0
64
+
65
+Open your system's **Control Panel**, choose **System and Security**, and then choose **System**. Click **Advanced System Settings*, and in the window that pops up click **Environment Variables**.
66
+
67
+In the box labeled *System variables*, look for a variable called `Path`. Click **Edit**. In the box that pops up, click in the box labeled *Variable Value* and use the right arrow key to scroll all the way to the right. Be careful not to write over the existing variable; if you do, click Cancel and try again. Add a semicolon and the path to your *python.exe* file to the existing variable:
68
+
69
+    %SystemRoot%\system32\...\System32\WindowsPowerShell\v1.0\;C:\Python35
70
+
71
+Close any existing terminal windows, and open a new one. Now when you enter **python --version**, you should see the version of Python you just set in your `Path` variable. You can now start a Python terminal session by just entering **python** at a command prompt.
72
+
73
+<a name='installing_geany'></a>Installing Geany
74
+---
75
+
76
+You can download a Windows installer for Geany from [http://www.geany.org/Download/Releases](http://www.geany.org/Download/Releases). Download and run the installer called *geany-1.25_setup.exe*, accepting all the defaults.
77
+
78
+[top](#)
79
+
80
+<a name='configuring_geany'></a>
81
+### Configuring Geany
82
+
83
+If you use the simple command `python` to start a terminal session on your system, you shouldn't have to configure Geany at all. But if you use a command like `python3` or a full path like `C:\Python35\python` to start a terminal session, you'll have to modify Geany slightly so it uses the correct version of Python to run your programs.
84
+
85
+Open an empty file and save it as *hello_world.py*. The file should have one line in it:
86
+
87
+    print("Hello Python world!")
88
+
89
+Go to **Build>Set Build Commands**. You should see the word *Compile*, and a command next to the word *Compile*. Change this to
90
+
91
+    python3 -m py_compile "%f"
92
+
93
+You can also use a full path in this setting, such as `C:\Python35\python -m py_compile "%f"`.
94
+
95
+Next to the word *Execute*, enter the following command:
96
+
97
+    python3 "%f"
98
+
99
+Again, you can use a full path, such as `C:\Python35\python "%f"`.
100
+
101
+Now you can run programs by selecting **Build>Execute**, clicking the Execute icon with a set of gears on it, or by pressing **F5**.
102
+
103
+[top](#)
104
+
105
+
106
+

+ 2 - 0
chapter_02/apostrophe.py

@@ -0,0 +1,2 @@
1
+message = "One of Python's strengths is its diverse community."
2
+print(message)

+ 4 - 0
chapter_02/birthday.py

@@ -0,0 +1,4 @@
1
+age = 23
2
+message = "Happy " + str(age) + "rd Birthday!"
3
+
4
+print(message)

+ 2 - 0
chapter_02/comment.py

@@ -0,0 +1,2 @@
1
+# Say hello to everyone.
2
+print("Hello Python people!")

+ 5 - 0
chapter_02/hello_world.py

@@ -0,0 +1,5 @@
1
+message = "Hello Python world!"
2
+print(message)
3
+
4
+message = "Hello Python Crash Course world!"
5
+print(message)

+ 6 - 0
chapter_02/name.py

@@ -0,0 +1,6 @@
1
+first_name = "ada"
2
+last_name = "lovelace"
3
+full_name = first_name + " " + last_name
4
+
5
+message = "Hello, " + full_name.title() + "!"
6
+print(message)

+ 4 - 0
chapter_03/bicycles.py

@@ -0,0 +1,4 @@
1
+bicycles = ['trek', 'cannondale', 'redline', 'specialized']
2
+message = "My first bicycle was a " + bicycles[0].title() + "."
3
+
4
+print(message)

+ 13 - 0
chapter_03/cars.py

@@ -0,0 +1,13 @@
1
+cars = ['bmw', 'audi', 'toyota', 'subaru']
2
+
3
+print("Here is the original list:")
4
+print(cars)
5
+
6
+print("\nHere is the sorted list:")
7
+print(sorted(cars))
8
+
9
+print("\nHere is the reverse alphabetical list:")
10
+print(sorted(cars, reverse=True))
11
+
12
+print("\nHere is the original list again:")
13
+print(cars)

+ 7 - 0
chapter_03/motorcycles.py

@@ -0,0 +1,7 @@
1
+motorcycles = ['honda', 'yamaha', 'suzuki', 'ducati'] 
2
+print(motorcycles)
3
+
4
+too_expensive = 'ducati'
5
+motorcycles.remove(too_expensive)
6
+print(motorcycles)
7
+print("\nA " + too_expensive.title() + " is too expensive for me.")

+ 9 - 0
chapter_04/dimensions.py

@@ -0,0 +1,9 @@
1
+dimensions = (200, 50)
2
+print("Original dimensions:")
3
+for dimension in dimensions:
4
+    print(dimension)
5
+    
6
+dimensions = (400, 100)
7
+print("\nModified dimensions:")
8
+for dimension in dimensions:
9
+    print(dimension)

+ 2 - 0
chapter_04/even_numbers.py

@@ -0,0 +1,2 @@
1
+even_numbers = list(range(2,11,2)) 
2
+print(even_numbers)

+ 11 - 0
chapter_04/foods.py

@@ -0,0 +1,11 @@
1
+my_foods = ['pizza', 'falafel', 'carrot cake'] 
2
+friend_foods = my_foods[:] 
3
+
4
+my_foods.append('cannoli') 
5
+friend_foods.append('ice cream') 
6
+
7
+print("My favorite foods are:")
8
+print(my_foods)
9
+
10
+print("\nMy friend's favorite foods are:")
11
+print(friend_foods)

+ 6 - 0
chapter_04/magicians.py

@@ -0,0 +1,6 @@
1
+magicians = ['alice', 'david', 'carolina'] 
2
+for magician in magicians: 
3
+    print(magician.title() + ", that was a great trick!")  
4
+    print("I can't wait to see your next trick, " + magician.title() + ".\n") 
5
+    
6
+print("Thank you everyone, that was a great magic show!")

+ 2 - 0
chapter_04/numbers.py

@@ -0,0 +1,2 @@
1
+numbers = list(range(1,6)) 
2
+print(numbers) 

+ 5 - 0
chapter_04/players.py

@@ -0,0 +1,5 @@
1
+players = ['charles', 'martina', 'michael', 'florence', 'eli'] 
2
+
3
+print("Here are the first three players on my team:")
4
+for player in players[:3]:
5
+    print(player.title())

+ 6 - 0
chapter_04/squares.py

@@ -0,0 +1,6 @@
1
+squares = []
2
+for value in range(1,11):
3
+    square = value**2
4
+    squares.append(square)
5
+    
6
+print(squares)

+ 12 - 0
chapter_05/amusement_park.py

@@ -0,0 +1,12 @@
1
+age = 12
2
+
3
+if age < 4:
4
+    price = 0
5
+elif age < 18:
6
+    price = 5
7
+elif age < 65:
8
+    price = 10
9
+elif age >= 65:
10
+    price = 5
11
+
12
+print("Your admission cost is $" + str(price) + ".")

+ 5 - 0
chapter_05/banned_users.py

@@ -0,0 +1,5 @@
1
+banned_users = ['andrew', 'carolina', 'david']
2
+user = 'marie'
3
+
4
+if user not in banned_users:
5
+    print(user.title() + ", you can post a response if you wish.")

+ 7 - 0
chapter_05/cars.py

@@ -0,0 +1,7 @@
1
+cars = ['audi', 'bmw', 'subaru', 'toyota']
2
+
3
+for car in cars:
4
+    if car == 'bmw':
5
+        print(car.upper())
6
+    else:
7
+        print(car.title())

+ 4 - 0
chapter_05/magic_number.py

@@ -0,0 +1,4 @@
1
+answer = 17
2
+
3
+if answer != 42:
4
+    print("That is not the correct answer. Please try again!")

+ 12 - 0
chapter_05/toppings.py

@@ -0,0 +1,12 @@
1
+available_toppings = ['mushrooms', 'olives', 'green peppers',
2
+                      'pepperoni', 'pineapple', 'extra cheese']
3
+
4
+requested_toppings = ['mushrooms', 'french fries', 'extra cheese']
5
+
6
+for requested_topping in requested_toppings:
7
+    if requested_topping in available_toppings:
8
+        print("Adding " + requested_topping + ".")
9
+    else:
10
+        print("Sorry, we don't have " + requested_topping + ".")
11
+        
12
+print("\nFinished making your pizza!")

+ 7 - 0
chapter_05/voting.py

@@ -0,0 +1,7 @@
1
+age = 17
2
+if age >= 18:
3
+    print("You are old enough to vote!")
4
+    print("Have you registered to vote yet?")
5
+else:
6
+    print("Sorry, you are too young to vote.")
7
+    print("Please register to vote as soon as you turn 18!")

+ 17 - 0
chapter_06/alien.py

@@ -0,0 +1,17 @@
1
+alien_0 = {'x_position': 0, 'y_position': 25, 'speed': 'medium'}
2
+print("Original position: " + str(alien_0['x_position']))
3
+
4
+# Move the alien to the right.
5
+# Figure out how far to move the alien based on its speed.
6
+if alien_0['speed'] == 'slow':
7
+    x_increment = 1
8
+elif alien_0['speed'] == 'medium':
9
+    x_increment = 2
10
+else:
11
+    # This must be a fast alien.
12
+    x_increment = 3
13
+
14
+# The new position is the old position plus the increment.
15
+alien_0['x_position'] = alien_0['x_position'] + x_increment
16
+
17
+print("New position: " + str(alien_0['x_position']))

+ 22 - 0
chapter_06/aliens.py

@@ -0,0 +1,22 @@
1
+# Make an empty list for storing aliens.
2
+aliens = []
3
+
4
+# Make 30 green aliens.
5
+for alien_number in range (0,30):
6
+    new_alien = {'color': 'green', 'points': 5, 'speed': 'slow'}
7
+    aliens.append(new_alien)
8
+    
9
+for alien in aliens[0:3]:
10
+    if alien['color'] == 'green':
11
+        alien['color'] = 'yellow'
12
+        alien['speed'] = 'medium'
13
+        alien['points'] = 10
14
+    elif alien['color'] == 'yellow':
15
+        alien['color'] = 'red'
16
+        alien['speed'] = 'fast'
17
+        alien['points'] = 15
18
+        
19
+# Show the first 5 aliens:
20
+for alien in aliens[0:5]:
21
+    print(alien)
22
+print("...")

+ 10 - 0
chapter_06/favorite_languages.py

@@ -0,0 +1,10 @@
1
+favorite_languages = {
2
+    'jen': 'python',
3
+    'sarah': 'c',
4
+    'edward': 'ruby',
5
+    'phil': 'python',
6
+    }
7
+
8
+for name, language in favorite_languages.items():
9
+    print(name.title() + "'s favorite language is " +
10
+        language.title() + ".")

+ 15 - 0
chapter_06/many_users.py

@@ -0,0 +1,15 @@
1
+users = {'aeinstein': {'first': 'albert',
2
+                       'last': 'einstein',
3
+                       'location': 'princeton'},
4
+         'mcurie': {'first': 'marie',
5
+                    'last': 'curie',
6
+                    'location': 'paris'},
7
+         }
8
+
9
+for username, user_info in users.items():
10
+    print("\nUsername: " + username)
11
+    full_name = user_info['first'] + " " + user_info['last']
12
+    location = user_info['location']
13
+
14
+    print("\tFull name: " + full_name.title())
15
+    print("\tLocation: " + location.title())

+ 12 - 0
chapter_06/pizza.py

@@ -0,0 +1,12 @@
1
+# Store information about a pizza being ordered.
2
+pizza = {
3
+    'crust': 'thick',
4
+    'toppings': ['mushrooms', 'extra cheese'],
5
+    }
6
+
7
+# Summarize the order.
8
+print("You ordered a " + pizza['crust'] + "-crust pizza " +
9
+      "with the following toppings:")
10
+
11
+for topping in pizza['toppings']:
12
+    print("\t" + topping)

+ 8 - 0
chapter_06/user.py

@@ -0,0 +1,8 @@
1
+user_0 = {'username': 'efermi',
2
+          'first': 'enrico',
3
+          'last': 'fermi',
4
+          }
5
+
6
+for key, value in user_0.items():
7
+    print("\nKey: " + key)
8
+    print("Value: " + value)

+ 10 - 0
chapter_07/cities.py

@@ -0,0 +1,10 @@
1
+prompt = "\nPlease tell me a city you have visited:"
2
+prompt += "\n(Enter 'quit' when you are finished.) "
3
+
4
+while True:
5
+    city = input(prompt)
6
+    
7
+    if city == 'quit':
8
+        break
9
+    else:
10
+        print("I'd love to go to " + city.title() + "!")

+ 17 - 0
chapter_07/confirmed_users.py

@@ -0,0 +1,17 @@
1
+# Start out with some users that need to be verified,
2
+#  and an empty list to hold confirmed users.
3
+unconfirmed_users = ['alice', 'brian', 'candace']
4
+confirmed_users = []
5
+
6
+# Verify each user, until there are no more unconfirmed users.
7
+#  Move each verified user into the list of confirmed users.
8
+while unconfirmed_users:
9
+    current_user = unconfirmed_users.pop()
10
+    
11
+    print("Verifying user: " + current_user.title())
12
+    confirmed_users.append(current_user)
13
+    
14
+# Display all confirmed users.
15
+print("\nThe following users have been confirmed:")
16
+for confirmed_user in confirmed_users:
17
+    print(confirmed_user.title())

+ 4 - 0
chapter_07/counting.py

@@ -0,0 +1,4 @@
1
+current_number = 1
2
+while current_number <= 5:
3
+    print(current_number)
4
+    current_number += 1

+ 7 - 0
chapter_07/even_or_odd.py

@@ -0,0 +1,7 @@
1
+number = input("Enter a number, and I'll tell you if it's even or odd: ")
2
+number = int(number)
3
+
4
+if number % 2 == 0:
5
+    print("\nThe number " + str(number) + " is even.")
6
+else:
7
+    print("\nThe number " + str(number) + " is odd.")

+ 5 - 0
chapter_07/greeter.py

@@ -0,0 +1,5 @@
1
+prompt = "If you tell us who you are, we can personalize the messages you see."
2
+prompt += "\nWhat is your first name? "
3
+
4
+name = input(prompt)
5
+print("\nHello, " + name + "!")

+ 22 - 0
chapter_07/mountain_poll.py

@@ -0,0 +1,22 @@
1
+responses = {}
2
+
3
+# Set a flag to indicate that polling is active.
4
+polling_active = True
5
+
6
+while polling_active:
7
+    # Prompt for the person's name and response.
8
+    name = input("\nWhat is your name? ")
9
+    response = input("Which mountain would you like to climb someday? ")
10
+    
11
+    # Store the response in the dictionary:
12
+    responses[name] = response
13
+    
14
+    # Find out if anyone else is going to take the poll.
15
+    repeat = input("Would you like to let another person respond? (yes/ no) ")
16
+    if repeat == 'no':
17
+        polling_active = False
18
+        
19
+# Polling is complete. Show the results.
20
+print("\n--- Poll Results ---")
21
+for name, response in responses.items():
22
+    print(name + " would like to climb " + response + ".")

+ 11 - 0
chapter_07/parrot.py

@@ -0,0 +1,11 @@
1
+prompt = "\nTell me something, and I will repeat it back to you:"
2
+prompt += "\nEnter 'quit' to end the program. "
3
+  
4
+active = True
5
+while active:
6
+    message = input(prompt)
7
+    
8
+    if message == 'quit':
9
+        active = False
10
+    else:
11
+        print(message)

+ 7 - 0
chapter_07/pets.py

@@ -0,0 +1,7 @@
1
+pets = ['dog', 'cat', 'dog', 'goldfish', 'cat', 'rabbit', 'cat']
2
+print(pets)
3
+
4
+while 'cat' in pets:
5
+    pets.remove('cat')
6
+    
7
+print(pets)

+ 7 - 0
chapter_07/rollercoaster.py

@@ -0,0 +1,7 @@
1
+height = input("How tall are you, in inches? ")
2
+height = int(height)
3
+
4
+if height >= 36:
5
+    print("\nYou're tall enough to ride!")
6
+else:
7
+    print("\nYou'll be able to ride when you're a little older.")

+ 13 - 0
chapter_08/formatted_name.py

@@ -0,0 +1,13 @@
1
+def get_formatted_name(first_name, last_name, middle_name=''):
2
+    """Return a full name, neatly formatted."""
3
+    if middle_name:
4
+        full_name = first_name + ' ' +  middle_name + ' ' + last_name
5
+    else:
6
+        full_name = first_name + ' ' + last_name
7
+    return full_name.title()
8
+    
9
+musician = get_formatted_name('jimi', 'hendrix')
10
+print(musician)
11
+
12
+musician = get_formatted_name('john', 'hooker', 'lee')
13
+print(musician)

+ 8 - 0
chapter_08/greet_users.py

@@ -0,0 +1,8 @@
1
+def greet_users(names):
2
+    """Print a simple greeting to each user in the list."""
3
+    for name in names:
4
+        msg = "Hello, " + name.title() + "!"
5
+        print(msg)
6
+
7
+usernames = ['hannah', 'ty', 'margot']
8
+greet_users(usernames)

+ 5 - 0
chapter_08/greeter.py

@@ -0,0 +1,5 @@
1
+def greet_user(username):
2
+    """Display a simple greeting."""
3
+    print("Hello, " + username.title() + "!")
4
+    
5
+greet_user('jesse')

+ 4 - 0
chapter_08/making_pizzas.py

@@ -0,0 +1,4 @@
1
+import pizza as p
2
+
3
+p.make_pizza(16, 'pepperoni')
4
+p.make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

+ 9 - 0
chapter_08/person.py

@@ -0,0 +1,9 @@
1
+def build_person(first_name, last_name, age=''):
2
+    """Return a dictionary of information about a person."""
3
+    person = {'first': first_name, 'last': last_name}
4
+    if age:
5
+        person['age'] = age
6
+    return person
7
+
8
+musician = build_person('jimi', 'hendrix', age=27)
9
+print(musician)

+ 13 - 0
chapter_08/pets.py

@@ -0,0 +1,13 @@
1
+def describe_pet(pet_name, animal_type='dog'):
2
+    """Display information about a pet."""
3
+    print("\nI have a " + animal_type + ".")
4
+    print("My " + animal_type + "'s name is " + pet_name.title() + ".")
5
+    
6
+# A dog named Willie.
7
+describe_pet('willie')
8
+describe_pet(pet_name='willie')
9
+
10
+# A hamster named Harry.
11
+describe_pet('harry', 'hamster')
12
+describe_pet(pet_name='harry', animal_type='hamster')
13
+describe_pet(animal_type='hamster', pet_name='harry')

+ 9 - 0
chapter_08/pizza.py

@@ -0,0 +1,9 @@
1
+def make_pizza(size, *toppings):
2
+    """Summarize the pizza we are about to make."""
3
+    print("\nMaking a " + str(size) +
4
+          "-inch pizza with the following toppings:")
5
+    for topping in toppings:
6
+        print("- " + topping)
7
+        
8
+make_pizza(16, 'pepperoni')
9
+make_pizza(12, 'mushrooms', 'green peppers', 'extra cheese')

+ 24 - 0
chapter_08/printing_models.py

@@ -0,0 +1,24 @@
1
+def print_models(unprinted_designs, completed_models):
2
+    """
3
+    Simulate printing each design, until there are none left.
4
+    Move each design to completed_models after printing.
5
+    """
6
+    while unprinted_designs:
7
+        current_design = unprinted_designs.pop()
8
+    
9
+        # Simulate creating a 3d print from the design.
10
+        print("Printing model: " + current_design)
11
+        completed_models.append(current_design)
12
+        
13
+def show_completed_models(completed_models):
14
+    """Show all the models that were printed."""
15
+    print("\nThe following models have been printed:")
16
+    for completed_model in completed_models:
17
+        print(completed_model)
18
+        
19
+        
20
+unprinted_designs = ['iphone case', 'robot pendant', 'dodecahedron']
21
+completed_models = []
22
+
23
+print_models(unprinted_designs, completed_models)
24
+show_completed_models(completed_models)

+ 13 - 0
chapter_08/user_profile.py

@@ -0,0 +1,13 @@
1
+def build_profile(first, last, **user_info):
2
+    """Build a dictionary containing everything we know about a user."""
3
+    profile = {}
4
+    profile['first_name'] = first
5
+    profile['last_name'] = last
6
+    for key, value in user_info.items():
7
+        profile[key] = value
8
+    return profile
9
+
10
+user_profile = build_profile('albert', 'einstein',
11
+                             location='princeton',
12
+                             field='physics')
13
+print(user_profile)

+ 34 - 0
chapter_09/car.py

@@ -0,0 +1,34 @@
1
+"""A class that can be used to represent a car."""
2
+
3
+class Car():
4
+    """A simple attempt to represent a car."""
5
+
6
+    def __init__(self, manufacturer, model, year):
7
+        """Initialize attributes to describe a car."""
8
+        self.manufacturer = manufacturer
9
+        self.model = model
10
+        self.year = year
11
+        self.odometer_reading = 0
12
+        
13
+    def get_descriptive_name(self):
14
+        """Return a neatly formatted descriptive name."""
15
+        long_name = str(self.year) + ' ' + self.manufacturer + ' ' + self.model
16
+        return long_name.title()
17
+    
18
+    def read_odometer(self):
19
+        """Print a statement showing the car's mileage."""
20
+        print("This car has " + str(self.odometer_reading) + " miles on it.")
21
+        
22
+    def update_odometer(self, mileage):
23
+        """
24
+        Set the odometer reading to the given value.
25
+        Reject the change if it attempts to roll the odometer back.
26
+        """
27
+        if mileage >= self.odometer_reading:
28
+            self.odometer_reading = mileage
29
+        else:
30
+            print("You can't roll back an odometer!")
31
+    
32
+    def increment_odometer(self, miles):
33
+        """Add the given amount to the odometer reading."""
34
+        self.odometer_reading += miles

+ 27 - 0
chapter_09/dog.py

@@ -0,0 +1,27 @@
1
+class Dog():
2
+    """A simple attempt to model a dog."""
3
+    
4
+    def __init__(self, name, age):
5
+        """Initialize name and age attributes."""
6
+        self.name = name
7
+        self.age = age
8
+        
9
+    def sit(self):
10
+        """Simulate a dog sitting in response to a command."""
11
+        print(self.name.title() + " is now sitting.")
12
+
13
+    def roll_over(self):
14
+        """Simulate rolling over in response to a command."""
15
+        print(self.name.title() + " rolled over!")
16
+        
17
+
18
+my_dog = Dog('willie', 6)
19
+your_dog = Dog('lucy', 3)
20
+
21
+print("My dog's name is " + my_dog.name.title() + ".")
22
+print("My dog is " + str(my_dog.age) + " years old.")
23
+my_dog.sit()
24
+
25
+print("\nMy dog's name is " + your_dog.name.title() + ".")
26
+print("My dog is " + str(your_dog.age) + " years old.")
27
+your_dog.sit()

+ 37 - 0
chapter_09/electric_car.py

@@ -0,0 +1,37 @@
1
+"""A set of classes that can be used to represent electric cars."""
2
+
3
+from car import Car
4
+
5
+class Battery():
6
+    """A simple attempt to model a battery for an electric car."""
7
+
8
+    def __init__(self, battery_size=60):
9
+        """Initialize the batteery's attributes."""
10
+        self.battery_size = battery_size
11
+
12
+    def describe_battery(self):
13
+        """Print a statement describing the battery size."""
14
+        print("This car has a " + str(self.battery_size) + "-kWh battery.")  
15
+        
16
+    def get_range(self):
17
+        """Print a statement about the range this battery provides."""
18
+        if self.battery_size == 60:
19
+            range = 140
20
+        elif self.battery_size == 85:
21
+            range = 185
22
+            
23
+        message = "This car can go approximately " + str(range)
24
+        message += " miles on a full charge."
25
+        print(message)
26
+    
27
+        
28
+class ElectricCar(Car):
29
+    """Models aspects of a car, specific to electric vehicles."""
30
+
31
+    def __init__(self, manufacturer, model, year):
32
+        """
33
+        Initialize attributes of the parent class.
34
+        Then initialize attributes specific to an electric car.
35
+        """
36
+        super().__init__(manufacturer, model, year)
37
+        self.battery = Battery()

+ 12 - 0
chapter_09/favorite_languages.py

@@ -0,0 +1,12 @@
1
+from collections import OrderedDict
2
+
3
+favorite_languages = OrderedDict()
4
+
5
+favorite_languages['jen'] = 'python'
6
+favorite_languages['sarah'] = 'c'
7
+favorite_languages['edward'] = 'ruby'
8
+favorite_languages['phil'] = 'python'
9
+
10
+for name, language in favorite_languages.items():
11
+    print(name.title() + "'s favorite language is " +
12
+        language.title() + ".")

+ 7 - 0
chapter_09/my_car.py

@@ -0,0 +1,7 @@
1
+from car import Car
2
+
3
+my_new_car = Car('audi', 'a4', 2015)
4
+print(my_new_car.get_descriptive_name())
5
+
6
+my_new_car.odometer_reading = 23
7
+my_new_car.read_odometer()

+ 8 - 0
chapter_09/my_cars.py

@@ -0,0 +1,8 @@
1
+from car import Car
2
+from electric_car import ElectricCar
3
+
4
+my_beetle = Car('volkswagen', 'beetle', 2015)
5
+print(my_beetle.get_descriptive_name())
6
+
7
+my_tesla = ElectricCar('tesla', 'roadster', 2015)
8
+print(my_tesla.get_descriptive_name())

+ 13 - 0
chapter_10/alice.py

@@ -0,0 +1,13 @@
1
+filename = 'alice.txt'
2
+
3
+try:
4
+    with open(filename, encoding='utf-8') as f_obj:
5
+        contents = f_obj.read()
6
+except FileNotFoundError as e:
7
+    msg = "Sorry, the file " + filename + " does not exist."
8
+    print(msg)
9
+else:
10
+    # Count the approximate number of words in the file.
11
+    words = contents.split()
12
+    num_words = len(words)
13
+    print("The file " + filename + " has about " + str(num_words) + " words.")

File diff suppressed because it is too large
+ 3735 - 0
chapter_10/alice.txt


+ 14 - 0
chapter_10/division.py

@@ -0,0 +1,14 @@
1
+print("Give me two numbers, and I'll divide them.")
2
+print("Enter 'q' to quit.")
3
+
4
+while True:
5
+    first_number = input("\nFirst number: ")
6
+    if first_number == 'q':
7
+        break
8
+    second_number = input("Second number: ")
9
+    try:
10
+        answer = int(first_number) / int(second_number)
11
+    except ZeroDivisionError:
12
+        print("You can't divide by 0!")
13
+    else:
14
+        print(answer)

+ 7 - 0
chapter_10/file_reader.py

@@ -0,0 +1,7 @@
1
+filename = 'pi_digits.txt'
2
+
3
+with open(filename) as file_object:
4
+    lines = file_object.readlines()
5
+
6
+for line in lines:
7
+    print(line.rstrip())

+ 7 - 0
chapter_10/greet_user.py

@@ -0,0 +1,7 @@
1
+import json
2
+
3
+filename = 'username.json'
4
+
5
+with open(filename) as f_obj:
6
+    username = json.load(f_obj)
7
+    print("Welcome back, " + username + "!")

File diff suppressed because it is too large
+ 21022 - 0
chapter_10/little_women.txt


File diff suppressed because it is too large
+ 22108 - 0
chapter_10/moby_dick.txt


+ 7 - 0
chapter_10/number_reader.py

@@ -0,0 +1,7 @@
1
+import json
2
+
3
+filename = 'numbers.json'
4
+with open(filename) as file_object:
5
+    numbers = json.load(file_object)
6
+    
7
+print(numbers)

+ 7 - 0
chapter_10/number_writer.py

@@ -0,0 +1,7 @@
1
+import json
2
+
3
+numbers = [2, 3, 5, 7, 11, 13]
4
+
5
+filename = 'numbers.json'
6
+with open(filename, 'w') as file_object:
7
+    json.dump(numbers, file_object)

+ 1 - 0
chapter_10/numbers.json

@@ -0,0 +1 @@
1
+[2, 3, 5, 7, 11, 13]

+ 3 - 0
chapter_10/pi_30_digits.txt

@@ -0,0 +1,3 @@
1
+3.1415926535
2
+  8979323846
3
+  2643383279

+ 3 - 0
chapter_10/pi_digits.txt

@@ -0,0 +1,3 @@
1
+3.1415926535
2
+  8979323846
3
+  2643383279

File diff suppressed because it is too large
+ 10000 - 0
chapter_10/pi_million_digits.txt


+ 14 - 0
chapter_10/pi_string.py

@@ -0,0 +1,14 @@
1
+filename = 'pi_million_digits.txt'
2
+
3
+with open(filename) as file_object:
4
+    lines = file_object.readlines()
5
+
6
+pi_string = ''
7
+for line in lines:
8
+    pi_string += line.rstrip()
9
+
10
+birthday = input("Enter your birthday, in the form mmddyy: ")
11
+if birthday in pi_string:
12
+    print("Your birthday appears in the first million digits of pi!")
13
+else:
14
+    print("Your birthday does not appear in the first million digits of pi.")

+ 4 - 0
chapter_10/programming.txt

@@ -0,0 +1,4 @@
1
+I love programming.
2
+I love creating new games.
3
+I also love finding meaning in large datasets.
4
+I love creating apps that can run in a browser.

+ 31 - 0
chapter_10/remember_me.py

@@ -0,0 +1,31 @@
1
+import json
2
+
3
+def get_stored_username():
4
+    """Get stored username if available."""
5
+    filename = 'username.json'
6
+    try:
7
+        with open(filename) as f_obj:
8
+            username = json.load(f_obj)
9
+    except FileNotFoundError:
10
+        return None
11
+    else:
12
+        return username
13
+
14
+def get_new_username():
15
+    """Prompt for a new username."""
16
+    username = input("What is your name? ")
17
+    filename = 'username.json'
18
+    with open(filename, 'w') as f_obj:
19
+        json.dump(username, f_obj)
20
+    return username
21
+
22
+def greet_user():
23
+    """Greet the user by name."""
24
+    username = get_stored_username()
25
+    if username:
26
+        print("Welcome back, " + username + "!")
27
+    else:
28
+        username = get_new_username()
29
+        print("We'll remember you when you come back, " + username + "!")
30
+
31
+greet_user()

File diff suppressed because it is too large
+ 4319 - 0
chapter_10/siddhartha.txt


+ 16 - 0
chapter_10/word_count.py

@@ -0,0 +1,16 @@
1
+def count_words(filename):
2
+    """Count the approximate number of words in a file."""
3
+    try:
4
+        with open(filename, encoding='utf-8') as f_obj:
5
+            contents = f_obj.read() 
6
+    except FileNotFoundError:
7
+        pass
8
+    else:
9
+        # Count approximate number of words in the file.
10
+        words = contents.split()
11
+        num_words = len(words)
12
+        print("The file " + filename + " has about " + str(num_words) + " words.")
13
+
14
+filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt']
15
+for filename in filenames:
16
+    count_words(filename)

+ 5 - 0
chapter_10/write_message.py

@@ -0,0 +1,5 @@
1
+filename = 'programming.txt'
2
+
3
+with open(filename, 'a') as file_object:
4
+    file_object.write("I also love finding meaning in large datasets.\n")
5
+    file_object.write("I love creating apps that can run in a browser.\n")

+ 18 - 0
chapter_11/language_survey.py

@@ -0,0 +1,18 @@
1
+from survey import AnonymousSurvey
2
+
3
+# Define a question, and make a survey object.
4
+question = "What language did you first learn to speak?"
5
+my_survey = AnonymousSurvey(question)
6
+
7
+# Show the question, and store responses to the question.
8
+my_survey.show_question()
9
+print("Enter 'q' at any time to quit.\n")
10
+while True:
11
+    response = input("Language: ")
12
+    if response == 'q':
13
+        break
14
+    my_survey.store_response(response)
15
+
16
+# Show the survey results.
17
+print("\nThank you to everyone who participated in the survey!")
18
+my_survey.show_results()

+ 7 - 0
chapter_11/name_function.py

@@ -0,0 +1,7 @@
1
+def get_formatted_name(first, last, middle=''):
2
+    """Generate a neatly-formatted full name."""
3
+    if middle:
4
+        full_name = first + ' ' + middle + ' ' + last
5
+    else:
6
+        full_name = first + ' ' + last
7
+    return full_name.title()

+ 14 - 0
chapter_11/names.py

@@ -0,0 +1,14 @@
1
+from name_function import get_formatted_name
2
+
3
+print("Enter 'q' at any time to quit.")
4
+while True:
5
+    first = input("\nPlease give me a first name: ")
6
+    if first == 'q':
7
+        break
8
+        
9
+    last = input("Please give me a last name: ")
10
+    if last == 'q':
11
+        break
12
+        
13
+    formatted_name = get_formatted_name(first, last)
14
+    print("\tNeatly formatted name: " + formatted_name + '.')

+ 21 - 0
chapter_11/survey.py

@@ -0,0 +1,21 @@
1
+class AnonymousSurvey():
2
+    """Collect anonymous answers to a survey question."""
3
+    
4
+    def __init__(self, question):
5
+        """Store a question, and prepare to store responses."""
6
+        self.question = question
7
+        self.responses = []
8
+        
9
+    def show_question(self):
10
+        """Show the survey question."""
11
+        print(self.question)
12
+        
13
+    def store_response(self, new_response):
14
+        """Store a single response to the survey."""
15
+        self.responses.append(new_response)
16
+        
17
+    def show_results(self):
18
+        """Show all the responses that have been given."""
19
+        print("Survey results:")
20
+        for response in self.responses:
21
+            print('- ' + response)

+ 17 - 0
chapter_11/test_name_function.py

@@ -0,0 +1,17 @@
1
+import unittest
2
+from name_function import get_formatted_name
3
+
4
+class NamesTestCase(unittest.TestCase):
5
+    """Tests for 'name_function.py'."""
6
+    
7
+    def test_first_last_name(self):
8
+        formatted_name = get_formatted_name('janis', 'joplin')
9
+        self.assertEqual(formatted_name, 'Janis Joplin')
10
+        
11
+    def test_first_last_middle_name(self):
12
+        formatted_name = get_formatted_name(
13
+            'wolfgang', 'mozart', 'amadeus')
14
+        self.assertEqual(formatted_name, 'Wolfgang Amadeus Mozart')
15
+            
16
+
17
+unittest.main()

+ 30 - 0
chapter_11/test_survey.py

@@ -0,0 +1,30 @@
1
+import unittest
2
+from survey import AnonymousSurvey
3
+
4
+class TestAnonymousSurvey(unittest.TestCase):
5
+    """Tests for the class AnonymousSurvey."""
6
+    
7
+    def setUp(self):
8
+        """
9
+        Create a survey and a set of responses for use in all test methods.
10
+        """
11
+        question = "What language did you first learn to speak?"
12
+        self.my_survey = AnonymousSurvey(question)
13
+        self.responses = ['English', 'Spanish', 'Mandarin']
14
+        
15
+    
16
+    def test_store_single_response(self):
17
+        """Test that a single response is stored properly."""
18
+        self.my_survey.store_response(self.responses[0])
19
+        self.assertIn(self.responses[0], self.my_survey.responses)
20
+        
21
+        
22
+    def test_store_three_responses(self):
23
+        """Test that three individual responses are stored properly."""
24
+        for response in self.responses:
25
+            self.my_survey.store_response(response)
26
+        for response in self.responses:
27
+            self.assertIn(response, self.my_survey.responses)
28
+            
29
+
30
+unittest.main()

File diff suppressed because it is too large
+ 114 - 0
chapter_12/README.md


+ 31 - 0
chapter_12/alien_invasion.py

@@ -0,0 +1,31 @@
1
+import pygame
2
+from pygame.sprite import Group
3
+
4
+from settings import Settings
5
+from ship import Ship
6
+import game_functions as gf
7
+
8
+def run_game():
9
+    # Initialize pygame, settings, and screen object.
10
+    pygame.init()
11
+    ai_settings = Settings()
12
+    screen = pygame.display.set_mode(
13
+        (ai_settings.screen_width, ai_settings.screen_height))
14
+    pygame.display.set_caption("Alien Invasion")
15
+    
16
+    # Set the background color.
17
+    bg_color = (230, 230, 230)
18
+    
19
+    # Make a ship.
20
+    ship = Ship(ai_settings, screen)
21
+    # Make a group to store bullets in.
22
+    bullets = Group()
23
+
24
+    # Start the main loop for the game.
25
+    while True:
26
+        gf.check_events(ai_settings, screen, ship, bullets)
27
+        ship.update()
28
+        gf.update_bullets(bullets)
29
+        gf.update_screen(ai_settings, screen, ship, bullets)
30
+
31
+run_game()

+ 0 - 0
chapter_12/bullet.py


Some files were not shown because too many files changed in this diff

tmt/tiger_frontend - Gogs: Simplico Git Service

Bez popisu

golf 77628cf8bf first comm %!s(int64=2) %!d(string=před) roky
..
build 77628cf8bf first comm %!s(int64=2) %!d(string=před) roky
LICENSE 77628cf8bf first comm %!s(int64=2) %!d(string=před) roky
README.md 77628cf8bf first comm %!s(int64=2) %!d(string=před) roky
package.json 77628cf8bf first comm %!s(int64=2) %!d(string=před) roky

README.md

lines-and-columns

Maps lines and columns to character offsets and back. This is useful for parsers and other text processors that deal in character ranges but process text with meaningful lines and columns.

Install

$ npm install [--save] lines-and-columns

Usage

import { LinesAndColumns } from 'lines-and-columns'

const lines = new LinesAndColumns(
  `table {
  border: 0
}`
)

lines.locationForIndex(9)
// { line: 1, column: 1 }

lines.indexForLocation({ line: 1, column: 2 })
// 10

License

MIT