Python 基础与笔记(1)

xiaoxiao2021-02-28  99

1. Python支持C/C++的运算符有: = += -= *= /= %= Python特有的运算符: **(乘方) **=(乘方赋值) 不支持的运算符:前缀、后缀形式的++,-- 2. Python数值类型: int long float complex 3. 字符串 单引号、双引号里面的内容都是字符串。 第一个字符索引下标为0; 最后一个字符索引下标为-1; 字符串可以用“+”进行拼接; >>> str1 = 'hello' >>> str2 = 'world' >>> str1+str2 'helloworld' 字符串可以用“*”进行重复; >>> str1*5 'hellohellohellohellohello' >>> str1[0] 'h' >>> str1[-1] 'o' >>> str1[0:-1] 'hell' 4. 列表(list)和表列(tuple) 这是Python里自带容器。里面可以承载任意个数的Python对象。 列表用[]定义,其元素和长度可以变化。如  >>> alist = [1,2,3,4] >>> alist [1, 2, 3, 4] >>> alist[0:-1] [1, 2, 3] >>> alist[2:] [3, 4] >>> alist[:] [1, 2, 3, 4] >>> alist[:3] [1, 2, 3] >>> alist[1] = 5 >>> alist [1, 5, 3, 4] 表列用()定义,元素不能再次赋值。其他操作同列表。如 >>> atuple = ('robots',77,93,'try') >>> atuple ('robots', 77, 93, 'try') >>> atuple[0] 'robots' 5. 字典 字典就是Python里的hash table数据类型。用{}定义,内容包含key 和 value。key通常是数字或字符串。value可为任意基本数据类型。 >>> adict = {} >>> adict['host'] = 'earth' >>> adict['port'] = 80 >>> adict {'port': 80, 'host': 'earth'} >>> adict.keys() dict_keys(['port', 'host']) >>> adict['host'] 'earth' >>> adict.values() dict_values([80, 'earth']) 6. 缩进风格 Python代码段是用缩进标识的。 7. 文件操作 handle = open(file_name,access_mode = 'r') 几种模式: r:只读(默认) w:只写 a:append,添加内容到末尾 +:读写 b:二进制方式 8. 异常 try : try_block except someError: processing_block raise:明确引发一个异常。 9. 函数 def function_name([arguments]): 'optional documentation string' function_suite ##注意:函数所有参数都是以引用方式传递的,因此参数在函数中的任何变化都会影响到原始对象。(貌似3.3有变化了) def adder2(x,y) : return (x+y) 参数允许默认值。 10. 类 class class_name[(base_classes_if_any)]: "optional documentation string" static_member_declarations method_declarations 一个例子: class Cat : "Hello world, I am a cat, miao miao miao..." count = 0 def __init__(self, str = "Xiaomei") : 'Constructor' self.name = str count += 1 print("My name is : %s" % str) def show_info(self) 'Show some class info' print("My class name is :%s" % self.__class__) print("My name is : %s" % self.name) print("I have %d companies" % self.count) __class__内建变量显示类名,这里是__main__.Cat __doc__内建变量显示类声明时的documentation string 11. 模块

import 模块名

模块名.函数() 模块名.变量()
转载请注明原文地址: https://www.6miu.com/read-38099.html

最新回复(0)