程序设计入门-Python

本文是网易云课堂中程序设计入门-Python的课程笔记。

数据类型、运算符、变量赋值和简单I/O操作

对象与类型

五种基本对象类型

  1. 字符串,str

    使用单引号、双引号、三引号括起来的一连串字符。

  2. 整数,int

    支持十进制(21),八进制(025)和十六进制(0x15)

  3. 浮点数,float

    1.48, 21.021..21, 2.1E-2

  4. 布尔类型,bool

    True,False

对象类型

  • type()

    $1+2

    3

    $’1’ + ‘2’

    ‘12’

    $1.1 + 1.1

    2.2

    $1.1+1.1+1.1

    3.30000000000000003(浮点数3.3无法在电脑中精确表示,有一定精度损失)

算术运算

算术运算符 含义 举例
/ 除法运算 10/2=5.0;10/3=3.333335
% 求余数 10%3=1
// 求商运算 10//3=3
** 指数运算 2**3=8

**python2中“/“表示向下取整,因此5/9=0,需要写为5./9才对,python3则是表示正常除。

自动类型转换

参与运算的两个对象类型不同时,按照以下规则自动转换

*bool→int→float→complex

如:1.0+3=4.0;True+3.0=4.0

求余运算应用

今天是周六,10天之后是周几?

  • (6+10)%7=2

x是否为偶数

  • if (x % 2 == 0)

math模块

import math #引入math模块

dir(math) #列出math中的内容

help(math.sin) #帮助

  • math.pi
  • math.e

关系运算符

x % 2 == 0 #等于

x % 2 != 0

逻辑运算符

关系运算符 含义 举例
and True and False == False
or True or False == True
not not True == False
  • 港台女明星

    性别 == 女 and (籍贯 == 香港 or 籍贯 == 台湾)

  • 判断闰年

    • 年份能被4整除不能被100整除,或者能被400整除,则是闰年

      (y % 4 == 0 and y % 100 != 0) or (y % 400 == 0)

运算符优先级

运算符优先级

变量与I/O

变量,Variable

增量赋值运算符

  • 累加

    1
    2
    3
    count = count + 1
    # 简写为:
    count += 1

    | 增量赋值 | 等价表示 |
    | ——- | :———- |
    | x += 2 | x = x + 2 |
    | x -= 2 | x = x - 2 |
    | x = 2 | x = x 2 |
    | x /= 2 | x = x / 2 |
    | x %= 2 | x = x % 2 |
    | x = 2 | x = x 2 |

输入与输出

input函数

1
2
3
4
5
import math
radius = float(input(‘Radius:’))
area = math.pi * radius ** 2
print('Area:', area)

print函数

输出到多行

1
print'hello\nworld!')

课程练习

  1. 输入2 2 3时的结果为:
    256
    解释: 是幂运算,优先级是右结合,即多次幂运算先递归计算右边的结果:
    a
    b c = a ( b ** c)
  2. 输入 123 and 456 的结果为:
    456
    解释:逻辑运算是左结合的运算符;and 找假,找不到假返回最后一个真,or 找真,找到真的立刻给出真
    因此, 123 or 456 结果为123
  3. 7.0 % 5 的结果为:
    2.0
    解释:%为求余运算
  4. 使用 format 函数设置保留两位小数:

    num = 1 / 30
    ‘{0:.2f}’.format(num)
    ‘0.33’
    ‘%.2f’ % (num)
    ‘0.33’
    format(num, ‘.2f’)
    ‘0.33’

    程序控制结构

选择结构

程序流程图

if语句

1
2
3
4
5
6
score = 70
if score > 60:
print('yes')
else:
print('no')
1
2
3
4
5
6
score = 70
gender = 'lady'
if score > 60:
if gender == 'lady':
print('yes')
1
2
3
4
5
score = 70
gender = 'lady'
if score > 60 and gender = 'lady':
print('yes')
1
2
3
4
5
6
7
8
9
score = 70
gender = 'lady'
if score > 80:
print('A')
elif score > 70:
print('B')
else:
print('C')

一元二次方程求解

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
import math
a = float(input('a:'))
b = float(input('b:'))
c = float(input('c:'))
if a == 0:
if b != 0:
print('solution is:', -c/b)
elif c == 0:
print('x is any num')
else:
print('no solution')
else:
if b**2-4*a*c < 0:
print('no solution')
elif b**2-4*a*c == 0:
print('solution is:', -b/2/a)
else:
delta = math.sqrt(b**2-4*a*c)
print('solution is:', (-b-delta)/a/2,(-b+delta)/a/2)

篮球比赛领先多少才安全

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
score = int(input('forward score:'))
score -= 3
has_ball = input('has ball(0/1);')
time_remaining = float(input('time remmaining:'))
if has_ball == '1':
score += 0.5
else:
score -= 0.5
if score < 0:
score = 0
score **= 2
if score > time_remaining:
print('safe')
else:
print('not safe')

循环结构

while循环语句

  • 多次求一元二次方程

分析策略:

  • 循环体外设定循环可执行的初始条件
  • 书写需重复执行的代码(循环体)
  • 设定循环条件并在循环体内设定条件改变语句

打印字符串5次

1
2
3
4
count = 0
while count < 5:
print('hello world')

计算1+2+…+10

1
2
3
4
5
6
7
8
i = 1
s = 0
while i <= 10:
s += i
i += 1
print(s)

多次求解一元二次方程

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
import math
ch = ''
while ch != 'q':
a = float(input('a:'))
b = float(input('b:'))
c = float(input('c:'))
if a == 0:
if b != 0:
print('solution is:', -c/b)
elif c == 0:
print('x is any num')
else:
print('no solution')
else:
if b**2-4*a*c < 0:
print('no solution')
elif b**2-4*a*c == 0:
print('solution is:', -b/2/a)
else:
delta = math.sqrt(b**2-4*a*c)
print('solution is:', (-b-delta)/a/2,(-b+delta)/a/2)
ch = input('enter q to exit:')

for循环

计算1+2+3+…10

1
2
3
4
5
6
s = 0
for i in range(1, 11, 1):
s += i
print(s)

计算常数e

1
2
3
4
5
6
7
8
import math
e = 1
for i in range(1, 100):
e += 1/math.factorial(i)
print(e)
1
2
3
4
5
6
7
8
# 另一种算法,避免每次从1开始计算阶乘,可有效提升速度
e = 1
factorial = 1
for i in range(1, 100):
factorial *= i
e += 1/factorial
print(e)

求常数π

1
2
3
4
5
6
pi = 0
for i in range(1, 100000):
pi += (-1)**(i+1)/(2*i-1)
pi *= 4
print(pi)
1
2
3
4
5
6
7
8
9
10
11
# 该算法同样速度更快
pi = 0
sign = 1
divisor = 2
for i in range(1, 100000):
pi += 4 * sign /divisor
sign *= -1
divisor += 2
print(pi)

奇偶归一猜想

对于每一个正整数,如果它为奇数,则对其乘3加1,如果为偶数,则对其除以2,如此循环,最后都能够得到1

1
2
3
4
5
6
7
8
for n in range(1,100):
while n != 1:
if n % 2 == 0:
n /= 2
else:
n = n * 3 + 1
# print(n)
print(n, end=' ') # 输出不换行

九九乘法表

1
2
3
4
5
for i in range(1, 10):
for j in range(1, 10):
# print(i * j, end =' ')
print(format(i * j, '3d'), end=' ') #每个数字占3格,以整数形式输出,'3d'此处等同'3'
print()

鸡兔同笼(穷举法)

鸡兔同笼,35头,94足

1
2
3
4
5
for chickens in range(35+1):
for rabbits in range(35+1):
if 2 * chickens + 4 * rabbits == 94 and chickens + rabbits == 35:
print('chickens numbers:', chickens)
print('rabbits numbers:', rabbits)

while vs. for 循环

  • while循环更通用

    任何for循环都可以用while来实现

  • for循环适用于已知循环范围(range),即起始值和步长

    • 其他情况均使用while循环,如:不确定循环何时终止

编程练习

二分法求平方根:

  • 基本思想

    • 猜测一个平方根(x/2)
    • 如果猜小了,则正确平方根在猜测数字和原数字之间
    • 如果猜大了,则在0和猜测数字之间
  • 算法描述

    • input:x
    • output:√x

      • low = 0, high = x
      • guess = (low + high) / 2
      • 如果$guess^2 == x$, 则输出guess,程序结束
      • $如果guess^2 < x , 则输出low = guess;继续步骤2$
      • 如果$guess^2 > x$,则输出 $high = guess$;继续步骤2
      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      x = float(input('enter a number:'))
      low = 0
      high = x
      guess = (low + high) / 2
      while abs(guess ** 2 - x) > 1e-5:
      if guess ** 2 < x:
      low = guess
      else:
      high = guess
      guess = (high + low) / 2
      print('root of x is:', guess)

      对于上面的程序,当x<0或x<1时将不成立

      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
      x = float(input('enter a number:'))
      if x < 0:
      print('no root')
      elif x < 1:
      low = x
      high = 1
      guess = (low + high) / 2
      while abs(guess ** 2 - x) >1e-6:
      if guess ** 2 > x:
      high = guess
      else:
      low = guess
      guess = (high + low) / 2
      print('root of x is:', guess)
      else:
      low = 0
      high = x
      guess = (low + high) / 2
      while abs(guess ** 2 - x) > 1e-6:
      if guess ** 2 < x:
      low = guess
      else:
      high = guess
      guess = (high + low) / 2
      print('root of x is:', guess)

判断素数

根据基本定义判断

1
2
3
4
5
6
7
8
n = int(input('enter a int number:'))
for i in range(2, n):
if n % i == 0:
print('not a prime')
break
else:
print('is a prime')
  • 上面的程序是素数时每次不被整除都会输出

    1
    2
    3
    4
    5
    6
    7
    8
    n = int(input('enter a int number:'))
    for i in range(2, n):
    if n % i == 0:
    print(n, 'not a prime')
    break
    else:
    print(n, 'is a prime')

另一种算法:

无需判断所有的range(2, x)都不能整除x,只需要判断 range(2, int(math.sqrt(x) + 1)) 即可
1. 对于任意一个合数x,假设它有两个质因子a、b(a<=b),显然x = a*b。
2. 由不等式性质可得,a <= sqrt(x), 即 a <= x^(1/2)。
3. 因此,判断一个数是不是合数,只需要判断到 int(sqrt(x))即可找到是否有质因子存在,for循环中再+1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
# 可以通过缩小范围加快速度
print('2 is a prime')
count = 1
for n in range(3, 500, 2):
if n % 2 == 0:
continue
# print(n, 'not a prime')
else:
for i in range(3, n - 1, 2):
if n % i == 0:
#print(n, 'not a prime')
break
else:
print(n, 'is a prime')
count += 1
if count == 50:
break
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 算法
import math
count = 0
num = 2
while count < 50:
for i in range(2, int(math.sqrt(num)) + 1):
if num % i == 0:
break
else:
print(num)
count += 1
num += 1

回文数

  • 求 n的逆序n‘;
  • 如果n == n’,则为回文数
1
2
3
4
5
6
7
#### 转化为字符串问题
n = input('enter a number:')
n_new = n[::-1]
if n == n_new:
print('yes')
else:
print('no')
1
2
3
4
5
6
7
8
9
10
11
12
#### 一般解法
num = int(input('enter a number:'))
num_temp = num
num_prime = 0
while num_temp != 0:
num_prime = num_prime * 10 + num_temp % 10 #余数留给新的数字,并每次乘以10
num_temp //= 10 # 原来数字每次向右移动一位,123→12
if num == num_prime:
print('yes')
else:
print('no')

tips:

x = a if a > b else b