Skip to content

Johoo123 patch 2111 #1223

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 16 commits into
base: master
Choose a base branch
from
Open
4 changes: 2 additions & 2 deletions 02.proof-of-work.ipynb
Original file line number Diff line number Diff line change
@@ -91,7 +91,7 @@
"\n",
"当然,为了这么做,你还要多学一样反正你早晚都必须学会的东西,Git —— 请参阅附录《[Git 入门](T-appendix.git-introduction.ipynb)》。\n",
"\n",
"时间就是这样,我们没办法糊弄它。而有了 git 这样的工具之后,我们在什么时候做了什么样的工作,是很容易证明的 —— 这对我们来说真是天大的好事。"
"时间就是这样,我们没办法糊弄它。而有了 git 这样的工具之后,我们在什么时候做了什么样的工作,是很容易证明的 —— 这对我们来说真是天大的好事。.."
]
},
{
@@ -114,7 +114,7 @@
"source": [
"(1) 使用浏览器访问 https://github.com/selfteaching/the-craft-of-selfteaching\n",
"\n",
"(2) 点击右上角的 “Fork 按钮”,将该仓库 Fork 到你的 Github 账户中\n",
"(2) 点击右上角的 “Fork 按钮”,将该仓库 Fork 到你的 Github 账户中..\n",
"\n",
"![](images/github-fork.png)\n",
"\n",
8 changes: 4 additions & 4 deletions Part.1.A.better.teachyourself.ipynb

Large diffs are not rendered by default.

34 changes: 12 additions & 22 deletions Part.1.E.2.values-and-their-operators.ipynb
Original file line number Diff line number Diff line change
@@ -23,7 +23,7 @@
},
{
"cell_type": "code",
"execution_count": 1,
"execution_count": 3,
"metadata": {},
"outputs": [
{
@@ -118,7 +118,7 @@
},
{
"cell_type": "code",
"execution_count": 2,
"execution_count": 4,
"metadata": {},
"outputs": [
{
@@ -152,7 +152,7 @@
},
{
"cell_type": "code",
"execution_count": 19,
"execution_count": 6,
"metadata": {},
"outputs": [
{
@@ -161,7 +161,7 @@
"3.14159"
]
},
"execution_count": 19,
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
},
@@ -171,7 +171,7 @@
"3"
]
},
"execution_count": 19,
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
},
@@ -181,7 +181,7 @@
"3.0"
]
},
"execution_count": 19,
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
@@ -226,28 +226,18 @@
},
{
"cell_type": "code",
"execution_count": 18,
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"20.0"
]
},
"execution_count": 18,
"metadata": {},
"output_type": "execute_result"
},
{
"ename": "TypeError",
"evalue": "can only concatenate str (not \"int\") to str",
"output_type": "error",
"traceback": [
"\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[0;32m<ipython-input-18-e922b7565e53>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m 3\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m 4\u001b[0m \u001b[0;36m11\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;36m10\u001b[0m \u001b[0;34m-\u001b[0m \u001b[0;36m9\u001b[0m \u001b[0;34m*\u001b[0m \u001b[0;36m8\u001b[0m \u001b[0;34m/\u001b[0m \u001b[0;36m7\u001b[0m \u001b[0;34m//\u001b[0m \u001b[0;36m6\u001b[0m \u001b[0;34m%\u001b[0m \u001b[0;36m5\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 5\u001b[0;31m \u001b[0;34m'3.14'\u001b[0m \u001b[0;34m+\u001b[0m \u001b[0;36m3\u001b[0m \u001b[0;31m# 这一句会报错\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
"\u001b[0;31mTypeError\u001b[0m: can only concatenate str (not \"int\") to str"
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mTypeError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32mc:\\Users\\Administrator\\Documents\\GitHub\\the-craft-of-selfteaching\\Part.1.E.2.values-and-their-operators.ipynb 单元格 14\u001b[0m line \u001b[0;36m5\n\u001b[0;32m <a href='vscode-notebook-cell:/c%3A/Users/Administrator/Documents/GitHub/the-craft-of-selfteaching/Part.1.E.2.values-and-their-operators.ipynb#X16sZmlsZQ%3D%3D?line=1'>2</a>\u001b[0m InteractiveShell\u001b[39m.\u001b[39mast_node_interactivity \u001b[39m=\u001b[39m \u001b[39m\"\u001b[39m\u001b[39mall\u001b[39m\u001b[39m\"\u001b[39m\n\u001b[0;32m <a href='vscode-notebook-cell:/c%3A/Users/Administrator/Documents/GitHub/the-craft-of-selfteaching/Part.1.E.2.values-and-their-operators.ipynb#X16sZmlsZQ%3D%3D?line=3'>4</a>\u001b[0m \u001b[39m11\u001b[39m \u001b[39m+\u001b[39m \u001b[39m10\u001b[39m \u001b[39m-\u001b[39m \u001b[39m9\u001b[39m \u001b[39m*\u001b[39m \u001b[39m8\u001b[39m \u001b[39m/\u001b[39m \u001b[39m7\u001b[39m \u001b[39m/\u001b[39m\u001b[39m/\u001b[39m \u001b[39m6\u001b[39m \u001b[39m%\u001b[39m \u001b[39m5\u001b[39m\n\u001b[1;32m----> <a href='vscode-notebook-cell:/c%3A/Users/Administrator/Documents/GitHub/the-craft-of-selfteaching/Part.1.E.2.values-and-their-operators.ipynb#X16sZmlsZQ%3D%3D?line=4'>5</a>\u001b[0m \u001b[39m'\u001b[39;49m\u001b[39m3.14\u001b[39;49m\u001b[39m'\u001b[39;49m \u001b[39m+\u001b[39;49m \u001b[39m3\u001b[39;49m \u001b[39m# 这一句会报错\u001b[39;00m\n",
"\u001b[1;31mTypeError\u001b[0m: can only concatenate str (not \"int\") to str"
]
}
],
@@ -1138,7 +1128,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.3"
"version": "3.9.21"
}
},
"nbformat": 4,
2 changes: 1 addition & 1 deletion Part.1.E.4.functions.ipynb
Original file line number Diff line number Diff line change
@@ -705,7 +705,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.3"
"version": "3.9.21"
},
"toc-autonumbering": true
},
26 changes: 19 additions & 7 deletions Part.1.E.6.containers.ipynb

Large diffs are not rendered by default.

20 changes: 11 additions & 9 deletions Part.1.E.7.files.ipynb
Original file line number Diff line number Diff line change
@@ -149,17 +149,19 @@
},
{
"cell_type": "code",
"execution_count": 4,
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"first line\n",
"second line\n",
"third line\n",
"\n"
"ename": "FileNotFoundError",
"evalue": "[Errno 2] No such file or directory: '/tmp/test-file.txt'",
"output_type": "error",
"traceback": [
"\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
"\u001b[1;31mFileNotFoundError\u001b[0m Traceback (most recent call last)",
"\u001b[1;32mc:\\Users\\Administrator\\Documents\\GitHub\\the-craft-of-selfteaching\\Part.1.E.7.files.ipynb 单元格 13\u001b[0m line \u001b[0;36m1\n\u001b[1;32m----> <a href='vscode-notebook-cell:/c%3A/Users/Administrator/Documents/GitHub/the-craft-of-selfteaching/Part.1.E.7.files.ipynb#X15sZmlsZQ%3D%3D?line=0'>1</a>\u001b[0m f \u001b[39m=\u001b[39m \u001b[39mopen\u001b[39;49m(\u001b[39m'\u001b[39;49m\u001b[39m/tmp/test-file.txt\u001b[39;49m\u001b[39m'\u001b[39;49m, \u001b[39m'\u001b[39;49m\u001b[39mw\u001b[39;49m\u001b[39m'\u001b[39;49m)\n\u001b[0;32m <a href='vscode-notebook-cell:/c%3A/Users/Administrator/Documents/GitHub/the-craft-of-selfteaching/Part.1.E.7.files.ipynb#X15sZmlsZQ%3D%3D?line=1'>2</a>\u001b[0m f\u001b[39m.\u001b[39mwrite(\u001b[39m'\u001b[39m\u001b[39mfirst line\u001b[39m\u001b[39m\\n\u001b[39;00m\u001b[39msecond line\u001b[39m\u001b[39m\\n\u001b[39;00m\u001b[39mthird line\u001b[39m\u001b[39m\\n\u001b[39;00m\u001b[39m'\u001b[39m)\n\u001b[0;32m <a href='vscode-notebook-cell:/c%3A/Users/Administrator/Documents/GitHub/the-craft-of-selfteaching/Part.1.E.7.files.ipynb#X15sZmlsZQ%3D%3D?line=2'>3</a>\u001b[0m f\u001b[39m.\u001b[39mclose()\n",
"File \u001b[1;32mc:\\Users\\Administrator\\miniconda3\\envs\\new_env\\lib\\site-packages\\IPython\\core\\interactiveshell.py:310\u001b[0m, in \u001b[0;36m_modified_open\u001b[1;34m(file, *args, **kwargs)\u001b[0m\n\u001b[0;32m 303\u001b[0m \u001b[39mif\u001b[39;00m file \u001b[39min\u001b[39;00m {\u001b[39m0\u001b[39m, \u001b[39m1\u001b[39m, \u001b[39m2\u001b[39m}:\n\u001b[0;32m 304\u001b[0m \u001b[39mraise\u001b[39;00m \u001b[39mValueError\u001b[39;00m(\n\u001b[0;32m 305\u001b[0m \u001b[39mf\u001b[39m\u001b[39m\"\u001b[39m\u001b[39mIPython won\u001b[39m\u001b[39m'\u001b[39m\u001b[39mt let you open fd=\u001b[39m\u001b[39m{\u001b[39;00mfile\u001b[39m}\u001b[39;00m\u001b[39m by default \u001b[39m\u001b[39m\"\u001b[39m\n\u001b[0;32m 306\u001b[0m \u001b[39m\"\u001b[39m\u001b[39mas it is likely to crash IPython. If you know what you are doing, \u001b[39m\u001b[39m\"\u001b[39m\n\u001b[0;32m 307\u001b[0m \u001b[39m\"\u001b[39m\u001b[39myou can use builtins\u001b[39m\u001b[39m'\u001b[39m\u001b[39m open.\u001b[39m\u001b[39m\"\u001b[39m\n\u001b[0;32m 308\u001b[0m )\n\u001b[1;32m--> 310\u001b[0m \u001b[39mreturn\u001b[39;00m io_open(file, \u001b[39m*\u001b[39margs, \u001b[39m*\u001b[39m\u001b[39m*\u001b[39mkwargs)\n",
"\u001b[1;31mFileNotFoundError\u001b[0m: [Errno 2] No such file or directory: '/tmp/test-file.txt'"
]
}
],
@@ -9696,7 +9698,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.3"
"version": "3.9.21"
}
},
"nbformat": 4,
9 changes: 5 additions & 4 deletions Part.2.D.1-args.ipynb
Original file line number Diff line number Diff line change
@@ -430,14 +430,15 @@
},
{
"cell_type": "code",
"execution_count": 9,
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2\n"
"2\n",
"1\n"
]
}
],
@@ -448,7 +449,7 @@
"\n",
"n = 1\n",
"print(increase_one(n))\n",
"# print(n)"
"print(n)"
]
},
{
@@ -565,7 +566,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.3"
"version": "3.9.21"
},
"toc-autonumbering": true
},
14 changes: 6 additions & 8 deletions Part.2.D.4-recursion.ipynb
Original file line number Diff line number Diff line change
@@ -96,7 +96,7 @@
},
{
"cell_type": "code",
"execution_count": 1,
"execution_count": 6,
"metadata": {},
"outputs": [
{
@@ -201,7 +201,7 @@
},
{
"cell_type": "code",
"execution_count": 1,
"execution_count": 8,
"metadata": {},
"outputs": [
{
@@ -213,11 +213,9 @@
"dead: False kicked: False\n",
"dead: False kicked: False\n",
"dead: False kicked: False\n",
"dead: False kicked: False\n",
"dead: False kicked: False\n",
"dead: True kicked: True\n",
"I slept 8 days, and was dead to wake up...\n",
"The in_dream() function returns: 8\n"
"dead: True kicked: False\n",
"I slept 6 days, and was dead to wake up...\n",
"The in_dream() function returns: 6\n"
]
}
],
@@ -614,7 +612,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.3"
"version": "3.9.21"
}
},
"nbformat": 4,
120 changes: 17 additions & 103 deletions Part.3.B.2.classes-2.ipynb
Original file line number Diff line number Diff line change
@@ -406,92 +406,6 @@
"scrolled": true
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Help on runningGolem in module __main__ object:\n",
"\n",
"class runningGolem(Golem)\n",
" | runningGolem(name=None)\n",
" | \n",
" | Method resolution order:\n",
" | runningGolem\n",
" | Golem\n",
" | builtins.object\n",
" | \n",
" | Methods defined here:\n",
" | \n",
" | run(self)\n",
" | \n",
" | say_hi(self)\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Methods inherited from Golem:\n",
" | \n",
" | __init__(self, name=None)\n",
" | Initialize self. See help(type(self)) for accurate signature.\n",
" | \n",
" | ----------------------------------------------------------------------\n",
" | Data descriptors inherited from Golem:\n",
" | \n",
" | __dict__\n",
" | dictionary for instance variables (if defined)\n",
" | \n",
" | __weakref__\n",
" | list of weak references to the object (if defined)\n",
"\n"
]
},
{
"data": {
"text/plain": [
"['__class__',\n",
" '__delattr__',\n",
" '__dict__',\n",
" '__dir__',\n",
" '__doc__',\n",
" '__eq__',\n",
" '__format__',\n",
" '__ge__',\n",
" '__getattribute__',\n",
" '__gt__',\n",
" '__hash__',\n",
" '__init__',\n",
" '__init_subclass__',\n",
" '__le__',\n",
" '__lt__',\n",
" '__module__',\n",
" '__ne__',\n",
" '__new__',\n",
" '__reduce__',\n",
" '__reduce_ex__',\n",
" '__repr__',\n",
" '__setattr__',\n",
" '__sizeof__',\n",
" '__str__',\n",
" '__subclasshook__',\n",
" '__weakref__',\n",
" 'built_year',\n",
" 'name',\n",
" 'run',\n",
" 'say_hi']"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"text/plain": [
"{'name': 'Clay', 'built_year': 2019}"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"text/plain": [
@@ -526,9 +440,9 @@
" print('Hey! Nice day, Huh?')\n",
"\n",
"rg = runningGolem('Clay')\n",
"help(rg)\n",
"dir(rg)\n",
"rg.__dict__\n",
"# help(rg)\n",
"# dir(rg)\n",
"# rg.__dict__\n",
"hasattr(rg, 'built_year')"
]
},
@@ -959,7 +873,7 @@
},
{
"cell_type": "code",
"execution_count": 8,
"execution_count": 9,
"metadata": {},
"outputs": [
{
@@ -968,7 +882,7 @@
"1"
]
},
"execution_count": 8,
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
},
@@ -978,7 +892,7 @@
"101"
]
},
"execution_count": 8,
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
},
@@ -988,7 +902,7 @@
"101"
]
},
"execution_count": 8,
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
},
@@ -1035,23 +949,23 @@
" 'say_hi': <function __main__.Golem.say_hi(self)>,\n",
" 'cease': <function __main__.Golem.cease(self)>,\n",
" 'is_active': <function __main__.Golem.is_active(self)>,\n",
" 'population': <property at 0x1068f9d68>,\n",
" 'population': <property at 0x1e53da6c860>,\n",
" '__dict__': <attribute '__dict__' of 'Golem' objects>,\n",
" '__weakref__': <attribute '__weakref__' of 'Golem' objects>,\n",
" '__doc__': None})"
]
},
"execution_count": 8,
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"text/plain": [
"{'name': 'Clay', 'built_year': 2019, '_Golem__active': True}"
"{'name': 'Clay', 'built_year': 2025, '_Golem__active': True}"
]
},
"execution_count": 8,
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
},
@@ -1061,17 +975,17 @@
"True"
]
},
"execution_count": 8,
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"text/plain": [
"<property at 0x1068f9d68>"
"<property at 0x1e53da6c860>"
]
},
"execution_count": 8,
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
},
@@ -1081,7 +995,7 @@
"10000"
]
},
"execution_count": 8,
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
@@ -1133,7 +1047,7 @@
"hasattr(Golem, 'population')\n",
"getattr(Golem, 'population')\n",
"setattr(Golem, 'population', 10000)\n",
"g.population # 所以,在很多的情况下,不把数据封装在 Class 内部的话,后面会有很多麻烦。"
"g.population # 所以,在很多的情况下,不把数据封装在 Class 内部的话,后面会有很多麻烦。\n"
]
},
{
@@ -1160,7 +1074,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.9.7"
"version": "3.9.21"
},
"toc-autonumbering": true
},
15 changes: 9 additions & 6 deletions Part.3.B.3.decorator-iterator-generator.ipynb
Original file line number Diff line number Diff line change
@@ -313,7 +313,7 @@
},
{
"cell_type": "code",
"execution_count": 64,
"execution_count": 3,
"metadata": {},
"outputs": [
{
@@ -372,7 +372,7 @@
},
{
"cell_type": "code",
"execution_count": 67,
"execution_count": 9,
"metadata": {},
"outputs": [
{
@@ -391,7 +391,9 @@
"def counter(start, stop):\n",
" while start <= stop:\n",
" yield start\n",
" \n",
" start += 1\n",
" # return start\n",
"for i in counter(101, 105):\n",
" print(i)"
]
@@ -922,14 +924,14 @@
},
{
"cell_type": "code",
"execution_count": 50,
"execution_count": 10,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<strong>THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.</strong>\n"
"<STRONG>THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.</STRONG>\n"
]
}
],
@@ -947,8 +949,9 @@
" return modified_restult\n",
" return wrapper\n",
"\n",
"@strong\n",
"# @strong\n",
"@uppercase\n",
"@strong\n",
"def an_output():\n",
" return 'The quick brown fox jumps over the lazy dog.'\n",
"print(an_output())"
@@ -1116,7 +1119,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.3"
"version": "3.9.21"
},
"toc-autonumbering": true
},
46 changes: 43 additions & 3 deletions Part.3.B.4.regex.ipynb
Original file line number Diff line number Diff line change
@@ -816,7 +816,7 @@
},
{
"cell_type": "code",
"execution_count": 1,
"execution_count": 8,
"metadata": {},
"outputs": [
{
@@ -825,7 +825,47 @@
"['a', 'a', 'e', 'a', 'a', 'e', 'a', 'a', '|', 'e']"
]
},
"execution_count": 1,
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"text/plain": [
"['a', 'a', 'e', 'a', 'a', 'e', 'a', 'a', '|', 'e']"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"text/plain": [
"['a', 'a', 'e', 'a', 'a', 'e', 'a', 'a', 'e']"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"text/plain": [
"['a', 'a', 'e', 'a', 'a', 'e', 'a', 'a', 'e']"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
},
{
"data": {
"text/plain": [
"['a', 'a', 'e', 'a', 'a', 'e', 'a', 'a', '|', 'e']"
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
@@ -1639,7 +1679,7 @@
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.8.3"
"version": "3.9.21"
}
},
"nbformat": 4,
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -2,7 +2,7 @@

> One has no future if one couldn't teach themself<a href='#fn1' name='fn1b'><sup>[1]</sup></a>.
# 自学是门手艺
# 自学是门手艺

> 没有自学能力的人没有未来
17 changes: 17 additions & 0 deletions regular expression2.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@

import re
with open(r'\Users\Administrator\Documents\GitHub\the-craft-of-selfteaching\regex-target-text-sample.txt','r') as f:
str=f.read()

pttn=r'go+gle'
a=re.findall(pttn,str)
print(a)
pttn=r'go{2,5}gle'
b=re.findall(pttn,str)
print(b)
pttn=r'colou?red'
c=re.findall(pttn,str)
print(c)
pttn=r'520*'
d=re.findall(pttn,str)
print(d)
3,771 changes: 3,771 additions & 0 deletions results_test file.txt

Large diffs are not rendered by default.

3,771 changes: 3,771 additions & 0 deletions words_alpha_list.txt

Large diffs are not rendered by default.

70 changes: 70 additions & 0 deletions 学习笔记/5.12文件.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
# 文件
大量数据保存、读取、写入需要的就是文件(Files)。
## 创建文件
创建一个文件,最简单的就是python的内建函数`open()`
> open(file,mode='r')
第二个参数,`mode`,默认值是 `'r'`,可用的 `mode` 有以下几种:

| 参数字符 | 意义 |
| -------- | ------------------------------- |
| `'r'` | 只读模式 |
| `'w'` | 写入模式(重建)|
| `'x'` | 排他模式 —— 如果文件已存在则打开失败 |
| `'a'` | 追加模式 —— 在已有文件末尾追加 |
| `'b'` | 二进制文件模式 |
| `'t'` | 文本文件模式(默认)|
| `'+'` | 读写模式(更新)|
创建一个文件:
```python
open('/tmp/test-file.txt', 'w')
```
更多时候,还需要把这个函数的返回值,一个所谓file object保存到一个变量中,以便后面调用这个file object的各种Methods,比如获取文件名file.name,比如关闭文件file.close()
```python
f = open('/tmp/test-file.txt', 'w')
print(f.name)
f.close()
#路径三种写法:
#1. r'\
#2. 使用双反斜杠\\
#3. 使用正斜杠:“/”
```
## 删除文件
删除文件,就得调用os模块了,删除文件之前,要先确认文件是否存在,否则删除命令会失败。
```python
import os
f=open('/tmp/test-file.txt','w')
print(f.name)
f.close()
if os.path.exists(f.name):
os.remove(f.name)
print(f'{f.name}deleted.')
else:
print(f'{f.name} does not exist.')
```
## 读写文件
> f.write()或f.read()读取文件
> file.radline()每运行一次读一行
> file.readlines()读取全部内容,以列表返回
> file.radline().strip()读取后去除文本后的\n
> file.readlines()使用for line in f.realines():遍历返回的列表
> file.writelines(列表/...)向创建后的文件内部写入内容,注意创建内容时:'w'
## with语句块
针对文件操作,python有专门的语法块:with
`with open(...) as f:`
` f.write(...)`
` ... `
把各种对文件的操作打包
## 另一个完整的程序
“即便是结论正确,论证过程乱取八糟也不行!”
找得到不仅恰当且又**精彩**的例子和论据的,就是好作者。
> 找出所有字母加在一起为100的英文单词(a=1,b=2...)
> 1. 遍历英文字典,取出每一个单词
> 2. 遍历取出的单词的每个字母,在索引基础上+1
> 3. 判断if是否字母求和==100,如果是,则追加到空列表,否则,contine。
## 总结
1. open(),'r','w'
2. os模块,用来调用file的操作,os.remove()
3. file.read()、file.write()、file.readline()、file.readlines()、file.writelines()
4. 可以使用with把操作放到一个语句块中...
375 changes: 375 additions & 0 deletions 学习笔记/5.13.md

Large diffs are not rendered by default.

200 changes: 200 additions & 0 deletions 学习笔记/5.14.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
# 化名与匿名
## 化名
> 给函数取个化名
```python
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

def _is_leap(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)

year_leap_bool = _is_leap
year_leap_bool #<function __main__._is_leap(year)>
year_leap_bool(800) # _is_leap(800) -> True

id(year_leap_bool) # id() 这个函数可以查询某对象的内存地址
id(_is_leap) # year_leap_bool 和 _is_leap 其实保存在同一个地址中,也就是说,它们是同一个对象。

type(year_leap_bool) #function
type(_is_leap) #function # 它们都是 function
```
注意:
id(_is_leap)和id(year_leap_bool)是同一id,相当于赋值操作只是改变了名字,但是id值代表的内存地址未发生改变。
使用场景:提高代码可读性。
## lambda
函数内容很短时,直接使用lambda关键字定义函数
```python
def add(x,y):
return x+y
add(3,5)
#使用lambda
add=lambda x,y:x+y
add(3,5)#注意add作为变量直接接收了lambda,传参数直接传递到add中。
```
lambda的语法结构:
> `lambda_expr ::= "lambda" [parameter_list] ":" expression`
以上使用BNF标注。在lambda的:后只能有一个表达式。
匿名函数:lambda:...没有名字的函数
通过`add=lambda x,y:x+y`相当于给函数取名。
## lambda的使用场景
### 作为某函数的返回值
```python
def make_incrementor(n):
return lambda x:x+n
f=make_incrementor(42) #注意,并不是函数化名的写法
f(0)# 42
f(1)# 43
```
注意:
1. 因为lambda作为返回值,相当于make_incrementor(42)的返回值保存到了f变量中。
2. 相当于f=lambda x:x+42;传参数直接向匿名函数f变量中传递。
### 作为某函数的参数
一些函数可以接收函数作为参数:
> `map`(*function*, *iterable*, *...*)
>
> Return an iterator that applies *function* to every item of *iterable*, yielding the results. If additional *iterable* arguments are passed, *function* must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted. For cases where the function inputs are already arranged into argument tuples, see [`itertools.starmap()`](https://docs.python.org/3/library/itertools.html#itertools.starmap).
`map()`函数第一个参数接收函数,第二个参数iterable接收可被迭代对象(如容器(列表、元组、字典等)
```python
def double_it(n):
return n*2
a_list=[1,2,3,4,5,6]
b_list=list(map(double_it,a_list))
print(b_list)

c_list=list(map(lambda x:x*2,a_list))
print(c_list)
#使用lambda更为简洁
```
有些函数“用之即弃”,使用lambda更为方便:
```python
phonebook = [
{
'name': 'john',
'phone': 9876
},
{
'name': 'mike',
'phone': 5603
},
{
'name': 'stan',
'phone': 6898
},
{
'name': 'eric',
'phone': 7898
}
]
print(phonebook)
print(list(map(lambda x:x['name'],phonebook)))
print(list(map(lambda x:x['phone'],phonebook)))
```
`map()`可以传递多个迭代对象:
```python
a_list=[1,2,3]
b_list=[2,4,6]
print(list(map(lambda x,y:x*y,a_list,b_list)))#[2,8,18]
```
利用lambda作为sort函数排序的依据
```python
pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
pairs.sort(key=lambda p: p[1])#使用p[1]结构必须保证传入数据是可索引的序列类型,否则会报错。
#注意key作为指定sort排序的规则
#key=lambda p:p[1]相当于
#def get_second_element(item):#注意函数中item传入的需要是元组或列表??
# return item[1]
#key=get_second_element
pairs
```
# 递归函数
## 递归(Recursion)
递归函数(Recursive Functions):在自身内部调用自身的函数。
阶乘函数为例:
```python
def f(n):
if n==1:
return 1
else:
return n*f(n-1)
print(f(5))
```
## 递归函数的执行过程
执行过程:f(5)--5*f(4)--4*f(3)--3*f(2)--2*f(1)--1-->1*2-->2*3-->4*6-->5*24-->120
```python
#执行过程拆解:
def f(n):
print('\tn =', n)
if n == 1:
print('Returning...')
print('\tn =', n, 'return:', 1)
return 1
else:
r = n * f(n-1)
print('\tn =', n, 'return:', r)
return r
print('Call f(5)...')
print('Get out of f(n), and f(5) =', f(5))
```

## 递归的终点
递归函数必须在内部有一个让自己停止调用的方式,否则永远循环下去了...
和尚传说:
```python
def a_monk_telling_story():
print("山上有座庙,庙里有个和尚,和尚讲故事,他说...")
return a_monk_telling_story()
```
以上函数是个死循环!
盗梦空间:
```python
import random
def in_dream(day=0,dead=False,kicked=False):
dead=not random.randrange(0,10)
kicked=not random.randrange(0,10)
day+=1
print('dead:',dead,'kicked',kicked)
if dead:
print(f"I slept {day} days,and was dead to wake up...")
return day
elif kicked:
print(f"I slept {day} days,and was kicked to wake up...")
return day
return in_dream(day)
print("The in_dream() function returns:",in_dream())
```
1. 条件语句中,某个值与True进行比较,正确写法:if condition:pass
2. random.randrange(0,10)表示1/10的原因:pass
递归函数的特征:
* return中返回自身的调用
* 为了避免死循环,至少一个条件返回的不再是自身的调用
## 变量的作用域
* 全局变量(Global Variables):在所有函数外被赋值而后可以使用的,是全局变量,它们的作用域是全局,在函数内外都可以被调用。
* 局部变量(Local Variables):在函数内部被赋值后使用的,都是局部变量,它们的作用域是局部的,无法被函数外的代码调用。
程序员严格遵循一条原则:
> 函数内部绝对不调用全局变量,即便是必须改变全局变量,也只能通过函数的返回值在函数外改变全局变量。
> 做事的原则:自己的事自己搞,别人的事,最多通过自己的产出让他们自己去搞...
```python
def factorial(n):
if n==1:
return 1
else:
return n*factorial(n-1)
a=5
b=factorial(a) #a不会改变
print(a,b)
a=factorial(a)#主动为a赋值
print(a,b)
```
变量只是作为参数被传递,但是变量本身不改变。哪怕内外的变量和参数都是同一个名称,

## 递归函数三原则
1. 根据定义,递归函数必须在内部调用自己
2. 必须设定一个退出条件
3. 递归必须能逐步达到退出条件

## 思考与练习
普林斯顿大学的一个网页,有很多递归的例子

https://introcs.cs.princeton.edu/java/23recursion/
655 changes: 655 additions & 0 deletions 学习笔记/5.16.md

Large diffs are not rendered by default.

686 changes: 686 additions & 0 deletions 学习笔记/5.17.md

Large diffs are not rendered by default.

1,169 changes: 1,169 additions & 0 deletions 学习笔记/5.18.md

Large diffs are not rendered by default.

Empty file added 学习笔记/5.19.md
Empty file.
227 changes: 227 additions & 0 deletions 学习笔记/5.2值-循环-函数.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,227 @@
学习目录
# 几个重要概念
## 值及运算
1. 运算+流程控制
2. 质数判断程序:
```python
def is_prime(n):
if n < 2:
return False
if n==2:
return True
for m in range(2,int(n**0.5)+1):
if(n%m)==0:
return False
else:
return True
for i in range(80,100):
if is_prime(i):
print(i)
```
1) if
2) for
3) for i in range(a,b)
###
1.
* 常量
* 变量
函数返回值:默认是None
```python
def f():
pass
print(f())
print(print(f()))
```
在定义f函数时,内部没有return语句,则默认返回None
|函数的本质:把一个值交给某个函数,请其根据自己内部的运算和流程控制对其进行操作后返回另外一个值
举例:
```python
#绝对值
abs(-3.1415926)
#取整
int(abs(-3.1415926))
#浮点
float(int(abs(-3.141592)))
```
2. 值的类型
数据类型:
- 布尔值(Boolean):True、False
- 数字:整数、浮点数、复数(Complex Number)
- 字符串(String)
相同数据类型才可以运算!
- 类型转换(Type Conversion)
```python
int()、float()、str()、bool()
type()#可以查看值的类型
```
不同类型的值运算时需要确认是同一类型,否则报错。同时可以使用type()查看值的类型,同时进行类型的转换。
### 操作符
1. 数值操作符
加减乘除商余幂:+ - * / // % **
操作有优先级顺序!
2. 布尔值操作符
与、或、非:and or not
优先级:not > and > or
3. 逻辑操作符
小于、小于等于、大于、大于等于、等于、不等于:< <= > >= == !=
优先级:逻辑操作符 > 布尔值操作符 > 数值操作符
4. 字符串操作符
1) 拼接:+和''
2) 拷贝:*
3)逻辑运算:in、not in;以及<、>、<=、>=、==、!=
字符串有其对应的Unicode编码,所以可以进行比较。
5. 列表操作符
python容器(Container):为了便于批量处理数字和字符串。
1)数组(Array)
2)字符串(String)
3)列表(List)
#列表同字符串,都是有序容器,可以进行拼接,拷贝和逻辑运算以及比较等。
### 更复杂运算
对数值或字符串的操作(加减乘除商余幂、字符串拼接、拷贝、逻辑运算、比较)以及对布尔值(或、与、非)的操作,都属于简单的运算,更为复杂的需要调用函数。
* python内建函数(Built-in Function):
1. 绝对值abs()
2. 取整int()
3. 浮点数float()
4. 字符串str()
5. 布尔值bool()
6. 类型转换type()
.......
![Alt text](image-1.png)
内建函数也依然只能完成“基本操作””,无法完成复杂的运算。
* 更复杂数学运算,还可以调用标准库(Standard Library)中的math模块。
* 类(Class)定义的函数。
### 布尔值补充
|每个变量或者常量,除了它们的值之外,同时还对应着一个布尔值。
### 值的类型补充
1. 等差数列range()
2. 元组tuple()
3. 字典dict()
4. 集合set()
5. 日期date type()
### 总结
程序结构:运算+流程控制
编程是对不同类型的值进行运算,因此每一种值都对应相应的操作方式:
* 操作符
1. 值运算
2. 逻辑运算
* 函数
* 内建函数
* 其他模块里的函数
* 其本身所属类之中所定义的函数
接下来的学习:各种数据结构及其操作、操作符和函数。
## 流程控制
分支与循环
### if语句
1. 奇偶数
2. 骰子游戏
### for循环
1. for循环比较其他语言的写法:for a in range(10):
2. range()函数:python的内建函数
* range(stop)#range默认返回了n-1的整数数列,若需返回n,需要n+1则返回n本身。
* range(start,stop,[,step])
### CONTINUE和BREAK和PASS
1. CONTINUE
* 忽略continue之后的语句,继续下一次循环
2. BREAK
* 结束当前循环,开始运行循环之后的语句
* PYTHON中比较有个性的地方:for 循环后可以跟一个else语句,当for循环正常结束时,会执行else语句,若循环被break中断,则不会执行else语句。
3. PASS
* 占位语句,不做任何事情,写pass等后面需要完善逻辑了再写。
### while循环
编程语言中提供的两种循环结构:
- Collection-controlled loop:for...in...
- Condition-controlled loop:while...
for更适合处理序列类数据的迭代,while更适合处理条件类数据的迭代。
#### 一个投骰子赌大小的游戏
PASS
### 总结
1. 只处理一种情况:if...
2. 处理True/False两种情况:if...else...
3. 处理多种情况:if...elif...elif...else...
4. 迭代有序数据类型:for...in...,如果需要处理没有break发生的情况,使用for...else...
5. 其他循环:while...
6. 与循环有关的语句还有:continue,break,pass
## 函数
函数实际上是一个可被调用的完整程序。我们只需要学会阅读函数的使用说明书,就可以使用它。
本章目的:学会阅读官方文档函数的说明书,并学会使用函数。
官方文档:[Built-in Functions](https://docs.python.org/3/library/functions.html)
### 示例print()
#### 基本使用方法
* 传递给它的值输出到屏幕上:
```python
print('line 1st')
print('line 2nd')
print()
print('line 4th')
```
* 一次传递多个参数用,分开,print逐个输出到屏幕上。
```python
print('Hello,', 'jack', 'mike', '...', 'and all you guys!')
```
* 变量或表达式的值插入到字符串中的时候,可以用f-string:
```python
name = 'Ann'
age = '22'
print(f'{name} is {age} years old.')
```
但以上是f-string的用法,f-string中用花括号{}括起来的部分是表达式,最终转换成字符串的时候,那些表达式值会被插入相应的位置...
```python
name = 'Ann'
age = '22'
f'{name} is {age} years old.'
```
#### print()官方文档
> print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
> * `sep=' '`:接收多个参数之后,输出时,分隔符号默认为空格,`' '`
> * `end='\n'`:输出行的末尾默认是换行符号 `'\n'`
> * `file=sys.stdout`:默认的输出对象是 `sys.stdout`(即,用户正在使用的屏幕)……
### 关键字参数
> * 位置参数(positional argument)arg
> * 关键字参数(keyword argument)kwarg:不提供时,则按默认值
#### sort()函数
> `sorted(iterable, *, key=None, reverse=False)`
### 位置参数
#### divmod(a,b)函数
### 可选位置参数(Optional Positional Arguments)
#### pow()函数,有可选的位置参数
`pow(x,y,[,z])`
> * pow(x,y)————返回值是x**y
> * pow(x,y,z)————返回值是x**y%z
### 可接收很多值的位置参数
#### print()函数
> print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
* 第一个位置参数*objects,这个位置可以接收很多个参数(或列表、元组)
#### max()函数
> max(arg1,arg2,*args[,key])
* 多个位置参数时,接收很多值的位置参数只能放置到最后一个位置
### Class也是函数
> 一些内建函数前面也写着Class,比如Class bool([x]),也是一种特殊类型的函数
### 总结
把函数当作一个产品,你是这个产品的用户,学会阅读说明书,注意可选位置参数的使用方法和关键字参数的默认值;函数的定义部分注意[]和=;函数默认返回None;

为了学会使用 Python,你以后最常访问的页面一定是这个:

> * https://docs.python.org/3/library/index.html
>
> 而最早反复阅读查询的页面肯定是其中的这两个:
> * https://docs.python.org/3/library/functions.html
> * https://docs.python.org/3/library/stdtypes.html
## 字符串

## 数据容器

## 文件

## 参数

## 化名与匿名

## 递归函数

##

## 正则表达式

## 其他
296 changes: 296 additions & 0 deletions 学习笔记/5.5字符串.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,296 @@
## 字符串
所有的值都要被转换成二进制
### 字符码表的转换
ASCII到Unicode(2^64)
```python
#单个字符转化成码值
ord('a')
#把Unicode码值转化成字符
chr(97)
```
### 字符串的标示
1. 单引号
2. 双引号
3. 三个单引号
4. 三个双引号
### 字符串与数值之间的转换
由数字构成的字符串与数值之间可以相互转换:
```python
#整数
int('3')
#浮点数
float('3.1415926')
#字符串类型
str(3.1415926)
```
input作为内建函数,可以接受一个字符串作为参数,并返回字符串的值。
> 注意input返回的是字符串,如果需要与数字比较则需要类型转换,直接比较会报错。
> input有一个可选参数,在用户输入之前会把参数输出到屏幕上。
```python
age=input('请输入你的年龄:')
if age<18:
print('未成年')
else:
print('成年')
#注意:这里会报错,因为input返回的是字符串,需要转换成数值类型
#直接修改提示语,确保用户输入的是字符串数字,再进行转换:
age=int(input('请输入你的年龄:例如:18'))
if age<18:
print('未成年')
else:
print('成年')
#int()将input返回的字符串转换成整数类型
```
### 转义符
> 本身不被当作字符,如果需要在字符串中含有,就得写\\
```python
"\\"
#有时会遇到字符串的'与字符串中的'相冲突的情况导致了系统误读。
#解决方法:
# 1. 使用转义符
'He said,it\'s fine.'
# 2. 使用双引号
"He said,it's fine."
# 3.习惯使用\'和\"表示字符串内部的引号
"He said,it\'s fine."
```
> 转义符其他用法:制表符和换行符
### 字符串的操作符
1. 拼接:```+`````` '' ```
2. 复制:```'string'*3```
3. 包含:```'string' in 'string'```
### 字符串的索引
> 字符串属于容器的一种(Container),容器可分为有序和无序两种,字符串属于有序容器,容器中的每个元素都有一个索引,通过索引可以访问到容器中的元素。
> 每个字符串都有一个索引,从0开始,到字符串长度-1
```python
s='hello world'
for char in s:
print(s.index(char),char)
```
我们可以使用*索引操作符*根据*索引**提取**字符串这个*有序容器*中的*一个或多个元素,即,其中的字符或字符串。这个 “提取” 的动作有个专门的术语,叫做 “Slicing”(切片)。索引操作符 `[]` 中可以有一个、两个或者三个整数参数,如果有两个参数,需要用 `:` 隔开。它最终可以写成以下 4 种形式:

> * `s[index]` —— 返回索引值为 `index` 的那个字符
> * `s[start:]` —— 返回从索引值为 `start` 开始一直到字符串末尾的所有字符
> * `s[start:stop]` —— 返回从索引值为 `start` 开始一直到索引值为 `stop` 的那个字符*之前*的所有字符
> * `s[:stop]` —— 返回从字符串开头一直到索引值为 `stop` 的那个字符*之前*的所有字符
> * `s[start:stop:step]` —— 返回从索引值为 `start` 开始一直到索引值为 `stop` 的那个字符*之前*的,以 `step` 为步长提取的所有字符
提醒:无论是 `range(1,2)`,或者 `random.randrange(100, 1000)` 又或者 `s[start:stop]` 都有一个相似的规律,包含左侧的 `1`, `100`, `start`,不包含右侧的 `2`, `1000`, `stop`
### 处理字符串的内建函数
```python
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

ord('\n')
ord('\t')
ord('\r')
chr(65) # 与 ord() 相对的函数
s = input('请照抄一遍这个数字 3.14: ')
int('3')
# int(s) 这一句会报错…… 所以暂时注释掉了
float(s) * 9
len(s)
print(s*3)
```
### 处理字符串的Method
字符串一个对象,更准确说是str类(Class str)的对象,它有一些方法(Method),可以用来处理字符串。(类>对象>方法)
#### 大小写转换
```python
str.upper()
str.lower()
str.capitalize()
str.swapcase()
str.casefold()
str..title()
#举例:
s='Now is better than never.'
s.capitalize()#句首字母大写
s.title()#每个单词首字母大写
```
#### 搜索与替换
官方文档是这么写的:
1. str.count
> `str.count(sub[,start[,end]])`
下面的函数说明加了默认值,以便初次阅读更容易理解:

> `str.count(sub [,start=0[, end=len(str)]])`
这里的方括号 `[]` 表示该参数可选;方括号里再次嵌套了一个方括号,这个意思是说,在这个可选参数 `start` 出现的情况下,还可以再有一个可选参数 `end`

`=` 表示该参数有个默认值。上述这段说明如果你感到熟悉的话,说明前面的内容确实阅读到位了…… 与大量 “前置引用” 相伴随的是知识点的重复出现。


> * 只给定 `sub` 一个参数的话,于是从第一个字符开始搜索到字符串结束;
> * 如果,随后给定了一个可选参数的话,那么它是 `start`,于是从 `start` 开始,搜索到字符串结束;
> * 如果 `start` 之后还有参数的话,那么它是 `end`;于是从 `start` 开始,搜索到 `end - 1` 结束(即不包含索引值为 `end` 的那个字符)。
>
> 返回值为字符串中 `sub` 出现的次数。
注意:字符串中第一个字符的索引值是 `0`

2. str.find
> 找到sub在字符串中的第一个后,返回索引值,找不到就返回-1
3. str.rfind
> 找到sub在字符串中的最后一个后,返回索引值,找不到就返回-1
4. str.index/str.rindex
> 与str.find/str.rfind类似,但是找不到会报错
5. str.startswitch
```str.startswith(prefix[, start[, end]])```
> 判断prefix字符串是否以某个子字符串起始的
6. str.endswith
```str.endswith(suffix[, start[, end]])```
> 查找suffix是否在目标字符串以子字符串结束的
> 查找前可以使用in来确认子字符串是否存在于目标字符串中
7. str.replace
> 替换字符串中的子字符串
```str.replace(old, new[, count])```
> 替换count个实例
8. str.expandtabs
> 将字符串中的tab转换成空格
```str.expandtabs([tabsize=8])```
```python
s1="Specail\tcases\tare\tsimple"
print(s1.expandtabs(2))
```

#### 去除子字符
1. str.strip([chars])
> 一般用来去除字符串首尾的所有空白,包括空格、TAB、换行符等
```python
s="\r \t Simple is better than complex. \n \t"
s
s.strip()
```
> 如果给定参数,那么参数中所有字母都会被从首尾去除,直到首尾不再包含
```python
s="Simple is better than complex."
s
s.strip("Six.p")# p 全部处理完之后,p 并不在首尾,所以原字符串中的 p 字母不受影响;
s.strip("pSix.mle")# 这一次,首尾的 p 被处理了…… 参数中的字符顺序对结果没有影响,换成 Sipx.mle 也一样……
```
2. str.lstrip()
> 只对左侧处理
```python
#str.lstrip([chars])
s="Simple is better than complex."
s
s.lstrip("Six.p")
s.lstrip("pSix.mle")
```
3. str.rstrip()
> 只对右侧处理
```python
#str.rstrip([chars])
s="Simple is better than complex."
s
s.rstrip("Six.p")
s.rstrip("pSix.mle")
```

#### 拆分字符串
计算机擅长处理格式化的数据,excle或numbers可以导出csv文件,这是文本文件。里面的每一行可能由多个数据构成,数据之间用,分隔。
1. str.splitlines()
> 将字符串拆分成一个列表,每个元素是字符串中的每一行(根据/n或行进行拆分)
2. str.split()
> 根据分隔符进行拆分
> str.split([sep=None,maxsplit=-1])
> 默认按照None(空白\t,\r等)进行拆分,也可以设置成,等。-1表示拆分全部,也可以设置拆分的次数。
3. str.partition()

#### 拼接字符串
1. str.join()
> 将字符串列表拼接成一个字符串
#### 字符串排版
1. str.center()
> 字符串居中,并使用指定字符填充,前提是设定整行长度
```python
#str.center(width[,fillchar])
s='Sparse is better than dense.'
s.title().center(60)
s.title().center(60,'=')
s.title().center(10)#如果宽度参数小于字符串长度,返回原字符串
#字符串向左或右对其
s.title().ljust(60)
s.title().rjust(60,'.')
```
2. str.zfill()
> 字符串右对齐,使用0填充
```python
#str.zfill(width)
for i in range(1,10):
filename=str(i).zfill(3)+'.mp3'
print(filename)
```
#### 格式化字符串
> 格式化字符串指的是特定变量插入字符串指定位置的过程。
1. str.format()
> `str.format(*args, **kwargs)`
作用:
> * 在一个字符串中,插入一个或者多个占位符 —— 用大括号 `{}` 括起来;
> * 而后将 `str.format()` 相应的参数,依次插入占位符中;
2. f-string
#### 使用f-string
> f-string 是 Python 3.6 引入的,它是一种格式化字符串的新方法。
> f-string和str.format()类似,但是写法更简单。
```python
name='John'
age=23
print('{} is {} years old.'.format(name,age))
#不写占位符索引的情况下,默认占位符从0开始,即0,1,2,3...(占位符数量-1)
# 即'{}{}'.format(a,b)和'{0}{1}'.format(a,b)是一样的。

#'{0} is {2} years old.'.format(name,age)会报错,因为占位符索引超出了占位符数量。

#str.format()里可以直接写表达式...
print('{} is a grown up? {} '.format(name,age>=18))

#f-string
name='Jack'
age=25
print(f'{name} is {age} years old')
print(f'{name} is a grown up? {age>=18}')
```
> .format()和f-string的区别:插入占位符和调用format并传参;直接把变量写在占位符里。
> 但.format可以改变参数索引顺序,更为灵活。
```python
name='John'
age=28
'{1} is {0} years old.'.format(name,age)
```
### 字符串属性
字符串一系列Methods,返回的是布尔值,用来判断字符串的构成属性:
1. str.isalnum()
2. str.isalpha()
3. str.isdigit()
4. str.islower()
5. str.isupper()
6. str.isspace()
7. str.istitle()
8. str.isnumeric

```python
# 字符串属性
# 1. isalnum() 判断字符串是否由字母和数字组成
# 2. isalpha() 判断字符串是否由字母组成
# 3. isascii()
# 4. isdecimal() 判断字符串是否由十进制组成
# 5. isdigit() 判断字符串是否由数字组成
# 6. isnumeric() 判断字符串是否由数字组成
# 7. islower() 判断字符串是否由小写字母组成
# 8. isupper() 判断字符串是否由大写字母组成
# 9. istitle() 判断字符串是否符合标题格式
# 10. isspace() 判断字符串是否由空白字符组成
# 11. isprintable() 判断字符串是否由可打印字符组成
```
....
### 总结

![Alt text](image-2.png)

![Alt text](image-3.png)

461 changes: 461 additions & 0 deletions 学习笔记/5.7数据容器.md

Large diffs are not rendered by default.

20 changes: 20 additions & 0 deletions 学习笔记/Arbitrary Keyword Argument接收很多值.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
def say_hi(**names_greetings):
for name,greetings in names_greetings.items():
print(f'{name},{greetings}')
say_hi(mike='hello',ann='my daring',john='Hi')

#直接使用字典的迭代方式:分别定义变量来接收key-value
def say_hi1(**names_greetings):
for name, greeting in names_greetings.items():
print(f'{greeting}, {name}!')

a_dictionary = {'mike':'Hello', 'ann':'Oh, my darling', 'john':'Hi'}
say_hi1(**a_dictionary)

say_hi1(**{'mike':'Hello', 'ann':'Oh, my darling', 'john':'Hi'})

#在函数内部,选择不同的方式去迭代字典:循环时直接保存key-value到变量,再索引取出
def say_hi_2(**names_greetings):
for name in names_greetings:
print(f'{names_greetings[name]}, {name}!')
say_hi_2(mike='Hello', ann='Oh, my darling', john='Hi')
314 changes: 314 additions & 0 deletions 学习笔记/ELIZA.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,314 @@
# %load https://raw.githubusercontent.com/jezhiggins/eliza.py/master/eliza.py
#----------------------------------------------------------------------
# eliza.py
#
# a cheezy little Eliza knock-off by Joe Strout
# with some updates by Jeff Epler
# hacked into a module and updated by Jez Higgins
#----------------------------------------------------------------------

import string
import re
import random

class eliza:
def __init__(self):
self.keys = list(map(lambda x:re.compile(x[0], re.IGNORECASE),gPats))
self.values = list(map(lambda x:x[1],gPats))

#----------------------------------------------------------------------
# translate: take a string, replace any words found in dict.keys()
# with the corresponding dict.values()
#----------------------------------------------------------------------
def translate(self,str,dict):
words = str.lower().split()
keys = dict.keys();
for i in range(0,len(words)):
if words[i] in keys:
words[i] = dict[words[i]]
return ' '.join(words)

#----------------------------------------------------------------------
# respond: take a string, a set of regexps, and a corresponding
# set of response lists; find a match, and return a randomly
# chosen response from the corresponding list.
#----------------------------------------------------------------------
def respond(self,str):
# find a match among keys
for i in range(0, len(self.keys)):
match = self.keys[i].match(str)
if match:
# found a match ... stuff with corresponding value
# chosen randomly from among the available options
resp = random.choice(self.values[i])
# we've got a response... stuff in reflected text where indicated
pos = resp.find('%')
while pos > -1:
num = int(resp[pos+1:pos+2])
resp = resp[:pos] + \
self.translate(match.group(num),gReflections) + \
resp[pos+2:]
pos = resp.find('%')
# fix munged punctuation at the end
if resp[-2:] == '?.': resp = resp[:-2] + '.'
if resp[-2:] == '??': resp = resp[:-2] + '?'
return resp

#----------------------------------------------------------------------
# gReflections, a translation table used to convert things you say
# into things the computer says back, e.g. "I am" --> "you are"
#----------------------------------------------------------------------
gReflections = {
"am" : "are",
"was" : "were",
"i" : "you",
"i'd" : "you would",
"i've" : "you have",
"i'll" : "you will",
"my" : "your",
"are" : "am",
"you've": "I have",
"you'll": "I will",
"your" : "my",
"yours" : "mine",
"you" : "me",
"me" : "you"
}

#----------------------------------------------------------------------
# gPats, the main response table. Each element of the list is a
# two-element list; the first is a regexp, and the second is a
# list of possible responses, with group-macros labelled as
# %1, %2, etc.
#----------------------------------------------------------------------
gPats = [
[r'I need (.*)',
[ "Why do you need %1?",
"Would it really help you to get %1?",
"Are you sure you need %1?"]],

[r'Why don\'?t you ([^\?]*)\??',
[ "Do you really think I don't %1?",
"Perhaps eventually I will %1.",
"Do you really want me to %1?"]],

[r'Why can\'?t I ([^\?]*)\??',
[ "Do you think you should be able to %1?",
"If you could %1, what would you do?",
"I don't know -- why can't you %1?",
"Have you really tried?"]],

[r'I can\'?t (.*)',
[ "How do you know you can't %1?",
"Perhaps you could %1 if you tried.",
"What would it take for you to %1?"]],

[r'I am (.*)',
[ "Did you come to me because you are %1?",
"How long have you been %1?",
"How do you feel about being %1?"]],

[r'I\'?m (.*)',
[ "How does being %1 make you feel?",
"Do you enjoy being %1?",
"Why do you tell me you're %1?",
"Why do you think you're %1?"]],

[r'Are you ([^\?]*)\??',
[ "Why does it matter whether I am %1?",
"Would you prefer it if I were not %1?",
"Perhaps you believe I am %1.",
"I may be %1 -- what do you think?"]],

[r'What (.*)',
[ "Why do you ask?",
"How would an answer to that help you?",
"What do you think?"]],

[r'How (.*)',
[ "How do you suppose?",
"Perhaps you can answer your own question.",
"What is it you're really asking?"]],

[r'Because (.*)',
[ "Is that the real reason?",
"What other reasons come to mind?",
"Does that reason apply to anything else?",
"If %1, what else must be true?"]],

[r'(.*) sorry (.*)',
[ "There are many times when no apology is needed.",
"What feelings do you have when you apologize?"]],

[r'Hello(.*)',
[ "Hello... I'm glad you could drop by today.",
"Hi there... how are you today?",
"Hello, how are you feeling today?"]],

[r'I think (.*)',
[ "Do you doubt %1?",
"Do you really think so?",
"But you're not sure %1?"]],

[r'(.*) friend (.*)',
[ "Tell me more about your friends.",
"When you think of a friend, what comes to mind?",
"Why don't you tell me about a childhood friend?"]],

[r'Yes',
[ "You seem quite sure.",
"OK, but can you elaborate a bit?"]],

[r'(.*) computer(.*)',
[ "Are you really talking about me?",
"Does it seem strange to talk to a computer?",
"How do computers make you feel?",
"Do you feel threatened by computers?"]],

[r'Is it (.*)',
[ "Do you think it is %1?",
"Perhaps it's %1 -- what do you think?",
"If it were %1, what would you do?",
"It could well be that %1."]],

[r'It is (.*)',
[ "You seem very certain.",
"If I told you that it probably isn't %1, what would you feel?"]],

[r'Can you ([^\?]*)\??',
[ "What makes you think I can't %1?",
"If I could %1, then what?",
"Why do you ask if I can %1?"]],

[r'Can I ([^\?]*)\??',
[ "Perhaps you don't want to %1.",
"Do you want to be able to %1?",
"If you could %1, would you?"]],

[r'You are (.*)',
[ "Why do you think I am %1?",
"Does it please you to think that I'm %1?",
"Perhaps you would like me to be %1.",
"Perhaps you're really talking about yourself?"]],

[r'You\'?re (.*)',
[ "Why do you say I am %1?",
"Why do you think I am %1?",
"Are we talking about you, or me?"]],

[r'I don\'?t (.*)',
[ "Don't you really %1?",
"Why don't you %1?",
"Do you want to %1?"]],

[r'I feel (.*)',
[ "Good, tell me more about these feelings.",
"Do you often feel %1?",
"When do you usually feel %1?",
"When you feel %1, what do you do?"]],

[r'I have (.*)',
[ "Why do you tell me that you've %1?",
"Have you really %1?",
"Now that you have %1, what will you do next?"]],

[r'I would (.*)',
[ "Could you explain why you would %1?",
"Why would you %1?",
"Who else knows that you would %1?"]],

[r'Is there (.*)',
[ "Do you think there is %1?",
"It's likely that there is %1.",
"Would you like there to be %1?"]],

[r'My (.*)',
[ "I see, your %1.",
"Why do you say that your %1?",
"When your %1, how do you feel?"]],

[r'You (.*)',
[ "We should be discussing you, not me.",
"Why do you say that about me?",
"Why do you care whether I %1?"]],

[r'Why (.*)',
[ "Why don't you tell me the reason why %1?",
"Why do you think %1?" ]],

[r'I want (.*)',
[ "What would it mean to you if you got %1?",
"Why do you want %1?",
"What would you do if you got %1?",
"If you got %1, then what would you do?"]],

[r'(.*) mother(.*)',
[ "Tell me more about your mother.",
"What was your relationship with your mother like?",
"How do you feel about your mother?",
"How does this relate to your feelings today?",
"Good family relations are important."]],

[r'(.*) father(.*)',
[ "Tell me more about your father.",
"How did your father make you feel?",
"How do you feel about your father?",
"Does your relationship with your father relate to your feelings today?",
"Do you have trouble showing affection with your family?"]],

[r'(.*) child(.*)',
[ "Did you have close friends as a child?",
"What is your favorite childhood memory?",
"Do you remember any dreams or nightmares from childhood?",
"Did the other children sometimes tease you?",
"How do you think your childhood experiences relate to your feelings today?"]],

[r'(.*)\?',
[ "Why do you ask that?",
"Please consider whether you can answer your own question.",
"Perhaps the answer lies within yourself?",
"Why don't you tell me?"]],

[r'quit',
[ "Thank you for talking with me.",
"Good-bye.",
"Thank you, that will be $150. Have a good day!"]],

[r'(.*)',
[ "Please tell me more.",
"Let's change focus a bit... Tell me about your family.",
"Can you elaborate on that?",
"Why do you say that %1?",
"I see.",
"Very interesting.",
"%1.",
"I see. And what does that tell you?",
"How does that make you feel?",
"How do you feel when you say that?"]]
]

#----------------------------------------------------------------------
# command_interface
#----------------------------------------------------------------------
def command_interface():
print('Therapist\n---------')
print('Talk to the program by typing in plain English, using normal upper-')
print('and lower-case letters and punctuation. Enter "quit" when done.')
print('='*72)
print('Hello. How are you feeling today?')

s = ''
therapist = eliza();
while s != 'quit':
try:
s = input('> ')
except EOFError:
s = 'quit'
print(s)
while s[-1] in '!.':
s = s[:-1]
print(therapist.respond(s))


if __name__ == "__main__":
command_interface()
7 changes: 7 additions & 0 deletions 学习笔记/Keyword Arguments设定默认值.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
def say_hi(greetings,*names,capitalized=False):
for name in names:
if capitalized:
name=name.capitalize()
print(f'{greetings},{name}!')
say_hi('Hello','mike','john','zeo')
say_hi('Hello','mike','john','zeo',capitalized=True)
14 changes: 14 additions & 0 deletions 学习笔记/divmod函数.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

divmod(11, 3)
a, b = divmod(11, 3)
print(a)
print(b)

divmod(3, 11)
a, b = divmod(3, 11)
print(a)
print(b)

#元组包典型赋值写法:divmod返回元组包括商和余数,通过a,b=divmod(3,11)赋值给a,b。
10 changes: 10 additions & 0 deletions 学习笔记/file.writelines().py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#把列表写入到文件中
a_list=['first line test content\n','second line test content\n','third line test content\n']
f=open(r'\Users\Administrator\Documents\GitHub\the-craft-of-selfteaching\学习笔记\writelines-test-file.txt','w')
f.writelines(a_list)
f.close()

f=open(r'\Users\Administrator\Documents\GitHub\the-craft-of-selfteaching\学习笔记\writelines-test-file.txt','r')
for line in f.readlines():
print(line)
f.close()
14 changes: 14 additions & 0 deletions 学习笔记/for循环1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
for a in range(12):
print(f'value of a:{a}')
#python中for循环的用法更直接,取代了其他语言中使用的计数器形式

#使用list的方式打印range循环的整数数列
print(list(range(10)))
#为range传递两个参数start,end
print(list(range(2,10)))
#step步长,每隔几个整数打印一次
for i in range(1,10,3):
print(i)
#负数步长
print(list(range(0,-10,-1)))

7 changes: 7 additions & 0 deletions 学习笔记/if-奇偶数.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import random
r=random.randrange(1,1000)

if r%2==0:
print(f'{r} is even')
else:
print(f'{r} is odd')
21 changes: 21 additions & 0 deletions 学习笔记/if-骰子.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import random
r=random.randrange(2,13)

if r==7:
print('Draw')
elif r<11:
print('Small')
elif r>7:
print('Big!')

#模拟投飞了情况
e=random.randrange(0,13)

if e==7:
print('Draw')
elif e>=2 and e<7:
print('Small')
elif e>7:
print('Big!')
else:
print('投飞了')
Binary file added 学习笔记/image-1.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added 学习笔记/image-2.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added 学习笔记/image-3.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added 学习笔记/image.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
4 changes: 4 additions & 0 deletions 学习笔记/join.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
s=''
t=['p','y','t','h','o','n']
s=s.join(t)
print(s)
7 changes: 7 additions & 0 deletions 学习笔记/print()官方文档.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import sys # 如果没有这一行,代码会报错

print('Hello', 'world!') # 下一行的输出和这一行相同
print('Hello', 'world!', sep=' ', end='\n', file=sys.stdout, flush=False)
print('Hello', 'world!', sep='-', end='\t')
print('Hello', 'world!', sep='~++') # 上一行的末尾是 \t,所以,这一行并没有换行显示
print('Hello', 'world!', sep='\n') # 参数之间用换行 \n 分隔
1 change: 1 addition & 0 deletions 学习笔记/print()返回值.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
print(print('hello world'))
4 changes: 4 additions & 0 deletions 学习笔记/print函数.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
name='Ann'
age=18
print(f'my name is {name},age is {age}')
#注意使用了f-string的功能
3 changes: 3 additions & 0 deletions 学习笔记/readlines读写文件test-file.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
first line
second line
third line
3 changes: 3 additions & 0 deletions 学习笔记/readline读写文件test-file.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
first line
second line
third line
8 changes: 8 additions & 0 deletions 学习笔记/reguluar expression1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@

import re
with open(r'\Users\Administrator\Documents\GitHub\the-craft-of-selfteaching\regex-target-text-sample.txt','r') as f:
str=f.read()
pttn=r'beg[iau]ns?'
s=re.findall(pttn,str)
print(s)

19 changes: 19 additions & 0 deletions 学习笔记/replace和expandtabs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#replace() 方法把字符串中的 old(旧字符串) 替换成 new(新字符串),如果指定第三个参数max,则替换不超过 max 次。
s="""Simple is better than complex.
Complex is better than complicated."""
print(s)
#str.replace(old, new[, count])
print("s.replace:",\
s.lower().replace("is","IS"))
print("s.replace:",\
s.lower().replace("is","IS",1))
#count=1,只替换一次
print("s.replace:",\
s.lower().replace("is","[]",2))
#expandtabs() 方法把字符串中的 tab 符号('\t')转为空格,tab 符号('\t')默认的空格数是 8。
#str.expandtabs(tabsize=8)
s1="Specail\tcases\tare\tsimple"
print(s1)
print("str.expandtabs:",\
s1.expandtabs())
print(s1.expandtabs(2))
5 changes: 5 additions & 0 deletions 学习笔记/sort()函数.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

print(sorted('abdc'))
print(sorted('abdc', reverse=True))
24 changes: 24 additions & 0 deletions 学习笔记/startswith-endswitch.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
s="""Simple is better than complex.
Complex is better than complicated."""
#str.startswith(prefix[, start[, end]])
print("s.lower().startswitch('S'):",\
s.lower().startswith('S'))
print("s.lower().startswitch('s'):",\
s.lower().startswith('s'))
print("s.lower().startswitch('b',10):",\
s.lower().startswith('b',10))
print("s.lower().startswitch('e',11,20):",\
s.lower().startswith('e',11,20))

#str.endswith(suffix[, start[, end]])
print("s.lower().endswith('.'):",\
s.lower().endswith('.'))
print("s.lower().endswith('.',10):",\
s.lower().endswith('.',10))
print("s.lower().endswith('.',10,20):",\
s.lower().endswith('.',10,20))

#找sub/prefix/suffix前确认子字符串是否在需要找的字符串中,可以使用in操作符
print('mpl' in s)
print('mple is' in s)
print('mple iso' in s)
9 changes: 9 additions & 0 deletions 学习笔记/str.count.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
s = """Simple is better than complex.
Complex is better than complicated."""
print(s.lower().count('mp'))
print(s.lower().count('mp', 10))
print(s.lower().count('mp', 10, 30))
a="hello world"
print(a.lower().count('l'))
print(a.lower().count('l',4))
print(a.lower().count('l',1,4))
24 changes: 24 additions & 0 deletions 学习笔记/str.find-rfind-index-rindex.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
#str.find(sub[,start[,end]])
print("example str.find():")
s="""Simple is better than complex.
Complex is better than complicated."""
print(s.lower().find('mpl'))
print(s.lower().find('mpl',10))
print(s.lower().find('mpl',10,20))
# 没有找到就返回-1

print("example str.rfind():")
#str.rfind(sub[,start[,end]])
#返回最后sub出现的位置,find是最早出现的位置
print(s.lower().rfind('mpl'))
print(s.lower().rfind('mpl',10))
print(s.lower().rfind('mpl',10,20))

print('Example str.index():')
#str.index(sub[,start[,end]])
#作用与find相同,如果没找到,就触发ValueError异常
print(s.lower().index('mpl'))
print(s.lower().index('mpl',10))
#str.rindex(sub[,start[,end]])
#作用与rfind相同,如果没找到,就触发ValueError异常
print(s.lower().rindex('mpl'))
Empty file added 学习笔记/test-file.txt
Empty file.
18 changes: 18 additions & 0 deletions 学习笔记/with打包文件操作.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import os
with open(r'\Users\Administrator\Documents\GitHub\the-craft-of-selfteaching\学习笔记\with test-file.txt','w') as f:
f.write('first line\nsecond line\n third line\n')

with open(r'\Users\Administrator\Documents\GitHub\the-craft-of-selfteaching\学习笔记\with test-file.txt','r') as f:
for line in f.readlines():
print(line)
file_name=r'\Users\Administrator\Documents\GitHub\the-craft-of-selfteaching\学习笔记\with test-file.txt'

if os.path.exists(file_name):
os.remove(file_name)
print(f'{file_name} deleted')
else:
print(f'{file_name} does not exists')

# 用with语句块的另外一个好处就是不用写file.close()了

# with ... as ...
3 changes: 3 additions & 0 deletions 学习笔记/writelines-test-file.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
first line test content
second line test content
third line test content
12 changes: 12 additions & 0 deletions 学习笔记/传递Arbitary Positional Aruguments.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#向*Positional Arguments传递容器
def say_hi(*names):
for name in names:
print(f'Hi,{name}!')
def say_hi_1(**names):
for key,values in names.items():
print(f'Hi,{key}:{values}!')

names={"ann","jack","john"}
a_dictionary = {'ann': 2321, 'mike': 8712, 'joe': 7610}
say_hi(*names)
say_hi_1(**a_dictionary)
4 changes: 4 additions & 0 deletions 学习笔记/传递多个Arbitary Positional Aruguments.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
def say_hi(greetings,*names):
for name in names:
print(f'{greetings},{name.capitalize()}!')
say_hi('Hello','mike','john','jack')
59 changes: 59 additions & 0 deletions 学习笔记/列表append copy extend insert reverse.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import random
n=3
a_list=[random.randrange(65,91) for i in range(n)]
b_list=[chr(random.randrange(65,91)) for i in range(n)]
print(a_list)
c_list=a_list+b_list+a_list*2
print(c_list)

#appened()方法
c_list.append('100')
print(c_list)

#clear()方法
print(a_list)
a_list.clear()
print(a_list)

#copy()方法
d_list=c_list.copy()
print(d_list)
del d_list[6:8]
print(d_list)
print(c_list)

#.copy和赋值不同
e_list=d_list
del e_list[6:8]
print(e_list)
print(d_list) #对elist进行操作时,d_list也同步发生了变化
print(id(e_list) == id(d_list)) # 输出 True
# 证明e_list=d_list这里并非创建了一个列表,而是将两个列表指向了同一个内存地址,因此修改其中任何一个,两者会同时发生改变。

#在末尾追加一个列表
print(a_list)
print(c_list)
a_list.extend(c_list)
print(a_list)
#注意这里extend与append的差异:extend将列表中元素逐一添加到列表末尾,而append将c_list直接作为一整个子列表添加到目标列表末尾:[X,X,[A,B]]
#因此:append是将列表作为整体添加,extend是拆分列表,将其中元素逐一添加。

#在索引位置插入一个元素
print(a_list)
a_list.insert(1,'example')
print(a_list) #插入到索引位置,后续元素依次更新索引
a_list.insert(2,'exemple')
print(a_list)

# 报错:a_list.sort(),因为此时a_list中元素类型不统一

#排序
print(a_list)
a_list.reverse()
print(a_list)
# 注意reversereverse() 通过直接交换索引位置的元素完成反转,不触发任何比较操作。即使元素类型混杂,只要列表结构合法,反转就能正常执行。

x=a_list.reverse()
print(x)
#同时reverse()方法对当前序列进行操作,返回值为None,因此不能直接赋值给变量

32 changes: 32 additions & 0 deletions 学习笔记/列表pop remove del.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
import random
n=3
a_list=[random.randrange(65,91) for i in range(n)]
print(a_list)

#插入
a_list.insert(1,'example')
print(a_list)

#删除
#remove去除example,如果有多个,只去除第一个
a_list.remove('example')
print(a_list)

#pop删除并返回被删除的值
p=a_list.pop(2)
print(a_list)
print(p)

#pop del 和remove的区别
a_list.insert(2,'example')
a_list.insert(2,'example')
a_list.insert(2,'example')
print(a_list)
del a_list[2]
print(a_list)

print(a_list.remove('example'))# 返回None
print(a_list)

#del直接删除了数列中元素,pop删除并返回被删除的值,remove删除第一个元素,并返回None

36 changes: 36 additions & 0 deletions 学习笔记/列表sort()-Methods.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import random
n=10
a_list=[random.randrange(1,100) for i in range(n)]
print(f'a_list comprehends {len(a_list)} random numbers:\n',a_list)

a_list.sort()
print('the list sorted:\n',a_list)
#sort()函数默认升序排列
#降序排列,修改参数reverse=True
a_list.sort(reverse=True)
print('the list sorted reversely:\n',a_list)

#对列表内部的字符串元素也可以进行排序
c_list=[chr(random.randrange(65,91)) for i in range(n)]
print(f'c_list comprehends {len(c_list)} random letters:\n',c_list)

c_list.sort()
print('the list sorted:\n',c_list)

c_list.sort(reverse=True)
print('the list sorted reversely:\n',c_list)

print(c_list)

d_list=[chr(random.randrange(65,91))+\
chr(random.randrange(97,123))\
for i in range(n)]
#在代码行末加上\,表示换行

print(f'd_list comprehends {len(d_list)} random letters:\n',d_list)

d_list.sort()
print('the list sorted:\n',d_list)

d_list.sort(key=str.lower,reverse=True)
print('the list sorted reversely:\n',d_list)
17 changes: 17 additions & 0 deletions 学习笔记/列表可用的内建函数.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import random
n=3
#生成3个随机数
a_list=[random.randrange(65,91) for i in range(n)]
b_list=[chr(random.randrange(65,91)) for i in range(n)]
print(a_list)
print(b_list)
#操作列表
c_list=a_list+b_list+a_list*2
print(c_list)

#内建函数操作len()、max()、min()、sum()
print(len(c_list))
print(max(b_list))
print(min(b_list))
# 根据Unicode码比较
print('X' not in b_list)
8 changes: 8 additions & 0 deletions 学习笔记/列表操作符.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
a_list=[1,2,3]
b_list=[4,5,6]
c_list=a_list+b_list*3
print(c_list)
d=7 not in c_list
print(d)
e=a_list>b_list
print(e)
26 changes: 26 additions & 0 deletions 学习笔记/列表索引.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import random
n=3
a_list=[random.randrange(65,91) for i in range(n)]
b_list=[chr(random.randrange(65,91)) for i in range(n)]
print(a_list)
print(b_list)
c_list=a_list+b_list+a_list*2
print(c_list)

print()
#根据索引提取(Slicing)
print(c_list[3]) #返回索引值为3的元素值
print(c_list[:]) #返回整个列表
print(c_list[5:]) #返回从索引为5开始到列表末尾的所有元素
print(c_list[:3]) #返回从列表开头到索引为3的所有元素
print(c_list[2:6]) #从索引2开始,直到索引6之前(不包括6)

print(c_list)
#根据索引删除
del c_list[3] #del是一个命令
print(c_list)
del c_list[5:8] #删除最新的c_list列表对应的[5,8)
print(c_list)
#根据索引替换
c_list[1:5:2]=['a',2] #索引1开始,5结束,2step替换一次,依次替换['a',2]
print(c_list)
8 changes: 8 additions & 0 deletions 学习笔记/创建文件.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
f=open(r'\Users\Administrator\Documents\GitHub\the-craft-of-selfteaching\学习笔记\test-file.txt','w')
print(f.name)
f.close()
#路径三种方法:
#1. r'\
#2. 使用双反斜杠\\
#3. 使用正斜杠:“/”

9 changes: 9 additions & 0 deletions 学习笔记/删除文件.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import os
f=open(r'\Users\Administrator\Documents\GitHub\the-craft-of-selfteaching\学习笔记\删除文件test-file.txt','w')
print(f.name)
f.close()#关闭文件,否则无法删除文件
if os.path.exists(f.name):
os.remove(f.name)
print(f'{f.name} deleted')
else:
print(f'{f.name} does not exist')
6 changes: 6 additions & 0 deletions 学习笔记/同时迭代多个容器.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
#zip函数
chars='abcdefghijklmnopqrstuvwxyz'
nums=range(1,27)
#注意range左闭右开
for c,n in zip(chars,nums):
print(f"Let's assume {c} represents {n}.")
13 changes: 13 additions & 0 deletions 学习笔记/基础_质数.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
def is_prime(n):
if n<2:
return False
if n==2:
return True
for m in range(2,int(n**0.5)+1):
if n%m==0:
return False
else:
return True
for i in range(50,100):
if is_prime(i):
print(i)
12 changes: 12 additions & 0 deletions 学习笔记/字符串属性.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# 字符串属性
# 1. isalnum() 判断字符串是否由字母和数字组成
# 2. isalpha() 判断字符串是否由字母组成
# 3. isascii()
# 4. isdecimal() 判断字符串是否由十进制组成
# 5. isdigit() 判断字符串是否由数字组成
# 6. isnumeric() 判断字符串是否由数字组成
# 7. islower() 判断字符串是否由小写字母组成
# 8. isupper() 判断字符串是否由大写字母组成
# 9. istitle() 判断字符串是否符合标题格式
# 10. isspace() 判断字符串是否由空白字符组成
# 11. isprintable() 判断字符串是否由可打印字符组成
16 changes: 16 additions & 0 deletions 学习笔记/字符串格式化.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
name='John'
age=23
print('{} is {} years old.'.format(name,age))
#不写占位符索引的情况下,默认占位符从0开始,即0,1,2,3...(占位符数量-1)
# 即'{}{}'.format(a,b)和'{0}{1}'.format(a,b)是一样的。

#'{0} is {2} years old.'.format(name,age)会报错,因为占位符索引超出了占位符数量。

#str.format()里可以直接写表达式...
print('{} is a grown up? {} '.format(name,age>=18))

#f-string
name='Jack'
age=25
print(f'{name} is {age} years old')
print(f'{name} is a grown up? {age>=18}')
20 changes: 20 additions & 0 deletions 学习笔记/拆分字符串.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#文本文件保存到某个变量之中,经常需要对字符串进行操作
#str.splitlines()
#str.split()
#str.partition()
s = """Name,Age,Location
John,18,New York
Mike,22,San Francisco
Janny,25,Miami
Sunny,21,Shanghai"""
print(s)
print(s.splitlines())
#s.splitlines()返回的是一个列表(List),由被拆分的每一行作为其中的元素。
#str.split()根据分隔符拆分
r=s.splitlines()[2]#取出返回值2的那一行
print(r)
print(r.split())#默认使用None分割(各种空白,比如,\t 和 \r 都被当作 None)
print(r.split(sep=","))#使用","分割
print(r.split(","))#使用","分割,也可以省略sep
print(r.split(",",maxsplit=0))#拆分0次,即不拆分
print(r.split(",",maxsplit=-1))#全部拆分
6 changes: 6 additions & 0 deletions 学习笔记/斐波那契数列.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
n=1000
a,b=0,1
while a<n:
print(a,end=' ')
a,b=b,a+b
print()
36 changes: 36 additions & 0 deletions 学习笔记/读写readline()-readlines().py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
f=open(r'\Users\Administrator\Documents\GitHub\the-craft-of-selfteaching\学习笔记\readline读写文件test-file.txt','w')
f.write('first line\nsecond line\nthird line')
f.close()

f=open(r'\Users\Administrator\Documents\GitHub\the-craft-of-selfteaching\学习笔记\readline读写文件test-file.txt','r')
s=f.readline()
print(s)
s=f.readline()
print(s)
f.close()
#使用str.strip():\n被去掉了
f1=open(r'\Users\Administrator\Documents\GitHub\the-craft-of-selfteaching\学习笔记\readline读写文件test-file.txt','w')
f1.write('first line\nsecond line\nthird line\n')
f1.close()

f1=open(r'\Users\Administrator\Documents\GitHub\the-craft-of-selfteaching\学习笔记\readline读写文件test-file.txt','r')
s1=f1.readline().strip()
print(s1)
s1=f1.readline().strip()
print(s1)
s1=f1.readline().strip()
print(s1)
f1.close()

#使用readlines()读取文件中的每一行,并作为一个列表返回
f2=open(r'\Users\Administrator\Documents\GitHub\the-craft-of-selfteaching\学习笔记\readlines读写文件test-file.txt','w')
f2.write('first line\nsecond line\nthird line\n')
f2.close()

f2=open(r'\Users\Administrator\Documents\GitHub\the-craft-of-selfteaching\学习笔记\readlines读写文件test-file.txt','r')
s2=f2.readlines()
print(s2)
for index, line in enumerate(s2):
#直接使用enumerate获取列表的索引和值,同时在for后面定义接收的变量:
print(f'第{index+1}行:\n 内容:{line}')
f2.close()
12 changes: 12 additions & 0 deletions 学习笔记/读写文件.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
f=open(r'\Users\Administrator\Documents\GitHub\the-craft-of-selfteaching\学习笔记\读写文件test-file.txt','w')
f.write('first line\nsecond line\nthird line')
f.close()

f=open(r'\Users\Administrator\Documents\GitHub\the-craft-of-selfteaching\学习笔记\读写文件test-file.txt','r')
s=f.read()
print(s)
f.close()




3 changes: 3 additions & 0 deletions 学习笔记/读写文件test-file.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
first line
second line
third line
20 changes: 20 additions & 0 deletions 学习笔记/进阶cotinue break_质数.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
#写法一:print(n)属于语句块for i in range(2,n):
for n in range(2,100):
if n==2:
print(n)
continue
for i in range(2,n):
if (n%i)==0:
break
print(n)
#相当于只针对for-break的执行了一次print(n)
#写法二:print(n)不属于语句块for i in range(2,n):
for n in range(2,100):
if n==2:
print(n)
continue
for i in range(2,n):
if (n%i)==0:
break
print(n)
#相当于针对每个i都执行了一次print(n)
55 changes: 55 additions & 0 deletions 计算字母求和程序.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
#ord()函数,直接使用字母的ASCII进行计算
print(f"a的ASCII码:{ord('a')}")
#a--97,即对应到1为ord('a')-96
#以knowledge为例:
word='knowledge'
sum=0
for char in word:
sum+=ord(char)-96
print(f'knowledge的ASCII:{sum}')
#把以上计算过程打包为一个函数
def sum_of_word(word):
sum=0
for char in word:
sum+=ord(char)-96
# print(f"{word}对应的ASCII:{sum}")
return sum
sum_of_word('attitude')
sum_of_word('hello')
#导入下载的字典,把字典的内容遍历,同时对字典的内容进行函数调用:
# with open(r'\Users\Administrator\Documents\GitHub\the-craft-of-selfteaching\words_alpha.txt','r') as file:
# for word in file.readlines():#遍历读取文件的返回列表
# if sum_of_word(word)==100:
# print(word)
#查找问题:打印出第一个单词的每个字母,定位问题:
# with open(r'\Users\Administrator\Documents\GitHub\the-craft-of-selfteaching\words_alpha.txt','r') as file:
# for word in file.readlines():#遍历读取文件的返回列表
# if sum_of_word(word)==100:
# print(word)
# for c in word:
# print(c,ord(c)-96)
# break
#如果使用list(word)打印结果则更为直观:'a', 'b', 's', 't', 'r', 'u', 's', 'e', 'n', 'e', 's', 's', 'e', 's', '\n'
#验证\n的ASCII:
# print(ord('\n')-96)
with open(r'\Users\Administrator\Documents\GitHub\the-craft-of-selfteaching\results_test file.txt','w') as results:
with open(r'\Users\Administrator\Documents\GitHub\the-craft-of-selfteaching\words_alpha.txt','r') as file:
for word in file.readlines():#遍历读取文件的返回列表
#str.strip()删除字符串前后的空白字符
if sum_of_word(word.strip())==100:
# print(word)
results.write(word)
with open(r'\Users\Administrator\Documents\GitHub\the-craft-of-selfteaching\words_alpha.txt','r') as file:
lines=file.readlines()
#repr显示原始字符
first_line=lines[0]
first_line_o=repr(lines[0])
first_line1=lines[0].strip()
print(f"readlines读取的第一个元素:{first_line}")
print(f"readlines读取的第一个元素_原始数据:{first_line_o}")
print(f"使用strip后:{first_line1}")
#验证换行符的存在,查看字符串长度:
print(len(first_line))
print([ord(c) for c in first_line])