{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 1.4 人机交互"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">一般来说,<font color=red>一个程序可以没有输入,但至少要有一个输出。</font> \n",
"内置函数 <font color=\"red\">__input()__</font> 接收用户<font color=\"red\">__输入__</font>的字符串 \n",
"内置函数 <font color=\"red\">__print()__</font> 将程序的处理结果以字符的形式<font color=\"red\">__展示__</font>给用户</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1.4.1 输出函数"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">Python主要有两种输出值的方式: \n",
"<font color=\"red\">__表达式语句__</font> \n",
"<font color=\"red\">__print() 函数__</font> </font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">表达式语句主要用于<font color=\"red\">__交互模式__</font>,在交互模式下输入变量或表达式将可以直接输出变量或表达式的值。 \n",
"例如在交互模式下输入5 + 6 / 2 - 3 * 2并回车,解释器直接输出表达式计算结果。</font>"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"2.0"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"5 + 6 / 2 - 3 * 2 # 交互模式下可以直接输出表达式结果,不用加print()\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" <font face='楷体' color='red' size=5> 练一练1 </font>"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [],
"source": [
"# 模仿上面的表达式,自己写一个表达式,然后点击“运行”查看输出结果 \n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">表达式语句直接输出仅用于极少计算或测试时,更普遍的方式是用 <font color=\"red\">__print()函数__</font> 进行输出。 \n",
"print()函数的语法为:</font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"print(*objects, sep=' ', end='\\n')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">print()函数主要用于将<font color=\"red\">__单个对象__</font> 或<font color=\"red\">__多个对象__</font> 输出到屏幕上。</font>"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello world! hello\n"
]
}
],
"source": [
"print('Hello world!',end=\" \") # 单个对象原样输出,输出后自动换行\n",
"print(\"hello\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" <font face='楷体' color='red' size=5> 练一练2 </font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 模仿上面的程序,试着编程输出“Hi,Python!”\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" <font face='楷体' color='red' size=5> 练一练3 </font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 模仿上面程序,试着编程输出:'Hello ***!' ,其中*号替换成你自己的名字\n",
"# 例如输出:你好 李明!\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"print(2022) # 单个对象原样输出,输出后自动换行"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"78.539815\n"
]
}
],
"source": [
"area = 3.1415926 * 5 ** 2 # 表达式计算结果命名为变量 area\n",
"print(area) # 输出变量的值"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"若输出的对象为表达式,则先计算表达式结果,再输出这个结果:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"print(3.1415926 * 5 ** 2) # 圆的面积 78.539815"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">输出多个对象时,用半角逗号“,”将要输出的对象隔开作为print()函数的参数。 \n",
"输出时默认用空格对输出值进行分隔。</font>"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2022 6 16\n",
"2022 6 16\n"
]
}
],
"source": [
"print(2022, 6, 16) # 输出多个对象时,对象之间用半角逗号分隔\n",
"# 输出 2022 6 16,输出的多个对象之间默认用空格分隔\n",
"print(\"2022\",\"6\",\"16\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">输出<font color=Red>__多个对象__</font>时,可以用 <font color=\"red\">__sep参数__</font> 指定分隔符号,sep 参数的值必须是 <font color=Red>__字符串__</font>。</font>"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2022/6/16\n",
"2022/6/16\n"
]
}
],
"source": [
"print(2022, 6, 16, sep='/') # sep参数值为字符串'/',用于分隔输出的多个对象\n",
"# 输出 2022/6/16\n",
"print('2022',\"6\",\"16\",sep='/')\n"
]
},
{
"cell_type": "code",
"execution_count": 35,
"metadata": {},
"outputs": [],
"source": [
"print(2022, 6, 16, sep='-') # sep参数值为字符串'-',用于分隔输出的多个对象\n",
"# 输出 2022-6-16"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [],
"source": [
"print(23, 59, 30, sep=':') # sep参数值为字符串':',用于分隔输出的多个对象\n",
"# 输出 23:59:30"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" <font face='楷体' color='red' size=5> 练一练4 </font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 模仿上面例子,分别用“-”和“/”为分隔符,输出当前的日期\n",
"# 例如:2022年08月01日时年月日分别为2022 08 01,此时输出:\n",
"# 2022-08-01 \n",
"# 2022/08/01\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">print()函数中 <font color=\"red\">__end 参数__</font> 默认值是 <font color=\"red\">__换行符('\\n')__</font> ,此参数值缺省时,执行print() 函数后会自动输出一个 <font color=\"red\">__换行__</font> 。</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">下面三条输出语句会在三行中输出:</font>"
]
},
{
"cell_type": "code",
"execution_count": 12,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"欢迎您\n",
"学习python\n",
"程序设计\n"
]
}
],
"source": [
"print('欢迎您')\n",
"print('学习python')\n",
"print('程序设计')\n",
"# 欢迎您\n",
"# 学习python\n",
"# 程序设计"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">若print()函数中增加end参数,会用end的值做结束符,下面例子中end的值为空字符串,输出前面的字符串后再输出一个空字符串,不换行,三条语句的内容在同一行中输出。</font>"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"欢迎您学习python程序设计\n"
]
}
],
"source": [
"print('欢迎您', end='')\n",
"print('学习python', end='')\n",
"print('程序设计')\n",
"# 欢迎您学习python程序设计"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"类似的应用还有:"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"print('2024', end='/')\n",
"print('02', end='/')\n",
"print('29')\n",
"# 2024/02/29\n",
"\n",
"print('23', end=':')\n",
"print('08', end=':')\n",
"print('35')\n",
"# 23:08:35"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"end参数也经常用于在同一行输出循环中的结果:\n",
"下面例子会循环4次,依次输出range(4)产生的数列中的数字,每次输出都换行。"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0\n",
"gf\n",
"1\n",
"gf\n",
"2\n",
"gf\n",
"3\n",
"gf\n",
"1234\n"
]
}
],
"source": [
"for i in range(4): # 重复执行缩进区域的语句4次 \n",
" print(i) # end默认参数值是'\\n',默认输出后换行\n",
" print(\"gf\")\n",
"print(\"1234\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"下面例子会循环4次,每次输出字符串'Hello world!',每次输出都换行。"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Hello world!\n",
"Hello world!\n",
"Hello world!\n",
"Hello world!\n"
]
}
],
"source": [
"for i in range(4): # 重复执行缩进区域的语句4次 \n",
" print('Hello world!') # end默认参数值是'\\n',默认输出后换行"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"如果希望多个print() 语句的输出在 <font color=\"red\">__换行符('\\n')__</font> 同一行中,可以给print() 函数里的end 参数一个 <font color=\"red\">__字符串__</font>类型的值。 \n",
"例如设置 <font color=\"red\">__end=' '__</font> 或 <font color=\"red\">__end=','__</font> ,使每条print() 语句的输出后用 <font color=\"red\">__空格__</font> 或 <font color=\"red\">__逗号__</font> 代替默认的 <font color=\"red\">__换行符('\\n')__</font> ,实现多条print() 语句输出在 <font color=\"red\">__同一行__</font> 内的效果。"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"for i in range(4): # 重复执行缩进区域的语句4次 \n",
" print(i, end=' ') # end参数值不是'\\n'时,输出后不换行,单引号间有一个空格,输出的字符间有空格分隔\n",
" # 输出的每个数后有一个空格:0 1 2 3"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [],
"source": [
"for i in range(4): # 重复执行缩进区域的语句4次 \n",
" print('Hello world!', end=' ') # end默认参数值是'\\n',默认输出后换行"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"设置end=''(空字符串),实现多个对象连续输出的效果(相当于拼接到一起)。"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [],
"source": [
"for i in range(4): # 重复执行缩进区域的语句4次 \n",
" print(i, end='') # end参数值不是'\\n'时,输出后不换行,单引号间没有空格,输出的字符连在一起\n",
" # 输出的每个数后没有空格,连续输出:0123"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"注意, <font color=\"red\">__中文逗号与英文逗号__</font> 是不同的,英文符号是半角,中文符号是全角表示,注意观察下面两组代码的输出:"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"0,1,2,3, # 英文逗号,称为半角符号\n",
"0,1,2,3, # 中文逗号,称为全角符号,字符间分隔空隙更大一些,符号占位更宽"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {
"scrolled": true
},
"outputs": [],
"source": [
"for i in range(4): # 重复执行缩进区域的语句4次 \n",
" print(i, end=',') # 输出的结尾是一个英文逗号,逗号占位较小\n",
" # 输出:0,1,2,3,"
]
},
{
"cell_type": "code",
"execution_count": 6,
"metadata": {},
"outputs": [],
"source": [
"for i in range(4): # 重复执行缩进区域的语句4次 \n",
" print(i, end=',') # 输出的结尾是一个中文逗号,逗号占位更宽\n",
" # 输出:0,1,2,3,"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" <font face='楷体' color='red' size=5> 练一练5 </font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 模仿上面例子,在同一行内输出从0到50的整数,每个整数后有一个空格\n",
"# range()括号中的数字控制输出数字的范围\n",
"# 正确结果:0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 \n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" <font face='楷体' color='red' size=5> 练一练6 </font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 模仿上面例子,在同一行内输出从0到49的整数,每个整数后有一个半角逗号(英文逗号)\n",
"# 正确结果:0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,\n",
"\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1.4.2 输出格式"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">print() 函数只能输出用特定分隔符分隔的值,当需要更多的控制输出格式时,可以使用以下方法。</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### (1)格式化字符串字面值"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" <font size=\"3\"><font color=\"red\" size=\"3\">__格式化字符串字面值__</font>,又称为f-string,这是Python 3.6以后提供的一个新方法,用“f”或“F”做前缀格式化字符串输出。</font>"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"f'原样输出的字符串{大括号位置用大括号中的变量值替换}'"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">使用时,在字符串开始的引号前加上 <font color=\"red\">__“f”或“F”__</font>,字符串中可放置 <font color=\"red\">__大括号“{}”__</font>作为 <font color=\"red\">__替换域__</font>,输出时,字符串将被原样输出, <font color=\"red\">__替换域__</font>中的变量或表达式在程序运行时会被变量和表达式的值代替。</font>"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5 - 3 = 2\n",
"5 - 3 = 2\n"
]
}
],
"source": [
"a = 5\n",
"b = 3\n",
"print(f\"{a} - {b} = {a - b}\") # 大括号中可以放变量名或表达式,输出: 5 - 3 = 2\n",
"print(f'{a} - {b} = {a - b}') # 大括号中可以放变量名或表达式,输出: 5 - 3 = 2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
" <font face='楷体' color='red' size=5> 练一练7 </font>"
]
},
{
"cell_type": "code",
"execution_count": 9,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"4+8=4\n"
]
}
],
"source": [
"# 模仿上面例子,按“加+”“减-”“乘*”“除/”的顺序,在4行中输出a与b四则运算的结果,空白处添加你的代码\n",
"# 注意输出中的空格应该在字符串中,大括号中只放变量名或表达式\n",
"a = 4\n",
"b = 8\n",
"\n",
"print(f'{a}+{b}={a}')\n",
"\n",
"\n",
"# 正确结果:\n",
"# 4 + 8 = 12\n",
"# 4 - 8 = -4\n",
"# 4 * 8 = 32\n",
"# 4 / 8 = 0.5"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">f 后面的字符串中可以包含各种文字和符号,下面例子中字符串中包含冒号和豆号。</font>"
]
},
{
"cell_type": "code",
"execution_count": 17,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"姓名:Tom,性别:male,年龄:20\n"
]
}
],
"source": [
"user_name = 'Tom'\n",
"gender = 'male'\n",
"age = '20'\n",
"print(f'姓名:{user_name},性别:{gender},年龄:{age}')\n",
"# 输出:姓名:Tom,性别:male,年龄:20"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"大括号中的变量值可以为任意类型,当大括号中的值为 <font color=\"red\">__字符串__</font>时,需使用与f 后面引号不同的 <font color=\"red\">__引号__</font>,f 后面是单引号做定界符时,字符串用双引号,f 后面是双引号做定界符时,字符串用单引号。\n",
"\n",
"说明:python 3.12.0以后的版本中,大括号中的字符串可以使用与外面相同的引号。 \n",
"例如: \n",
"3.12以前的版本的写法: \n",
"f\"\"\"{f'''{f'{f\"{1+1}\"}'}'''}\"\"\" \n",
"3.12.0以后可以简单写作: \n",
"f\"{f\"{f\"{f\"{f\"{f\"{1+1}\"}\"}\"}\"}\"}\" "
]
},
{
"cell_type": "code",
"execution_count": 18,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"姓名:Tom,性别:male,年龄:40\n",
"姓名:Tom,性别:male,年龄:40\n"
]
}
],
"source": [
"print(f'姓名:{\"Tom\"},性别:{\"male\"},年龄:{40}')\n",
"# 姓名:Tom,性别:male,年龄:40\n",
"\n",
"print(f\"姓名:{'Tom'},性别:{'male'},年龄:{40}\")\n",
"# 姓名:Tom,性别:male,年龄:40"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font face='楷体' color='red' size=5> 练一练8 </font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 请模仿上面例子,编程输出:我的名字是李明,来自湖北省武汉市。\n",
"user_name = '李明'\n",
"city = '武汉'\n",
"province = '湖北'\n",
"\n",
"\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"正确结果:\n",
"我的名字是李明,来自湖北省武汉市。"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 将练一练8中的李明、武汉和湖北分别替换为你自己的姓名、入学前的省市,再执行程序查看输出。\n",
"\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">用 ':m' 在 ':'后传递一个整数m可以让该字段最小字符宽度为m个,可用于设置右对齐。</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">下面例子中,当输出少于3个字符时至少占3个字符宽度,可用于保证输出右对齐。</font>"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1 * 9 = 9\n",
"9 * 9 = 81\n",
"9 * 19 = 171\n"
]
}
],
"source": [
"print(f'{1} * {9} = {1 * 9:3}') # 1 * 9 = 9\n",
"print(f'{9} * {9} = {9 * 9:3}') # 9 * 9 = 81\n",
"print(f'{9} * {19} = {9 * 19:3}') # 9 * 19 = 171"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">当输出 <font color=\"red\">__多于m个字符__</font>时按全部字符 <font color=\"red\">__实际字符宽度__</font>输出。</font>"
]
},
{
"cell_type": "code",
"execution_count": 21,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"1 * 9 = 9\n",
"9 * 19 = 8991\n"
]
}
],
"source": [
"print(f'{1} * {9} = {1 * 9:4}') # 1 * 9 = 9\n",
"print(f'{9} * {19} = {9 * 999:4}') # 9 * 19 = 8991"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">用<font color=\"red\">__':.nf'__</font>在<font color=\"red\">__冒号 ':'__</font> 后传递一个整数 n 和字母 f 可以<font color=\"red\">__精确控制__</font>浮点数输出时的<font color=\"red\">__小数位数为n__</font>。</font>"
]
},
{
"cell_type": "code",
"execution_count": 26,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"小学生用圆周率时精确到小数点后3位,结果为3.142\n",
"大学生用圆周率时精确到小数点后7位,结果为3.1415927\n",
"3.1415927\n"
]
}
],
"source": [
"pi = 3.141592653589793\n",
"\n",
"print(f'小学生用圆周率时精确到小数点后3位,结果为{pi:.3f}')\n",
"# 小学生用圆周率时精确到小数点后2位,结果为3.14\n",
"print(f'大学生用圆周率时精确到小数点后7位,结果为{pi:.7f}')\n",
"# 大学生用圆周率时精确到小数点后7位,结果为3.1415927\n",
"print(round(pi,7))"
]
},
{
"cell_type": "code",
"execution_count": 28,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"7 / 3 = 2.3333333333333335\n",
"7 / 3 = 2.33\n",
"7 / 3 = 233.33%\n"
]
}
],
"source": [
"a = 7\n",
"b = 3\n",
"\n",
"# 输出默认精度的结果\n",
"print(f'{a} / {b} = {a / b}') # 输出7 / 3 = 2.3333333333333335\n",
"\n",
"# 输出结果保留小数点后2位,冒号后面的点表示小数点,2表示保留2位数字,f表示浮点数\n",
"print(f'{a} / {b} = {a / b:.2f}') # 输出 7 / 3 = 2.33\n",
"\n",
"# :.2%是一个格式说明符。.表示小数点,2表示小数点后的位数,%表示将数值转换为百分比。\n",
"print(f'{a} / {b} = {a / b:.2%}') # 7 / 3 = 233.33%"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font face='楷体' color='red' size=5> 练一练9 </font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 模仿上面例子,按“加+”“减-”“乘*”“除/”的顺序,在4行中输出a与b四则运算的结果,结果保留4位小数,空白处添加你的代码\n",
"\n",
"a = 5.3267\n",
"b = 7.35364\n",
"\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"正确结果如下所示"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"\n",
"5.3267 + 7.35364 = 12.6803\n",
"5.3267 - 7.35364 = -2.0269\n",
"5.3267 * 7.35364 = 39.1706\n",
"5.3267 / 7.35364 = 0.7244"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 【拓展】利用f-string方法,还可以构建采色的打印,模板如下:"
]
},
{
"cell_type": "code",
"execution_count": 16,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'\\x1b[效果;前景色;背景色m要打印的文本\\x1b[0m'"
]
},
"execution_count": 16,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"f'\\033[效果;前景色;背景色m要打印的文本\\033[0m'"
]
},
{
"cell_type": "code",
"execution_count": 29,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[031m我要用红色输出\u001b[0m\n"
]
}
],
"source": [
"print(f'\\033[031m{\"我要用红色输出\"}\\033[0m')"
]
},
{
"cell_type": "code",
"execution_count": 30,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\u001b[034m我要用蓝色输出\u001b[0m\n"
]
}
],
"source": [
"print(f'\\033[034m{\"我要用蓝色输出\"}\\033[0m')"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"下面说明一下上面的参数如何设置:"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"| 参数 | 参数值 |\n",
"| :---- | :---- |\n",
"| 文字效果 | 0:终端默认,1:高亮,4:下划线,5:闪烁,7:反白显示|\n",
"| **前景色** | 30(黑),31(红),32(绿),33(黄),34(蓝),35(紫),36(青),37(灰) |\n",
"| **背景色** | 40(黑),41(红),42(绿),43(黄),44(蓝),45(紫),46(青),47(灰) |\n"
]
},
{
"cell_type": "code",
"execution_count": 11,
"metadata": {},
"outputs": [],
"source": [
"print(f'\\033[4;031m{\"我要用红色带下划线输出\"}\\033[0m')"
]
},
{
"cell_type": "code",
"execution_count": 10,
"metadata": {},
"outputs": [],
"source": [
"print(f'\\033[7;031m{\"我要用红色反白输出\"}\\033[0m')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"每次都重新编辑转义字符串、查颜色表是一件很麻烦的事情。Python有一些封装好颜色字符库可以使用。下面代码主要用于打印服务器日志记录,提供高亮黑底状态下的红、黄、绿、白字显示,并且可以选择是否在字符串开头打印时间戳,可用于演示自定义颜色自字符串输出的效果。"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [],
"source": [
"import time\n",
"\n",
"\n",
"# 打印彩色字符\n",
"def colormsg(msg: str, color: str = \"\", timestamp: bool = True):\n",
" str = \"\"\n",
" if timestamp:\n",
" str += time.strftime('{}-{}-{} {}:{}:{} '.format(*time.localtime(time.time())))\n",
" if color == \"red\":\n",
" str += \"\\033[1;31;42m\" # 红字绿背景色\n",
" elif color == \"green\":\n",
" str += \"\\033[1;32;40m\" # 绿字黑背景\n",
" elif color == \"yellow\":\n",
" str += \"\\033[1;33;47m\" # 黄字灰背景\n",
" else:\n",
" print(str + msg)\n",
" return\n",
" str += msg + \"\\033[0m\" # 结束标记\n",
" print(str)\n",
"\n",
"\n",
"# 调用定义的函数实现不同颜色字符串的输出\n",
"colormsg(\"[ERROR]网络连接异常!\", \"red\")\n",
"colormsg(\"[OK]认证成功!\", \"green\")\n",
"colormsg(\"[INFO]远程连接已关闭\", \"yellow\")\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### (2)str.format() 方法 "
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"格式:\n",
"<模版字符串>.format(<逗号分隔的参数>)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">与f-string类似,<font color=\"red\">__<模版字符串>__</font>由一系列的用<font color=\"red\">__大括号“{}”__</font>表示的<font color=\"red\">__替换域__</font>组成,用来控制修改字符串中嵌入值出现的<font color=\"red\">__位置__</font>。调用此方法的“模版字符串”可以包含字符串以及若干个大括号表示的替换域。</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">format() 括号中的放置与替换域<font color=\"red\">__数量相同__</font>的参数值,运行时默认按替换域出现的顺序<font color=\"red\">__一一对应__</font>填入到前面的替换域中。</font>"
]
},
{
"cell_type": "code",
"execution_count": 33,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5 + 3 = 8\n"
]
}
],
"source": [
"a = 5\n",
"b = 3\n",
"print('{} + {} = {}'.format(a, b, a + b)) # 参数值按出现顺序填入替换域"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">如果替换域中标有序号,将<font color=\"red\">__根据序号__</font>到format()括号里查找序号对应的值进行填入。</font>"
]
},
{
"cell_type": "code",
"execution_count": 19,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5 * 3 = 15\n",
"5 * 3 = 15\n",
"5 * 3 = 15\n"
]
}
],
"source": [
"# 这三条语句输出相同格式信息:\n",
"a = 5\n",
"b = 3\n",
"print('{} * {} = {}'.format(a, b, a * b)) # 参数值按出现顺序填入替换域\n",
"print('{2} * {1} = {0}'.format(a * b, b, a)) # 参数序号从0开始编号,依次为:0,1,2\n",
"print('{2} * {0} = {1}'.format(b, a * b, a)) # 括号中序号根据参数序号调整"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font face='楷体' color='red' size=5> 练一练10 </font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 应用str.format() 方法,按“加+”“减-”“乘*”“除/”的顺序,在4行中输出a与b四则运算的结果,结果保留 2 位小数,空白处添加你的代码\n",
"a = 5.3267\n",
"b = 7.35364\n",
"\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"按位置传递参数"
]
},
{
"cell_type": "code",
"execution_count": 36,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"我叫王伟,今年18岁\n"
]
}
],
"source": [
"print('我叫{},今年{}岁'.format('王伟', 18)) # 我叫王伟,今年18岁"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"按序号传递参数,与位置无关,大括号中数字表示传递的对象的位置"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"这是咖啡,我喜欢喝茶\n"
]
}
],
"source": [
"print('这是{0},我喜欢喝{1}'.format('咖啡', '茶')) # 这是茶,我喜欢喝咖啡"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"序号可重复使用"
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {},
"outputs": [],
"source": [
"print('这是{1},我喜欢喝{1}'.format('咖啡', '茶')) # 这是茶,我喜欢喝茶"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"参数可多于替代域索引数"
]
},
{
"cell_type": "code",
"execution_count": 55,
"metadata": {},
"outputs": [],
"source": [
"print('这是{0},我喜欢喝{0}'.format('茶', '咖啡', '红酒')) # 这是茶,我喜欢喝茶"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"参数少于替代域索引数时报错。\n",
"使用时要保证format()中的参数数量与前面大括号{}的数量相同。"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [],
"source": [
"print('这是{1},我喜欢喝{0}'.format('茶')) # 错误用法,测试时去掉行首#号\n",
"# IndexError: Replacement index 1 out of range for positional args tuple"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"除此以外,还可以在每个替换域中传入一个变量,在format()方法里给每一个变量赋值,输出时,将值按替换域的顺序进行输出。"
]
},
{
"cell_type": "code",
"execution_count": 43,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"3 - 3 = 2\n"
]
}
],
"source": [
"print('{b} - {b} = {c}'.format(a=5, b=3, c=5-3)) # 5 - 3 = 2"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"使用变量名形式的简单字段名传递关键字参数,关键字参数的位置可以随意调换"
]
},
{
"cell_type": "code",
"execution_count": 44,
"metadata": {},
"outputs": [],
"source": [
"print('我叫{user},今年{age}岁'.format(user='王伟', age=18))\n",
"print('我叫{user},今年{age}岁'.format(age=18, user='王伟'))\n",
"# 我叫王伟,今年18"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font face='楷体' color='red' size=5> 练一练11 </font>"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 应用str.format() 方法,输出:这是一辆2022年生产,型号是L90的红旗牌汽车,售价1000万元。\n",
"year = 2022\n",
"model = 'L90'\n",
"brand = '红旗'\n",
"price = 1000\n",
"# 补充你的代码,得到输出结果 \n",
"\n"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"正确输出结果:"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"这是一辆2022年生产,型号是L90的红旗牌汽车,售价1000万元。"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">str.format()中也可以在大括号中加冒号和“格式限定符”,在冒号后面加“.mf”控制输出保留小数点后m位数字的浮点数(f代表float)。</font>"
]
},
{
"cell_type": "code",
"execution_count": 8,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"5 / 3 = 1.6666666666666667\n",
"5 / 3 = 1.6667\n",
"3.35\n"
]
}
],
"source": [
"print('{} / {} = {}'.format(a, b, a / b)) # 5 / 3 = 1.6666666666666667\n",
"print('{} / {} = {:.4f}'.format(a, b, a / b)) # 5 / 3 = 1.6667,.4f保留4位小数浮点数\n",
"print(round(3.345,2)) ##保留2 位小数"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### (3)字符串拼接的方法 "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"用“+”将多个字符串拼接为一个字符串输出。<br /> \n",
"参与拼接的可以是字符串也可以是字符串变量。 <br />\n",
"参与拼接的变量为整数等其他数据类型时,需先用str()函数将其转为字符串类型再参与拼接。"
]
},
{
"cell_type": "code",
"execution_count": 54,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"<class 'int'>\n",
"我叫王伟,今年18岁\n"
]
}
],
"source": [
"user = '王伟'\n",
"age = 18 # 18是整数,用str(age)转为字符串 '18'\n",
"print(type(age))\n",
"print('我叫' + user + ',今年' +str(age) + '岁') # 我叫王伟,今年18岁"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 1.4.3 输入函数 "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">input()函数:<br /> \n",
" 作用是从标准输入设备(键盘)获得用户输入的一行数据,不管用户输入的是字符型还是数字型的数据,input()函数都会<font color=red>将其作为一个字符串类型</font>处理。</font>"
]
},
{
"cell_type": "code",
"execution_count": 55,
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
" 5\n",
" 3\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"输入给a的数据的类型是:<class 'str'>\n",
"a + b 的结果是两个字符串拼接到一起:53\n",
"a * int(b)是将字符串5重复整数3次:555\n"
]
}
],
"source": [
"a = input() # 输入 5,默认为字符串'5'\n",
"b = input() # 输入 3,默认为字符串'3'\n",
"print(f'输入给a的数据的类型是:{type(a)}') # 输出<class 'str'>,a的类型是字符串 \n",
"print(f'a + b 的结果是两个字符串拼接到一起:{a + b}') # 输出 53,'+' 作用是将两个字符串拼接为一个字符串\n",
"print(f'a * int(b)是将字符串{a}重复整数{int(b)}次:{a * int(b)}') # 输出 555,'*' 作用是将字符串重复整数b次"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"当用户输入为“5”和“3”时,输出结果分别为“53”和“555”,而不是直接进行数学运算而得到“8”和“15”,这表明即使我们输入数字型数据,系统也会将其作为字符串进行处理。"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"为了提高程序的用户友好性,input()可以包含一些<font color=Red>__提示性的文字__</font>,提示性文字以<font color=Red>__双引号或单引号__</font>引起来放于input后的括号内,如:"
]
},
{
"cell_type": "code",
"execution_count": 25,
"metadata": {},
"outputs": [
{
"name": "stdin",
"output_type": "stream",
"text": [
"请输入一个正整数,表示长方形边长: 1\n",
"请输入一个正整数,表示长方形边长: 6\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"边长为1和6的长方形面积为:6\n"
]
}
],
"source": [
"a = input(\"请输入一个正整数,表示长方形边长:\") # 输入 5,默认为字符串'5'\n",
"b = input('请输入一个正整数,表示长方形边长:') # 输入 3,默认为字符串'3'\n",
"print(f'边长为{a}和{b}的长方形面积为:{int(a) * int(b)}') # 输出15"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"提示性文字及输入: \n",
"请输入一个正整数,表示长方形边长:5 \n",
"请输入一个正整数,表示长方形边长:3 \n",
"提示性文字及输出: \n",
"边长为5和3的长方形面积为:15 "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font size=\"3\">当输入数据需要参与数值运算时,可以直接将input()函数做为类型转换函数int()或float()的参数,在输入同时完成数据类型的转换。</font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"#### a = int(input()) # 输入字符串'3'转为整数 3\n",
"b = int(input()) # 输入字符串'5转为整数 5\n",
"print(a * b) # 输出数值计算结果 15\n",
"print(f'{a} * {b} = {a * b}') # 输出: 3 * 5 = 15\n",
"print(f'边长为{a}和{b}的长方形面积为:{a * b}') # 输出边长为3和5的长方形面积为:15"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"输入: \n",
"3 \n",
"5 \n",
"输出: \n",
"15 \n",
"3 * 5 = 15 \n",
"边长为3和5的长方形面积为:15 "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font face='楷体' color='red' size=5> 练一练12 </font>"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"描述\n",
"用户输入矩形的长和宽,计算其面积并输出。\n",
"\n",
"输入格式\n",
"第一行输入一个整数,代表矩形的长\n",
"第二行输入一个整数,代表矩形的宽\n",
" \n",
"输出格式\n",
"表示矩形的面积整数"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"# 空白处补充你的代码\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"测试数据: \n",
"输入 \n",
"5 \n",
"8 \n",
"输出 \n",
"40 "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"user = input('请输入姓名:') # 输出“请输入姓名:”等待输入,输入:张华\n",
"print('你真的是', user, '?') # 输出3个对象,空格分隔,你真的是 张华 ?\n",
"print('你真的是', user, '?', sep='') # 输出3个对象,空字符串分隔,你真的是张华?\n",
"print('你真的是' + user + '?') # 字符串拼接,无分隔,你真的是张华?\n",
"print(f'你真的是{user}?') # 格式化字符串输出,你真的是张华?"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"运行时屏幕上会看到“请输入姓名:”的提示,同时程序做好接收用户输入的准备。<br />\n",
"注意到第一个print语句输出时,在变量user的值“张华”的前后各输出一个空格,这是由print()函数的参数sep的默认值为空格导致的,可以在输出时设置参数“sep=''”来消除空格,也可以用字符串拼接或“f”前缀格式化字符串的方法消除多余的空格。"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"<font face='楷体' color='red' size=5> 练一练13 </font>"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"运行以下代码,查看结果:"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [],
"source": [
"def print_hi(user_name):\n",
" print(f'= 欢迎{user_name} =')\n",
" \n",
" \n",
"def print_line():\n",
" print(\"==================\")\n",
" \n",
" \n",
"def print_blank():\n",
" print(\"= =\")\n",
" \n",
" \n",
"print_line()\n",
"print_blank()\n",
"print_hi('小明')"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"欢迎以上代码的代行结果,修改以下代码,得到下面示例的输出:"
]
},
{
"cell_type": "code",
"execution_count": 5,
"metadata": {},
"outputs": [],
"source": [
"def print_hi(user_name):\n",
" print(f'= 欢迎{user_name} =')\n",
" \n",
" \n",
"def print_line():\n",
" print(\"==================\")\n",
" \n",
" \n",
"def print_blank():\n",
" print(\"= =\")\n",
" \n",
" \n",
"# 补充你的代码\n",
"\n",
"\n",
"\n",
"\n",
"\n"
]
},
{
"cell_type": "raw",
"metadata": {},
"source": [
"==================\n",
"= =\n",
"= =\n",
"= =\n",
"= 欢迎小明 =\n",
"= =\n",
"= =\n",
"= =\n",
"=================="
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"需要注意的是,用自动评测平台测试程序时,为简化问题,<font color='red'>**一般不在input()中添加提示性文字**</font>。 \n",
" \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"例如: \n",
"输入两个整数,计算两个数的和: "
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"a = int(input()) # int()将输入的整数字符串转为整数类型,数值类型才能进行数学运算\n",
"b = int(input())\n",
"print(a + b)"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {},
"outputs": [],
"source": [
"输入: \n",
"6 \n",
"9 \n",
"输出: \n",
"15 "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"例如: \n",
"输入表示矩形长和宽的两个整数,计算矩形面积: "
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {},
"outputs": [],
"source": [
"width = int(input()) # int()将输入的整数字符串转为整数类型,数值类型才能进行数学运算\n",
"length = int(input())\n",
"area = width * length\n",
"print(area)"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"输入: \n",
"4 \n",
"5 \n",
"输出: \n",
"20 "
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.7.5"
}
},
"nbformat": 4,
"nbformat_minor": 4
}