前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python初学者笔记—入门基础知识

python初学者笔记—入门基础知识

作者头像
诡途
发布2020-10-16 10:00:54
9270
发布2020-10-16 10:00:54
举报

一、变量

变量:存储数据的容器,我们可以通过变量来操作数据 我们在创建变量时会在内存中开辟一个空间,可以存储不同类型的数据。

变量需要被定义: a=100

>>> b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'b' is not defined

每个对象都包含标识,类型和数据(值)这些信息。 可以通过id()、type()、print()三个函数查看

二、标识符命名规则:

  • 1、标识符由字母、数字、下划线、中文
  • 2、开头的字符不能使数字
>>> 1abc=100
  File "<stdin>", line 1
    1abc=100
       ^
SyntaxError: invalid syntax
  • 3、大小写敏感(区分大小写)
  • 4、不能以关键词命名
>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
  • 5、命名要有含义、尽量不要再开始位置使用下划线
>>> a="小王"
>>> a
'小王'
>>> name='小王'
>>> name
'小王'
>>> age=25
>>> password=123456

三、运算符

算数运算符:

      • / **(幂次计算) //整除 %取模(求余数)

比较运算符(返回逻辑判断结果): < > <= >= ==(值的比较) !=

赋值运算符: = += -= *= /= //= **= a+=1 --> a=a+1 a-=1 --> a=a-1

# 序列解包
>>> a=1;b=2;c=3;d=4
>>> a,b,c,d=1,2,3,4

逻辑运算符: and or not and:两边的条件都为True时返回True,否则返回False or:两边的条件有一个为True时返回True,否则返回False not:取反

成员运算符(判断对象是否在序列中): in ; not in

身份运算符(判断是否是同一个对象): is , is not a is b --> id(a)==id(b)

运算符的优先级: 括号() > 乘方 > 乘法除法 > 自左向右顺序计算

四、特殊字符

1、注释符(pycharm ctrl+/ 快速注释和取消注释)

# print("hello world!1")
# print(123)# print("hello world!2")
# print("hello world!3")
# print("hello world!4")
# print("hello world!5")

2、字符串 ''单引号 "“双引号 “”” “”"三引号

三引号用于创建多行字符串,有时也做注释 word=""“第一行 第二行 第三行 第四行 “””

3、转义符 将普通字符声明为特殊字符\n换行符 \t制表符 将特殊字符声明为普通字符’ " \

>>> path="C:\name\time\random.txt"
>>> print(path)
C:
andom.txtme
如何正确表示path路径
方法1:
path="C:\\name\\time\\random.txt"
方法2:
path=r"C:\name\time\random.txt"
方法3:
path="C:/name/time/random.txt"

4、续行符\

>>> a='12312312312312312333333123123123123\
... ABASDASDASZXCQWEQWEQWEQ'
>>> a
'12312312312312312333333123123123123ABASDASDASZXCQWEQWEQWEQ'

5、分号

>>> a=100
>>> b=100
>>> a=100;b=100
一行中写多行语句

五、数据类型

基础数据类型:数值型(整形 浮点数 布尔值 复数) 字符串 综合数据类型:列表 元组 字典 集合

数值型 整形 int(下标、元素的提取) a=100 b=200 c=-5 d=26

浮点数 float(用于科学计算) a=3.14 b=9.1 c=.2 d=5.

布尔值 bool(True和False) True和1等价 False和0等价

复数 complex(1+2j)实部+虚部

字符串:不可变的有序序列 string=‘Python’ string=‘Python123中文 # ! ?’

序列(sequence):一种将多个数据组合在一起的结构 有序:支持索引和切片的操作

s='Python';len(s)# 查看字符长度
s[0]# 获取第一个元素
s[1]# 获取第二个元素
s[-1]# 获取最后一个元素
s[-2]# 获取最后第二个元素
s[10]

>>> s[10]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

#切片:string[2:4]
#切片:可以获取序列中的多个元素
string[start:end]# 左闭右开 [ )
>>> string='Python123中文 # ! ?'
>>> string
'Python123中文 # ! ?'
>>> string[0:8]
'Python12'
>>> string[8]
'3'
>>> string[2:10]
'thon123中'

string[2:100]# 超出范围不会报错
>>> string[:100]
'Python123中文 # ! ?'
string[2:]# 从指定位置到结尾位置
string[:5]# 从开始位置到指定位置
string[:]# 从开始位置到结尾位置

string[start,end,step]
>>> num[::1]
'1234567890'
>>> num[::2]
'13579'
>>> num
'1234567890'
>>> num[::3]
'1470'
>>> num[::-1]# 逆向排序
'0987654321'

#字符串不可变,不支持元素的修改
string[0]
>>> string[0]='p'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'str' object does not support item assignment

#字符串的常见操作
# 字符串的拼接
a='上海';b='浦东'
a+b --> '上海浦东'
a*3 --> '上海上海上海'
a='上海';b='浦东';c='世纪大道'
'上海-浦东-世纪大道'
>>> a+'-'+b+'-'+c
'上海-浦东-世纪大道'

# 查看元素个数
len(string)
>>> string
'Python123中文 # ! ?'
>>> len(string)
17

# 基础数据类型之间的转换
age='25'
>>> age+1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int

int() float() str() bool() 
int('25')-->25 int(3.14)--> 3
>>> int('abc')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'abc'

float('3.14') float(3) 

str(123) str(3.14)

# 需要数字具有字符串的特性时:
a="我的年龄是:"
b=25
>>> a+b
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: must be str, not int
>>> a+str(b)
'我的年龄是:25'

# 输入和输出
# 输出print()
# 输入和输出
string="人生苦短,我用Python。"
print(string+' Oh yeah!')
print(string+' Oh yeah!')
print(string+' Oh yeah!')
print(string+' Oh yeah!')
print(string+' Oh yeah!')

# 每次print会进行和换行
string="人生苦短,我用Python。"
# end输出结束后打印的字符,默认换行符
# print(string+' Oh yeah!',end='---------')
# print(string+' Oh yeah!',end='\n')

string1="人生苦短"
string2="我用Python"
# sep打印多个对象时字符之间的分隔符,默认空格
print(string1,string2,1,2,sep='++')

# 输入(接受信息都为字符串类型)
# name=input("请输入你的姓名:")
# age=input("请输入你的年龄:")
# print(type(name),type(age))
# print("你的名字是:",name)
# print("你的年龄是:",age)

# 请输入你的名字和年龄,并且打印出你的名字和明年的年龄
# 要求:一条print语句完成
# name=input("请输入你的姓名:")
# age=input("请输入你的年龄:")
# print("你的名字是"+name+"你的年龄是"+str(int(age)+1)+"岁")
# print("你的名字是"+name+"你的年龄是",int(age)+1,"岁",sep="")

# 字符串格式化
# 创建字符串模板,常用与创建自定义的字符串
# print('今天学习的课程是%s'%'python编程基础')
# print('今天学习的课程是%s'%'python基础')
# print('我的名字是%s,今年%d岁,体重是%.1f公斤'%('程时',18,72.5))
# name=input("请输入你的名字:")
# age=input("请输入你的年龄:")
# weight=input("请输入你的体重:")
# print('我的名字是%s,今年%s岁,体重是%s公斤'%(name,age,weight))

# 1、输入一串字符,并返回它的长度。(结合input用法)
# string=input("请输入一段字符信息:")
# print("输入的字符信息长度是%s"%len(string))

# 2、输入你的名字和年龄,输出你明年是多少岁(结合input和字符串格式化)
# name=input("请输入你的名字:")
# age=input("请输入你的年龄:")
# print("你的名字是%s,你的年龄是%d岁,你明年%d岁"%(name,int(age),int(age)+1))
# print("你的名字是%s,你的年龄是%s岁,你明年%s岁"%(name,age,int(age)+1))


# 综合数据类型
列表list 元组tuple 字典dict 集合set

列表:可变的有序序列,可以存储任意类型的数据
string=''
tlist=[]
>>> tlist=[1,3.14,True,1+2j,'python','r语言',[100,200,300]]
>>> type(tlist)
<class 'list'>
有序序列:支持索引和切片
# 索引(下标)
tlist[0] tlist[4]
tlist[-1] tlist[-2]
# 切片(返回列表)
tlist[2:5] # 左闭右开
tlist[2:-1]
tlist[2:] tlist[:5]
tlist[:] 
# 步长
>>> tlist[::2]
[1, True, 'python', [100, 200, 300]]
>>> tlist[::3]
[1, (1+2j), [100, 200, 300]]
>>> tlist[::-1]# 翻转列表
[[100, 200, 300], 'r语言', 'python', (1+2j), True, 3.14, 1]
>>> tlist[2:5]
[True, (1+2j), 'python']
>>> tlist[2:5:2]
[True, 'python']

# 可变的有序序列
string='Python'
string[0]='p'
tlist[0]='p'
>>> tlist[0]='100'
>>> tlist
['100', 3.14, True, (1+2j), 'python', 'r语言', [100, 200, 300]]

# 增删改查
# 查询数据(索引、切片)
# 增加数据
# 不同的对象具有不同的方法
>>> string.append(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'str' object has no attribute 'append'

对象.方法名(参数)
list.append(object)# 将一个对象追加到列表的末尾
>>> tlist=[1,2,3]
>>> tlist.append('java')
>>> tlist.append('C++')
>>> tlist.append(['Excel','Mysql','Spss'])
>>> tlist
[1, 2, 3, 'java', 'C++', ['Excel', 'Mysql', 'Spss']]
>>>

list.extend(seqence)# 将一个序列中的元素依次追加到列表的末尾

list.insert(index,obj)# 将一个对象插入到列表的指定索引位置

修改数据(修改序列元素)
tlist[-1]='C#'

删除数据
del是通用方法,用于从内存空间中删除对象
del 对象  del list ; del list[index]
list.clear()# 将一个列表中的元素清空
# 通过索引删除
list.pop(index=-1)# 删除列表中的指定索引元素(默认索引为-1),会返回删除的对象
>>> tlist=['a','b','c']
>>> tlist
['a', 'b', 'c']
>>> tlist.pop()
'c'
>>> tlist
['a', 'b']
>>> tlist=['a','b','c']
>>> tlist.pop(0)
'a'
>>> tlist
['b', 'c']

# 通过目标删除
num=['Python','Excel','Mysql','Spss','Ps']
num.remove(obj)# 将列表中的指定对象删除
num.remove("Ps")
>>> num=['Python','Excel','Mysql','Spss','Ps']
>>> num.remove("Ps")
>>> num
['Python', 'Excel', 'Mysql', 'Spss']
Tip:remove方法只删除找到的第一个目标

# 其他常用操作
list.reverse()# 将列表元素进行翻转
list.sort()# 对列表元素进行排序
num=[1, 2, 5, 7, 10, 13, 23]
>>> num.sort()# 默认升序
>>> num
[1, 2, 5, 7, 10, 13, 23]
>>> num.sort(reverse=True)# 降序
>>> num
[23, 13, 10, 7, 5, 2, 1]
sorted(num)# 不修改原对象的情况下进行排序
>>> sorted(num)
[1, 2, 5, 7, 10, 13, 23]
>>> sorted(num,reverse=True)
[23, 13, 10, 7, 5, 2, 1]

list.conut(obj)# 对元素进行计数
>>> n=[1,2,1,2,1,2,3,4,5,2]
>>> n.count(2)
4
list.index(obj)# 第一个查找到元素所在位置
>>> n
[1, 2, 1, 2, 1, 2, 3, 4, 5, 2]
>>> n.index(2)
1
>>> n.index(1)
0
>>> n.index(3)
6

拼接操作:
list1+list2
>>> list1=[1,2,3]
>>> list2=['a','b','c']
>>> list1+list2
[1, 2, 3, 'a', 'b', 'c']
>>> list1+[4]
[1, 2, 3, 4]
>>> list1+[list2]
[1, 2, 3, ['a', 'b', 'c']]
>>> list1*3
[1, 2, 3, 1, 2, 3, 1, 2, 3]

# len(list) 查看元素数量  max(list) min(list) sum(list)



元组(tuple):与列表相似,但是元素不支持修改,也是一种有序序列
s='123'
l=[1,2,3]
t=(1,2,3) t=1,2,3 t=('Python',) t='Python',
>>> type(t)
<class 'tuple'>

# 有序序列:支持索引、切片
# 不可变:增删改
# len(list) 查看元素数量  max(list) min(list) sum(list)

list更加灵活  tuple更加安全
列表和元组的相互转化
list ---> tuple
tuple(list)
tuple ---> list
list(tuple)
str ---> tuple
tuple(str)
str ---> list
list(str)
str.join(seq)
>>> num=list('123456789')
>>> num
['1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> ''.join(num)
'123456789'
>>> '+'.join(num)
'1+2+3+4+5+6+7+8+9'
>>> '--'.join(num)
'1--2--3--4--5--6--7--8--9'


字典:一种由键值对作为元素组成的无序可变序列
dict1={key1:value1,key2:value2,key3:value3,...}
# 特性:
1、字典中键对象不能重复
2、字典的键对象必须是不可变类型(值对象没有要求)
# 不可变类型:字符串 数值 元组
# 可变类型:列表 字典

# 增删改查
# 查询数据
dict1={'key1':'value1','key2':'value2','key3':'value3','key4':'value4'}
dict1[key]-->value
>>> dict1['key5']# 不存在此键值对会报错
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'key5'

# 修改数据
dict1['key1']='new_value1'

# 添加数据
dict1['new_key']='add_value'

# 添加多个键值对
d1={'a':1,'b':2}
d2={'c':3,'d':4}
>>> d1.update(d2)
>>> d1
{'a': 1, 'b': 2, 'c': 3, 'd': 4}

# 删除数据
del dict1;del dict1[key]
dict.clear()# 清空字典中的元素
dict.pop(key)# 删除指定的键值对

# 其他常用操作
len(dict1)# 查看元素数量
key in dict# 成员判断(判断是否在字典键对象中)
dict.fromkeys(seq,value)# 以序列中的元素为键对象快速创建字典
dict([(key1,valu1),(key2,value2)])
dict(key1=value1,key2=value2)
user=['小明','小李','小张']
password=[123,456,789]
zip(user,password)
dict(zip(user,password))
>>> dict(zip(user,password))
{'小明': 123, '小李': 456, '小张': 789}


集合(set):与字典类似,它是一组字典键对象的集合,但是不保存value的值
>>> s={1,2,3,4,5}
>>> s
{1, 2, 3, 4, 5}
>>> type(s)
<class 'set'>
集合保留字典的特性,元素不能重复且不为可变序列,常用于去重
set([1,2,1,2,1,2])
set(['001','002','003','002'])
list(set([1,2,3,3]))


# 增删查
# 查询数据(list for循环遍历)
# 增加数据
set.add(obj)# 向集合中添加对象
set.update(seq)# 将一个序列中的元素添加到集合中
# 删除数据
set.claer()# 清空元素
set.remove(obj)# 删除集合中指定元素

# 其他常用操作
1 in {1,2,3}# 成员判断
len()# 查看元素数量

s1={1,2,3};s2={2,3,4}
>>> s1&s2# 交集
{2, 3}
>>> s1|s2# 并集
{1, 2, 3, 4}
>>> s1-s2# 差集
{1}



# python中有哪些内置数据类型
整型 浮点型 布尔型 复数 字符串 列表 元组 字典 集合
# 什么是序列,英文拼写是?
序列:可以将多个元素组织在一起的一种数据结构
sequence

info=[["小明",22,"程序员",10000,"北京"],
	  ["老王",40,"工程师",15000,"上海"],
	  ["老张",42,"医生",20000,"深圳"]]
# 通过格式化字符串用以下格式打印输出小明、老王、老张的信息:
# xxx的职业是xxx,目前xxx岁,在xxx工作每个月能拿xxxx元。
# 例如结果是print('小明的职业是程序员,目前22岁,在北京工作每个月能拿10000')
print('%s的职业是%s,目前%s岁,在%s工作每个月能拿%s'%("小明","程序员",22,"北京",10000))
print('%s的职业是%s,目前%s岁,在%s工作每个月能拿%s'%(info[0][0],info[0][2],info[0][1],info[0][4],info[0][3]))
print('%s的职业是%s,目前%s岁,在%s工作每个月能拿%s'%(info[1][0],info[1][2],info[1][1],info[1][4],info[1][3]))
print('%s的职业是%s,目前%s岁,在%s工作每个月能拿%s'%(info[2][0],info[2][2],info[2][1],info[2][4],info[2][3]))

# 将列表中的数字都做平方处理
num=[1,2,3,'a','b','c']
num[0]=num[0]**2
num[1]=num[1]**2
num[2]=num[2]**2
num

# 获取到列表中所有的奇数
num=[0,1,2,3,4,5,6,7,8,9,10]
>>> num[1::2]
[1, 3, 5, 7, 9]
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-08-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、变量
  • 二、标识符命名规则:
  • 三、运算符
  • 四、特殊字符
  • 五、数据类型
相关产品与服务
容器服务
腾讯云容器服务(Tencent Kubernetes Engine, TKE)基于原生 kubernetes 提供以容器为核心的、高度可扩展的高性能容器管理服务,覆盖 Serverless、边缘计算、分布式云等多种业务部署场景,业内首创单个集群兼容多种计算节点的容器资源管理模式。同时产品作为云原生 Finops 领先布道者,主导开源项目Crane,全面助力客户实现资源优化、成本控制。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档