文章目录
~
主要参考 python语言程序设计
引用 https://github.com/jackfrued/Python-Core-50-Courses
引用https://www.zhihu.com/question/46973549/answer/767530541
C2-C6
变量、常量、输入
- 变量:指向存储在内存中某个值名字- choose descriptive name
- 从控制台读取输入:
radius = eval(input("Enter a value:"))
#eval()函数求值并转换为数值
- 同时赋值
var1,var2,var3,...,varn = exp1, exp2,...,expn
- 定名常量:区分于变量,全用大写表示
- 浮点型:数字在内存中以科学计数法存储,小数点浮动到新位置。
优先级
+,-(一元)
**
not
*,/,//,% 从左至右
+,-(二元)
<, <=,>,>=
==, !=
and
or
=,+=(赋值运算符)
- math 函数
- 不换行打印:
print("AAA", end = "")
print("BBB", end = "*")
print("CCC", end = "")
# AAABBB*CCC
- "+"运算符连接两个字符串
函数 round(), format()
interest = 12618.98 * 0.0013
print("interest is:", interest)
print("interest is:", round(interest, 2))
print("interest is:", format(interest, ".2f"))
# interest is: 16.404674
# interest is: 16.4
# interest is: 16.40
// round函数采用的是四舍六入五成双的计数保留方法
// 1、小于等于4的舍去;2、大于等于6的进一;3、5的话要看后面有没有有效数字,
有的话进一,没有的话要按照5前面数字的奇偶来处理,
若5前面为奇数,则进一,若5前面为偶数,舍5不进。
//比如1.15--->1.2, 1.25--->1.2, 1.250--->1.2, 1.25012--->1.3
print(format(0.53312,".2%"))
print(format(0.53312,"10.2%"))
print(format(0.53312,"<10.2%"))
# 53.31%
# 53.31%
# 53.31%
对象,方法
- 每个数据都是对象,对象所用的函数称为方法。
- py自动给每个变量赋值一个id,即id(),
n = 3
# 是将3赋值给了n,实际是3赋值给了int对象,这个对象是由变量n引用的
布尔类型,数值,表达式
randint()
import random
print(random.randint(0,9))
# 9
# randint(a,b)随机产生a到b之间,包含a,b的整数
if,嵌套if, if-elif-else语句
原则:“Flat is better than nested”
- Py中没有用花括号来构造代码块而是使用了缩进的方式来表示代码的层次结构
循环
while 循环
count = 0
while count < 5:
print("Hi")
count += 1
#Hi
#Hi
#Hi
#Hi
#Hi
import random
answer = random.randint(1, 100)
counter = 0
while True:
counter += 1
number = eval(input('Enter your guess: '))
if number < answer:
print('your guess is too low')
elif number > answer:
print('your guess is too high')
else:
print('Yes!')
break
print(f'you total guess is {counter} times')
for 循环
#用for循环实现1~100求和
total = 0
for x in range(1, 101):
total += x
print(total)
#用for循环实现1~100偶数求和
total = 0
for x in range(2, 101, 2):
total += x
print(total)
* range(101):产生0到100范围的整数,取不到101。
* range(1, 101):产生1到100范围的整数,前闭后开
* range(1, 101, 2):产生1到100的奇数,2是步长,每次数值递增的值
* range(100, 0, -2):产生100到1的偶数,-2是步长,每次数字递减的值
嵌套循环
print(" Multiplication Table")
print(" ", end="")
for j in range(1, 10):
print(' ', j, end = " ")
print() # jum the new line
print(" --------------------------------------")
for i in range(1, 10):
print(i, "|", end = "")
for j in range(1, 10):
print(format(i * j, "4d"), end = "")
print()
# Multiplication Table
# 1 2 3 4 5 6 7 8 9
# --------------------------------------
# 1 | 1 2 3 4 5 6 7 8 9
# 2 | 2 4 6 8 10 12 14 16 18
# 3 | 3 6 9 12 15 18 21 24 27
# 4 | 4 8 12 16 20 24 28 32 36
# 5 | 5 10 15 20 25 30 35 40 45
# 6 | 6 12 18 24 30 36 42 48 54
# 7 | 7 14 21 28 35 42 49 56 63
# 8 | 8 16 24 32 40 48 56 64 72
# 9 | 9 18 27 36 45 54 63 72 81
# 完美间距!运行了五六次调的lol
实例–GCD&LCM
x = int(input('x = '))
y = int(input('y = '))
if x > y:
x, y = y, x
for factor in range(x, 0, -1):
if x % factor == 0 and y % factor == 0:
print(f'The greatest common divisor is {factor}')
print(f'The least common multiple is{x * y // factor}')
break
定义函数
- 带返回值函数与无返回值函数,无返回值函数实际返回return None。
- 位置参数,关键字参数(参数名=参数值)调用函数。
- 位置参数不能出现在关键字参数之后
- 值传递:实参的值(对象的引用值)传递给形参
x赋值给y,xy指向同一个对象,如果将1加到y,就会创建新对象,将这个新对象的引用赋值到y
x = 4
y = x
print(id(x))
print(id(y))
y = y + 1
print(id(y))
#1710824253840
#1710824253840
#1710824253872
- 变量的作用域,全局变量,在所有函数之外创建
- 默认参数:允许定义带默认值的参数。函数可以混用默认值参数和非默认值参数,非默认值参数必须定义在默认值参数之前。
- 不支持同一模块定义两同名函数。
函数抽象与逐步求精
自顶向下,逐步求精
C7
- 对象,状态,行为
- 对象,顾名思义。
- 状态,用变量表示,数据域
- 行为,方法(函数)。使用通用类来定义同一种类型的对象
- 类是为不同使用者使用而设计的,为了满足更广泛的应用需求,类必须为用户提供各种途径方法对类进行定制。
构造对象
初始化程序 __init__
- self是指向对象本身的参数。使用self访问在类定义中的对象成员。
- 一个实例变量被创建,作用域就是整个类。
- 看似保存一个对象的变量实际上包含是指向这个对象的引用。(Circle1是一个变量,它包含一个指向Circle对象的引用)
不变对象和可变对象
隐藏数据域
- 私有数据域:两个下划线开始
- 数据不会被篡改,类更加好维护
CircleWithPrivateRadius.py
import math
class Circle:
def __init__(self, radius = 1):
self.__radus = radius
def getRadius(self):
return self.__radus
def getPerimeter(self):
return 2 * self.__radus * math.pi
def getArea(self):
return self.__radus * self.__radus * math.pi
str类
- 一个str对象是不可改变的。一旦创建这个字符串,它的内容不可变。
- py使用一个对象来表示具有相同内容的字符串(即id相同)(对所有不可变对象都是真的,如int)
处理字符串的函数
s = "welcome"
s1 = "python"
for i in range(0, len(s), 2):
print(s[i], end="")
print(s[-1])
print(s[1:4])
print(s[:4])
print(s[4:-1])
print(s + "to" + s1)
print(3 * s1)
print("come" in s1)
print("come" not in s1)
for ch in s:
print(ch)
wloee
elc
welc
om
welcometopython
pythonpythonpython
False
True
w
e
l
c
o
m
e
运算符重载和特殊方法
- 让自定义的类生成的对象(实例)能够使用运算符进行操作
- 让自定义的实例像内建对象一样进行运算符操作
- 让程序简洁易读
- 对自定义对象将运算符赋予新的规则
class Mynumber:
def __init__(self,v):
self.data = v
def __repr__(self): #消除两边的尖括号
return "Mynumber(%d)"%self.data
def __add__(self,other):
'''此方法用来制定self + other的规则'''
v = self.data + other.data
return Mynumber(v) #用v创建一个新的对象返回给调用者
def __sub__(self,other):
'''此方法用来制定self - other的规则'''
v = self.data - other.data
return Mynumber(v)
n1 = Mynumber(100)
n2 = Mynumber(200)
# n3 = n1 + n2
n3 = n1+n2 # n3 = n1.__add__(n2)
print(n3) #Mynumber(300)
n4 = n3 - n2 #等同于n4 = n3.__sub__(n2)
print("n4 = ",n4)
class Mylist:
def __init__(self, iterable=()):
self.data = list(iterable)
def __repr__(self):
return 'Mylist(%s)' % self.data
def __add__(self, lst):
print('__add__被调用')
return Mylist(self.data + lst.data)
def __mul__(self, rhs):
# rhs为int类型,不能用rhs.data
print('__mul__被调用')
return Mylist(self.data * rhs)
def __rmul__(self, lhs):
print("__rmul__被调用")
return Mylist(self.data * lhs)
L1 = Mylist([1, 2, 3])
L2 = Mylist([4, 5, 6])
L3 = 3 * L1
print(L3)
L1 += L2
print(L1)
L2 *= 3
print(L2)
class Mylist:
def __init__(self, iterable=()):
self.data = list(iterable)
def __repr__(self):
return 'Mylist(%s)' % self.data
def __contains__(self, e):
return True if e in self.data else False
l1 = Mylist([1, 2, 3, 4, -5, 6])
if 2 in l1: # 等同于if l1.__contains__(4)
print('2在l1内')
else:
print('2不在l1内')
if -4 not in l1: # 等同于if not l1.__contains__(4)
print('-4不在l1内')
else:
print('-4在l1内')