{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# 第2章 Python程序实例解析\n",
"## 温度转换程序实例\n",
"温度刻画存在不同体系,摄氏度以1标准大气压下水的结冰点为0度,沸点为100度,将温度进行等分刻画。华氏度以1标准大气压下水的结冰点为32度,沸点为212度,将温度进行等分刻画。 \n",
"问题:如何利用Python程序进行摄氏度和华氏度之间的转换\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"- 输入:华氏或者摄氏温度值、温度标识 \n",
"- 处理:温度转化算法 \n",
"- 输出:华氏或者摄氏温度值、温度标识 \n",
"> F表示华氏度,82F表示华氏82度 \n",
"> C表示摄氏度,28C表示摄氏28度 \n",
"\n",
"根据华氏和摄氏温度定义,转换公式如下:\n",
" C = ( F – 32 ) / 1.8 \n",
" F = C * 1.8 + 32 \n",
" 其中,C表示摄氏温度,F表示华氏温度\n"
]
},
{
"cell_type": "code",
"execution_count": 45,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"请输入带有符号的温度值:120x\n",
"输入的格式错误\n"
]
}
],
"source": [
"#温度转换程序\n",
"\n",
"#输入温度值\n",
"#判断字符串最后一位是'F'还是'C',并以此决定转换方向\n",
"#(注意:1、取出字符串前几位;2、转换整数)\n",
"#打印转换后的温度值\n",
"TempStr = input(\"请输入带有符号的温度值:\")\n",
"if TempStr[-1] in ['F','f']: # if TempStr[-1] == 'F' or ....\n",
" C = (eval(TempStr[:-1]) -32) / 1.8\n",
" print(\"转换后的温度是{:.2f}C\".format(C))\n",
"elif TempStr[-1] in ['C','c']: # else if\n",
" F = 1.8 * eval(TempStr[0:-1]) + 32\n",
" print(\"转换后的温度是{:.2f}F\".format(F))\n",
"else:\n",
" print(\"输入的格式错误\")"
]
},
{
"cell_type": "code",
"execution_count": 52,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"请输入带有符号的温度值:c120\n",
"转换后的温度是:F248.00\n"
]
}
],
"source": [
"#修改程序,输入时将温度类型的F或C放在第一个字符\n",
"'''\n",
"输入:带类型的温度值\n",
"输出:转换后的温度值\n",
"处理:转换公式\n",
"'''\n",
"TempStr = input(\"请输入带有符号的温度值:\")\n",
"if TempStr[0] in ['F','f']: # if TempStr[-1] == 'F' or ....\n",
" C = (eval(TempStr[1:]) -32) / 1.8\n",
" print(\"转换后的温度是:C{:.2f}\".format(C))\n",
"elif TempStr[0] in ['C','c']: # else if\n",
" F = 1.8 * eval(TempStr[1:]) + 32\n",
" print(\"转换后的温度是:F{:.2f}\".format(F))\n",
"else:\n",
" print(\"输入的格式错误\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## Python程序语法元素分析\n",
"包括格式框架、注释、变量、表达式、分支语句、循环语句、函数等语法元素\n",
"### 程序的格式框架\n",
"Python语言采用严格的“缩进”来表明程序的格式框架。缩进指每一行代码开始前的空白区域,用来表示代码之间的包含和层次关系。 \n",
"- 用以在Python中标明代码的层次关系 \n",
"- 缩进是Python语言中表明程序框架的唯一手段 \n",
"\n",
"学习 Python 与其他语言最大的区别就是,Python 的代码块不使用大括号 {} 来控制类,函数以及其他逻辑判断。python 最具特色的就是用缩进来写模块。 \n",
"缩进的空白数量是可变的,但是所有代码块语句必须包含相同的缩进空白数量,这个必须严格执行。 "
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 注释\n",
"注释:程序员在代码中加入的说明信息,不被计算机执行\n",
"注释的两种方法:\n",
"- 单行注释以#开头 \n",
"> #Here are the comments \n",
"- 多行注释以 ’’’开头和结尾 \n",
"> ’’’ \n",
"> This is a multiline comment \n",
"> used in Python \n",
"> ’’’ \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 命名与保留字\n",
"- 常量:程序中值不发生改变的元素 \n",
"- 变量:程序中值发生改变或者可以发生改变的元素 \n",
"\n",
"Python语言允许采用大写字母、小写字母、数字、下划线(_)和汉字等字符及其组合给变量命名,但名字的首字符不能是数字,中间不能出现空格,长度没有限制\n",
"注意:标识符对大小写敏感,python和Python是两个不同的名字 \n",
"保留字,也称为关键字,指被编程语言内部定义并保留使用的标识符。\n",
"程序员编写程序不能定义与保留字相同的标识符。\n",
"每种程序设计语言都有一套保留字,保留字一般用来构成程序整体框架、表达关键值和具有结构性的复杂语义等。\n",
"掌握一门编程语言首先要熟记其所对应的保留字。\n",
"
"
andexecnot\n","
assertfinallyor\n","
breakforpass\n","
classfromprint\n","
continueglobalraise\n","
defifreturn\n","
delimporttry\n","
elifinwhile\n","
elseiswith \n","
exceptlambdayield\n","
\n"]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 运算符\n",
"#### 算术运算符\n",
"\n",
"例如:a = 10, b=20 \n",
"
"
\n","
运算符描述实例\n","
\n","
\n","
+加 - 两个对象相加 a + b 输出结果 30\n","
\n","
\n","
-减 - 得到负数或是一个数减去另一个数 a - b 输出结果 -10\n","
\n","
\n","
\\*乘 - 两个数相乘或是返回一个被重复若干次的字符串 a \\* b 输出结果 200\n","
\n","
\n","
/除 - x除以y b / a 输出结果 2\n","
\n","
\n","
%取模 - 返回除法的余数 b % a 输出结果 0\n","
\n","
\n","
\\*\\*幂 - 返回x的y次幂 a\\*\\*b 为10的20次方, 输出结果 100000000000000000000\n","
\n","
\n","
//取整除 - 返回商的整数部分 9//2 输出结果 4 , 9.0//2.0 输出结果 4.0\n","
\n","
\n","\n",
"#### 比较运算符\n",
"
"
\n","
运算符描述实例\n","
\n","
\n","
== 等于 - 比较对象是否相等 (a == b) 返回 False。 \n","
\n","
\n","
!= 不等于 - 比较两个对象是否不相等 (a != b) 返回 true. \n","
\n","
\n","
<>不等于 - 比较两个对象是否不相等 (a <> b) 返回 true。这个运算符类似 != 。\n","
\n","
\n","
> 大于 - 返回x是否大于y (a > b) 返回 False。\n","
\n","
\n","
< 小于 - 返回x是否小于y。所有比较运算符返回1表示真,返回0表示假。这分别与特殊的变量True和False等价。注意,这些变量名的大写。 (a < b) 返回 true。 \n","
\n","
\n","
>= 大于等于\t- 返回x是否大于等于y。 (a >= b) 返回 False。\n","\n",
"
\n","
\n","
<= 小于等于 -\t返回x是否小于等于y。 (a <= b) 返回 true。 \n","
\n","
\n","\n",
"#### 赋值运算符\n",
"
"
\n","
运算符描述实例\n","
\n","
\n","
=简单的赋值运算符 c = a + b 将 a + b 的运算结果赋值为 c\n","
\n","
\n","
+=加法赋值运算符 c += a 等效于 c = c + a\n","
\n","
\n","
-=减法赋值运算符 c -= a 等效于 c = c - a\n","
\n","
\n","
\\*=乘法赋值运算符 c \\*= a 等效于 c = c \\* a\n","
\n","
\n","
/=除法赋值运算符 c /= a 等效于 c = c / a\n","
\n","
\n","
%=取模赋值运算符 c %= a 等效于 c = c % a\n","
\n","
\n","
\\*\\*=幂赋值运算符 c \\*\\*= a 等效于 c = c \\*\\* a\n","
\n","
\n","
//= 取整除赋值运算符 c //= a 等效于 c = c // a\n","
\n","
\n","\n",
"#### 位运算符\n",
"
"
\n","
运算符描述实例\n","
\n","
\n","
&按位与运算符:参与运算的两个值,如果两个相应位都为1,则该位的结果为1,否则为0 (a & b) 输出结果 12 ,二进制解释: 0000 1100\n","
\n","
\n","
| 按位或运算符:只要对应的二个二进位有一个为1时,结果位就为1。 (a | b) 输出结果 61 ,二进制解释: 0011 1101\n","
\n","
\n","
^按位异或运算符:当两对应的二进位相异时,结果为1 (a ^ b) 输出结果 49 ,二进制解释: 0011 0001\n","
\n","
\n","
~ 按位取反运算符:对数据的每个二进制位取反,即把1变为0,把0变为1 。 ~x 类似于 -x-1 (~a ) 输出结果 -61 ,二进制解释: 1100 0011,在一个有符号二进制数的补码形式。\n","
\n","
\n","
<<左移动运算符:运算数的各二进位全部左移若干位,由\"<<\"右边的数指定移动的位数,高位丢弃,低位补0。 a << 2 输出结果 240 ,二进制解释: 1111 0000\n","
\n","
\n","
>>右移动运算符:把\">>\"左边的运算数的各二进位全部右移若干位,\">>\"右边的数指定移动的位数 a >> 2 输出结果 15 ,二进制解释: 0000 1111\n","
\n","
\n","\n",
"#### 逻辑运算符\n",
"
"
\n","
运算符逻辑表达式描述实例\n","
\n","
\n","
andx and y 布尔\"与\" - 如果 x 为 False,x and y 返回 False,否则它返回 y 的计算值。\t (a and b) 返回 20。\n","
\n","
\n","
orx or y布尔\"或\"\t- 如果 x 是非 0,它返回 x 的值,否则它返回 y 的计算值。 (a or b) 返回 10。\n","
\n","
notnot x布尔\"非\" - 如果 x 为 True,返回 False 。如果 x 为 False,它返回 True。 not(a and b) 返回 False \n","
\n","
\n","\n",
"#### 成员运算符\n",
"
"
\n","
运算符描述实例\n","
\n","
\n","
in\n","如果在指定的序列中找到值返回 True,否则返回 False。
\n","
x 在 y 序列中 , 如果 x 在 y 序列中返回 True。\n","
\n","
\n","
not in如果在指定的序列中没有找到值返回 True,否则返回 False。\n","
x 不在 y 序列中 , 如果 x 不在 y 序列中返回 True。\n","
\n","
\n","\n",
"#### 身份运算符\n",
"
"
\n","
运算符描述实例\n","
\n","
\n","
is\n","is 是判断两个标识符是不是引用自一个对象
x is y, 类似 id(x) == id(y) , 如果引用的是同一个对象则返回 True,否则返回 False\n","
\n","
\n","
is notis not 是判断两个标识符是不是引用自不同对象 x is not y , 类似 id(a) != id(b)。如果引用的不是同一个对象则返回结果 True,否则返回 False。 \n","
\n","
\n","\n",
"#### 运算符优先级(不用记,不确定就用括号)\n",
"
"
运算符描述\n","
\n","
\\*\\*\n","
指数 (最高优先级)\n","
\n","
~ + -\n","
按位翻转, 一元加号和减号 (最后两个的方法名为 +@ 和 -@)\n","
\n","
\\* / % //\n","
乘,除,取模和取整除\n","
\n","
+ -\n","
加法减法\n","
\n","
>> <<\n","
右移,左移运算符\n","
\n","
&\n","
位 'AND'\n","
\n","
^ |\n","
位运算符\n","
\n","
<= < > >=\n","
比较运算符\n","
\n","
<> == !=\n","
等于运算符\n","
\n","
\n","
= %= /= //= -= += *= **=\n","
赋值运算符\n","
\n","
\n","
is is not\n","
身份运算符\n","
\n","
\n","
in not in\n","
成员运算符\n","
\n","
not or and\n","
逻辑运算符\n","
\n","
\n"]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 字符串\n",
"- Python语言中,字符串是用两个双引号“ ”或者单引号‘ ’括起来的一个或多个字符。 \n",
"- Python字符串的两种序号体系:正向和反向 \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 赋值语句\n",
"- Python语言中,= 表示“赋值”,即将等号右侧的值计算后将结果值赋给左侧变量,包含等号(=)的语句称为“赋值语句” \n",
"- 同步赋值语句:同时给多个变量赋值 \n",
", …, = , …, \n"
]
},
{
"cell_type": "code",
"execution_count": 61,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"x=10,y=20\n",
"x=20,y=10\n"
]
}
],
"source": [
"#例子:将两个变量的值交换,思考C语言怎么做(记得中间变量吗?)\n",
"x,y = 10,20\n",
"print(\"x={},y={}\".format(x,y))\n",
"#注意Python的多变量赋值语句,是不是随心所欲?\n",
"x,y = y,x\n",
"print(\"x={},y={}\".format(x,y))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### input()函数\n",
"获得用户输入之前,input()函数可以包含一些提示性文字 \n",
" = input()\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#试试输入函数,联想C语言的scanf函数"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 分支语句\n",
"分支语句是控制程序运行的一类重要语句,它的作用是根据判断条件选择程序执行路径,使用方式如下: \n",
"> if : \n",
"> \n",
"> elif : \n",
"> \n",
"> ... \n",
"> else: \n",
"> \n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### eval()函数\n",
"eval()函数是Python语言中一个十分重要的函数,它能够以Python表达式的方式解析并执行字符串,将返回结果输出\n",
"例如:"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"42"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"#eval函数实例\n",
"x = 5 \n",
"eval(\"x ** 2 + 2 * x +7\")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 输出函数\n",
"- print()函数用来输出字符信息,或以字符形式输出变量。 \n",
"- print()函数可以输出各种类型变量的值。 \n",
"- print()函数通过%来选择要输出的变量。 \n",
"实例:用户输入两个数,计算平均数"
]
},
{
"cell_type": "code",
"execution_count": 62,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"请输入第一个数:12.354\n",
"请输入第二个数:34.5\n",
"12.4和34.5的平均数是:23.4\n"
]
}
],
"source": [
"#注意Python的输出格式的两种使用最多的方式\n",
"num1 = input(\"请输入第一个数:\")\n",
"num2 = input(\"请输入第二个数:\")\n",
"avg = (float(num1) + float(num2)) / 2\n",
"#print(\"%.1f和%.1f的平均数是%.1f\" %(float(num1),float(num2),avg))\n",
"print(\"{0:.1f}和{1:.1f}的平均数是:{2:.1f}\".format(float(num1),float(num2),avg))"
]
},
{
"cell_type": "code",
"execution_count": 4,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"2.0和3.0的平均数是:2.5\n"
]
}
],
"source": [
"#换一种输出方式试试:format函数\n",
"x = 2\n",
"y = 3\n",
"print(\"{0:.1f}和{1:.1f}的平均数是:{2:.1f}\".format(x,y,(x+y)/2))"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 循环语句\n",
"循环语句:控制程序运行,根据判断条件或计数条件确定一段程序的运行次数 \n",
"遍历循环,基本过程如下 \n",
"for i in range (): \n",
" \n",
"例如,使某一段程序连续运行10次 \n",
"for i in range (10): \n",
" \n",
"其中,变量i用于计数 \n",
"\n"
]
},
{
"cell_type": "code",
"execution_count": 68,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"0 1 2 3 4 5 6 7 8 9 "
]
}
],
"source": [
"for i in range(10):\n",
" print(i,end=\" \")"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### 函数\n",
"内置函数和自定义函数"
]
},
{
"cell_type": "code",
"execution_count": 1,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#用函数方式改造温度转换程序\n",
"#定义温度转换函数\n",
"def tempConvert(ValueStr):\n",
" #函数体\n",
" pass\n",
"\n",
"#输入温度,调用函数\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## turtle库和蟒蛇绘制程序\n",
"![](attach\\img1.jpg)\n",
"### 实例:Python蟒蛇绘制"
]
},
{
"cell_type": "code",
"execution_count": 69,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#引入turtle库\n",
"import turtle\n",
"\n",
"turtle.setup(650,350,200,200)\n",
"turtle.penup()\n",
"turtle.fd(-250)\n",
"turtle.pendown()\n",
"turtle.pensize(25)\n",
"turtle.pencolor(\"purple\")\n",
"turtle.seth(-40)\n",
"for i in range(4):\n",
" turtle.circle(40,80)\n",
" turtle.circle(-40,80)\n",
"turtle.circle(40,80/2)\n",
"turtle.fd(40)\n",
"turtle.circle(16,180)\n",
"turtle.fd(40 * 2/3)\n",
"turtle.exitonclick()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"### turtle库语法元素分析\n",
"- import是一个关键字,用来引入一些外部库,这里的含义是引入一个名字叫turtle的函数库 \n",
"- Turtle中的turtle.setup()函数用于启动一个图形窗口,它有四个参数 \n",
"> turtle.setup(width, height, startx, starty) \n",
"> 分别是:启动窗口的宽度和高度 \n",
"> 表示窗口启动时,窗口左上角在屏幕中的坐标位置。 \n",
"\n",
"- 我们所使用的显示屏幕也是一个坐标系,该坐标系以左上角为原点,向左和向下分别是x轴和y轴。 \n",
"- turtle中的turtle.pensize()函数表示小乌龟运动轨迹的宽度。 \n",
"- turtle中的turtle.pencolor()函数表示小乌龟运动轨迹的颜色。 \n",
"- turtle中的turtle.seth(angle)函数表示小乌龟启动时运动的方向。\n",
"- left()和right()函数代表左转和右转一个角度\n",
"- turtle.circle()函数让小乌龟沿着一个圆形爬行 \n",
"> 参数rad描述圆形轨迹半径的位置 \n",
"> 这个半径在小乌龟运行的左侧rad远位置处,如果rad为负值,则半径在小乌龟运行的右侧 \n",
"> 参数angle表示小乌龟沿着圆形爬行的弧度值 \n",
"- turtle.fd()函数也可以用turtle.forward()表示乌龟向前直线爬行移动 \n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#五角星\n",
"import turtle\n",
"turtle.penup()\n",
"turtle.fd(-150)\n",
"turtle.pendown()\n",
"turtle.pencolor('red')\n",
"turtle.pensize(3)\n",
"\n",
"turtle.fd(200)\n",
"for i in range(4):\n",
" turtle.right(144)\n",
" turtle.fd(200)\n",
"\n",
"turtle.exitonclick()"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"## 程序练习题\n"
]
},
{
"cell_type": "markdown",
"metadata": {
"collapsed": true
},
"source": [
"1、思考题:发工资,输入工资(整型),计算钞票最少张数。 \n",
"2、练习:用turtle库绘制一个正六边形。然后思考,绘制正n边形。"
]
},
{
"cell_type": "code",
"execution_count": 2,
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"请输入您的工资:3928\n",
"100元:39张:\n",
"50元:0张:\n",
"20元:1张:\n",
"10元:0张:\n",
"5元:1张:\n",
"2元:1张:\n",
"1元:1张:\n"
]
}
],
"source": [
"#发工资\n",
"moneys = [100,50,20,10,5,2,1]\n",
"salary = eval(input(\"请输入您的工资:\"))\n",
"for money in moneys:\n",
" print(\"{}元:{}张:\".format(money, salary//money))\n",
" salary = salary % money"
]
},
{
"cell_type": "code",
"execution_count": 7,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": [
"#正六边形\n",
"import turtle\n",
"turtle.penup()\n",
"turtle.fd(-150)\n",
"turtle.pendown()\n",
"turtle.pencolor('red')\n",
"turtle.pensize(3)\n",
"\n",
"turtle.fd(50)\n",
"for i in range(9):\n",
" turtle.right(36)\n",
" turtle.fd(50)\n",
"\n",
"turtle.exitonclick()"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": true
},
"outputs": [],
"source": []
}
],
"metadata": {
"hide_input": false,
"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.6.1"
},
"toc": {
"colors": {
"hover_highlight": "#DAA520",
"navigate_num": "#000000",
"navigate_text": "#333333",
"running_highlight": "#FF0000",
"selected_highlight": "#FFD700",
"sidebar_border": "#EEEEEE",
"wrapper_background": "#FFFFFF"
},
"moveMenuLeft": true,
"nav_menu": {
"height": "336px",
"width": "252px"
},
"navigate_menu": true,
"number_sections": false,
"sideBar": true,
"threshold": 4,
"toc_cell": false,
"toc_section_display": "block",
"toc_window_display": false,
"widenNotebook": false
}
},
"nbformat": 4,
"nbformat_minor": 1
}
一键复制
编辑
Web IDE
原始数据
按行查看
历史