Python学习随笔[内容大多为转载]2021-9-14

字符串

1. 双引号单引号标识与作为字符串本身功能的重合

例如:

print('we're')

 此行代码会出现错误,编译器本身对字符串的识别规定与特殊字符字符串本身功能重合

同样的问题也会出现在C++里面

Python 里面的解决方法有如下几种

1.

print('we\'re ')
//增加转义字符

 2.

print("we're ")
//双引号中间的单引号依然被视为字符串

3.

print('''we're "''')
//三引号中间的双引号和单引号均被视为字符串

 Python 输出换行符

 在Python中三引号可以输出换行符

print('''we're 


"''')

C++里面的解决方法如下

 1. 可使用转义字符

int main()
{
	string str = "\"Working hard for my baby bunny\"";
	cout << str << endl;
}
\\printf:"Working hard for my baby bunny"
\\C++使用转义字符这种方法在python里面通用

2. C++11之后支持原始字符串

//c++11 之后支持原始字符串(raw string),可以不用转义
printf(R"("Working hard for my baby bunny")")

C++输出换行符

printf("\n")
//换行符

字符串拼接

Python

print("apple"+"origin")

C++

char * strcat (目标字符串,源字符串);//将源字符串的副本附加到目标字符串上,目标字符串中的终止空字符由源字符串的第一个字符覆盖,并将这两个字符串连接形成的新字符串,末尾包含一个空字符

concatenate  串联

#include <stdio.h>
#include <string.h>
//字符串联
int main ()
{
  char str[80];
  strcpy (str,"these ");
  strcat (str,"strings ");
  strcat (str,"are ");
  strcat (str,"concatenated.");
  puts (str);
  return 0;
}

Python对于数字字符串的强制转换

print(float('1.0'))  //这是正确的
print(int('1.0'))  //这是错误的

Python对于多个变量的赋值

a,b,c=1,2,3
print(a,b,c)

for的隔位输出

for i in range(1,10,2):
    print(i)

Python的三者判断条件

x=1
y=2
z=3
# Python的三者判断
if x<y<z:
    print("x<y and y<z")

Python的三者判断的是通过先判断前一半,再判断后一半

if x!=y<3:
    print("Equal !")

 Python的函数默认值

def sale_car(price='10086',colour='red',brand='carmy',is_second_hand=True):
    print('price:',price,
          'colour',colour,
          'brand',brand,
          'is_second_hand',is_second_hand
          )

Pyhon程序的返回值

# 函数的返回值
def fun():
    a=10
    print(a)
    return a+10
print(fun())

Python 中的函数对全局变量的引用

a=None
def fun():
    global a
    a=20+20
    print(a)
fun()
print(a)

安装模块: 

1. pip3  install [模块名]    使用时候有提示  安装某个版本的模块

        示例

        pip3 install numpy-1.9.2

2. Linux下可能需要 sudo 权限

Python 读写文件

写入文本

# Python简单的文件写入
text='This is angel!\n This is a good man!'
my_file=open('myfile.txt','w')
my_file.write(text)
my_file.close()

附加文本

# Python文本附加
append_text="\nI love you !"
my_file=open('myfile.txt','a')
my_file.write(append_text)

逐行读取文本

# 按行读出文本里的列表并且存储成List元素
file=open('myfile.txt','r')
content=file.readlines()
print(content)

类与方法

其中init 可以创建被修改的变量,类似于参数的输入

class Caculator:
    # 固有属性
    name='Good caculator'
    price=18
    #初始的属性及功能
    def __init__(self,name,price,hight,width,weight):
        # 给定属性,
        self.name=name
        self.price=price
        self.hi=hight
        self.wi=width
        self.we=weight
    def add(self,x,y):
        # print(self.name)
        result=x+y
        print(result)
    def minus(self,x,y):
        result=x-y
        print(result)
    def times(self,x,y):
        print(x*y)
    def divide(self,x,y):
        print(x/y)
caculator=Caculator()
# caculator.name
print(caculator.add(10,11))
print(caculator.minus(10,11))
print(caculator.divide(10,11))
print(caculator.times(10,11))

 Python 数学运算 与 位运算  [数字]//[数字]是整数运算

9//4 #返回商的整数部分


位运算(应该特别注意,2^2是按位异或,不是幂)

#位运算符
2^2  #按位异或
2&2  #与运算
2|2  #或运算
~2   #非运算
<<   #左移动运算符
>>   #右移动运算符

Python 生成器 yield会节约运行内存,加上for 可以实现性能换内存,至于换的值不值,我觉得在大部分的情况下是值得,但是与for + next结合后,函数复杂度由o(1)编程o(n)因此可能出现以下几种情况

1. 当使用到顺序处理的列表的时候,这种方法一定是值的

2.当使用到索引的时候,这种方法会带来一定的损失,因为不断的next会提升时间复杂度,但在一些情况下依然节约了很大的内存,使用与否视情况而定。

Python List多维列向量

a=[1,2,3,5,55,745,88,55]
#插入元素
a.insert(1,55)

# list的索引(第一次出现的索引)
print(a.index(55))

#list里面的数目
print(a.count(55))

#排序
a.sort(reverse=True)
print(a)

#list倒序索引(负数)
print(a[-1])

多维List

muti_dim_a=[[1,2,3],
            [4,5,6],
            [7,8,9]]
print(muti_dim_a[0])

Python 调用自己写的模块

solution 1:在同一个文件夹内,另一个py脚本直接 import

solution2:把需要调用的脚本放到Lib/site_pakages里面当作普通默认模块调用

Python循环中的  break 和continue ,break打破此层循环,continue 提前结束此次循环

Python 中的错误处理

为了程序具有极好的容错性、让程序更加健壮。程序出错时候 系统会生成一个错误来通知通知陈旭,从而实现将“业务实现代码”和“错误处理代码”分离提供更好的可读性


s = input('请输入除数:')
try:
    result = 20 / int(s)
    print('20除以%s的结果是: %g' % (s , result))
except ValueError:
    print('值错误,您必须输入数值')
except ArithmeticError:
    print('算术错误,您不能输入0')
else:
    print('没有出现异常')
import sys
try:
    a = int(sys.argv[1])
    b = int(sys.argv[2])
    c = a / b
    print("您输入的两个数相除的结果是:", c )
except IndexError:
    print("索引错误:运行程序时输入的参数个数不够")
except ValueError:
    print("数值错误:程序只能接收整数参数")
except ArithmeticError:
    print("算术错误")
except Exception:
    print("未知异常")

 分组错误归类括号内()

import sys
try:
    a = int(sys.argv[1])
    b = int(sys.argv[2])
    c = a / b
    print("您输入的两个数相除的结果是:", c )
except (IndexError, ValueError, ArithmeticError):
    print("程序发生了数组越界、数字格式异常、算术异常之一")
except:
    print("未知异常")

程序访问异常信息   [异常信息访问]

def foo():
    try:
        fis = open("a.txt");
    except Exception as e:
        # 访问异常的错误编号和详细信息
        print(e.args)
        # 访问异常的错误编号
        print(e.errno)
        # 访问异常的详细信息
        print(e.strerror)
foo()

Python 中的 else模块的使用

# 是否采用 else模块要根据其场景来看,其中 else代码块中的异常不会被捕获,放在try里面会被捕获,我认为其中最大的额可利用的地方在于代码段异常的定位更宽了,在else_test中使用的话,要在后面增加try except判断更利于精确定

finally 子句常用于定义 无论在任何情况下都会执行的清理行为。若一个异常在 try 子句里 (或在 except 子句和 else 子句里) 被抛出,而又没有任何的 except 子句将其捕获,那么该异常 将会在 finally 子句执行后被抛出。例如

>>> try:
	fin = open('oneline.txt')
	print('Everything goes well!')
except FileExistsError:
	print('There is a FileExistsError!')
except FileNotFoundError:
	print('There is a FileNotFoundError!')
else:
	print(fin.readlines())
	fin.close()
finally:
	print("Operations are Finished!")
 
Everything goes well!
['I Love Python!']
Operations are Finished!

参考文章  【Python】详解 try-except-else-finally 语句 —— 异常处理完全解读 (上)_闻韶-CSDN博客

   Python try except else(异常处理)用法详解 (biancheng.net)

pickle文件写入与读取

使用 open的话,后面需要 close()

使用with  open as 就不用close()

file=open('pickle_example.pickle','rb')
a_dict222=pickle.load(file)
file.close()
print(a_dict222)


with open('pickle_example.pickle','rb') as file:
    a_dict222 = pickle.load(file)
    print('with结果:',a_dict222)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值