微信公众号:大数据左右手
专注于大数据技术,人工智能和编程语言
个人既可码代码也可以码文字。欢迎转发与关注

一天学会Python基础

Python崇尚优美、清晰、简单,是一个优秀并广泛使用的语言。

应用领域

  • Web应用开发
  • 自动化运维
  • 科学计算
  • 桌面软件
  • 服务器软件(爬虫)
  • 游戏
  • 产品早期原型和迭代
  • 人工智能
  • 数据分析

###话不多说,开搞
1.输入框

a = input("input:")
print("你刚刚输入的是:%s"%a)

2.数***算

## 习惯性的计算
b=5
c=2
b+c
b-c
print(b*c) ##  相乘 10
print(b/c) ## 想除,与其他语言不同的是,这个可以得出小数2.5
print(b//c) ## 相除取整 2
print(b%c)  ## 相除取余数 1
print(b**c) ## 幂 25
## 表达式计算
d=input("input:")
e=eval(d)
e # input:7+8-4 # 11

3.判断执行

f=2
if f>=18:
    print("你已经成年了")
else:
    print("未成年")
print('-------if的几种情况-----------')
## ""  None 0 [] {} 都为假
## 非0为真
if not "":
    print('为假')
if not None:
    print('为假')
if not 0:
    print('为假')
if not []:
    print('为假')
if not {}:
    print('为假') 
if  1:
    print('为真')
if  -1:
    print('为真')
if  'a':
    print('为真')

结果

未成年
-------if的几种情况-----------
为假
为假
为假
为假
为假
为真
为真
为真

4.while循环执行

g=1

while g<10:
    print(g)
    g=g+1

结果

1
2
3
4
5
6
7
8
9

九九乘法表

i = 1
while i <= 9 :
    j = 1
    while j <= i :
        print("%d*%d=%d\t" % (j,i,i*j),end="")
        j += 1
    i += 1
    #print("\n",end="")
    print("")

结果

1*1=1	
1*2=2	2*2=4	
1*3=3	2*3=6	3*3=9	
1*4=4	2*4=8	3*4=12	4*4=16	
1*5=5	2*5=10	3*5=15	4*5=20	5*5=25	
1*6=6	2*6=12	3*6=18	4*6=24	5*6=30	6*6=36	
1*7=7	2*7=14	3*7=21	4*7=28	5*7=35	6*7=42	7*7=49	
1*8=8	2*8=16	3*8=24	4*8=32	5*8=40	6*8=48	7*8=56	8*8=64	
1*9=9	2*9=18	3*9=27	4*9=36	5*9=45	6*9=54	7*9=63	8*9=72	9*9=81	

5.for循环

print('---------for用法--------------')
k='wangbo'
l=''
for x in k:
    print(x)
print('---------for-else用法--------------')
for x in l:
    print(x)
else:
    print("没有数据")
print('---------break用法--------------')    
for x in k:
    if x=='n':
        break
    print(x)
print('----------continue用法-------------')    
for x in k:
    if x=='n':
        continue
    print(x)

结果

---------for用法--------------
w
a
n
g
b
o
---------for-else用法--------------
没有数据
---------break用法--------------
w
a
----------continue用法1-------------
w
a
g
b
o

6.字符串操作(结果在注释后面)

## len函数返回对象的长度或者个数
m1='wangbo'
len(m1) ## 结果6
m2=[1,2,3,4,5,6,7,8]
len(m2) ## 结果8
m3=(1,2,'a','5')
len(m3) ## 结果4
m4={'name':'wangbo','age':25}
len(m4) ## 结果2

## 通过下标取出部分字符
'''
[:] 提取从开头(默认位置0)到结尾(默认位置-1)的整个字符串
[start:] 从start 提取到结尾
[:end] 从开头提取到end - 1
[start:end] 从start 提取到end - 1
[start:end:step] 从start 提取到end - 1,每step 个字符提取一个
[::-1]逆序
'''
m5='wangbo'
m5[0]
m5[1]
m5[2] ## 输出结果 w a n (如果超出下标会报错)
  ## 从右边取字符串
m5[-1] ## '0'

## 切片 切片是指对操作的对象截取其中一部分的操作
m5[0:4] # 取 下标0~3 的字符: wang
m5[4:] # 取 下标为4开始到最后的字符:bo
m5[1:-1] # 取 下标为1开始 到 最后第2个  之间的字符: angb

## 逆序(倒序)
m5[::-1] # obgnaw

## find  rfind
m6='hello wang bo and wang'
m6.find('wang') # 在字符串中查找 字符串首次出现的位置 如果不存在就返回 -1
m6.find('o',6,len(m6)) # 指定查找区域
m6.rfind('bo') # 类似于 find()函数,不过是从右边开始查找

## index index()跟find()方法一样,只不过如果str不在 mystr中会报一个异常
## rindex 同理
m6.index('wang')

## replace 把 str1 替换成 str2,如果 count 指定,则替换不超过 count 次,最多等于count
## 函数:replace(str1, str2,  mystr.count(str1))
m6.replace('wang','li') # 'hello li bo and li'
m6.replace('wang','li',1) # 'hello li bo and wang'

## split 以 str 为分隔符切片 mystr,如果 maxsplit有指定值,则仅分隔 maxsplit 个子字符串
## 函数:split(str=" ", maxsplit)
m6.split(' ') # ['hello', 'wang', 'bo', 'and', 'wang']
m6.split('and') # 不留and部分 ['hello wang bo ', ' wang']
m6.split('wa',1) # 指定切割次数 ['hello ', 'ng bo and wang']


## partition rpartition  以str分割成三部分,str前,str自身和str后
## 函数:partition(str)
m6.partition('and') # ('hello wang bo ', 'and', ' wang')
m6.rpartition('wang') # ('hello wang bo and ', 'wang', '')

## splitlines 按照行分隔,返回一个包含各行作为元素的列表,按照换行符分割
m7='hello\nwang\nbo\nand\nwang'
m7.splitlines() # ['hello', 'wang', 'bo', 'and', 'wang']

## startswith 和 endswith 检查字符串是否是以 obj 开头或者结尾, 是则返回 True,否则返回 False
## 函数:startswith(obj)   endswith(obj)
m6.startswith("hello") # True
m6.endswith("wang") # True

## lower and upper 转化大小写
m6.upper() # 'HELLO WANG BO AND WANG'

## lstrip 删除str 左边的空白字符 当然还要右边 rstrip
m8=' hello   '
m8.lstrip() # 'hello   '
m8.rstrip() # ' hello'

## isspace  只包含空格,则返回 True,否则返回 False
m8.isspace() # False
' '.isspace() # True 一个空格
'      '.isspace() # True 多个空格

## join
m9=['hello', 'world', 'wangbo', 'and', 'python']
' '.join(m9) # 'hello world wangbo and python'

## count 返回 str在start和end之间 在 mystr里面出现的次数
## 函数:count(str, start=0, end=len(str))
m6.count('wang') # 2

## capitalize 把字符串的第一个字符大写
m6.capitalize() # 'Hello wang bo and wang'

## title 把字符串的每个单词首字母大写
m6.title() #'Hello Wang Bo And Wang'

## ljust 返回一个原字符串左对齐,并使用空格填充至长度 width 的新字符串
## 函数:ljust(width)
## 当然还有rjust 和center
m6.ljust(30) # 'hello wang bo and wang        '
m6.rjust(30) # '        hello wang bo and wang'
m6.center(30) #  '    hello wang bo and wang    '

## isalpha 所有字符都连续的是字母 则返回 True,否则返回 False
m6.isalpha() # False
'hello'.isalpha() # True
'hell8o'.isalpha() # False

## isdigit 只包含数字则返回 True 否则返回 False
'8'.isdigit() # True
'8g'.isdigit() # False

## isalnum 所有字符都是字母或数字则返回 True,否则返回 False
'8g'.isalnum() # True
'8g----'.isalnum() # False

7.列表(list) (结果在注释后面)

n = ['xiaoWang','xiaoZhang','xiaoHua']

## 取出
n[1] # 'xiaoZhang'

## 使用for循环
for name in n:
    print(name) # xiaoWang xiaoZhang xiaoHua
    
## 使用while循环
index = 0
while index<len(n):
    print(n[index]) # xiaoWang xiaoZhang xiaoHua
    index+=1

## 列表的增删改查
## 1.append
n.append('wangbo')
n[3] # 'wangbo'

## extend将另一个集合中的元素逐一添加到列表中
n1= [1,2]
n2=[3,4]
n1.append(n2)
n1 # [1, 2, [3, 4]]

n3= [1,2]
n4=[3,4]
n3.extend(n4)
n3 # [1, 2, 3, 4]

## insert在指定位置index前插入元素
## insert(index, object) 在指定位置index前插入元素object
n5=[1,3]
n5.insert(1,2)
n5 # [1, 2, 3]

## 删除元素("删"del, pop, remove)
n6=[1,2,3,4,5,6]
del n6[1]
n6 # [1, 3, 4, 5, 6]

  ## pop删除最后一个元素
n7=[1,2,3,4,5,6]
n7.pop()
n7 # [1, 2, 3, 4, 5]

  ## remove根据元素的值进行删除
n8=[1,2,3,4,5,6]
n8.remove(2)
n8 # [1, 3, 4, 5, 6]

## 通过下标修改元素("改")
n9=[1,2,3,4,5,6]
n9[1]=10
n9 # [1, 10, 3, 4, 5, 6]

## 查找元素("查"in, not in, index, count)
    ## in和not in 存在与不存在 返回True与False
if 20 not in n9:
    print('true')

## index和count index和count与字符串中的用法相同

## 排序(sort, reverse) 
'''
sort方法是将list按特定顺序重新排列,默认为由小到大,
参数reverse=True可改为倒序,由大到小。
reverse方法是将list逆置。
'''
n9=[9,3,5,2,7,2,1]
n9.sort()
n9 # [1, 2, 2, 3, 5, 7, 9]

n10=[9,3,5,2,7,2,1]
n10.sort(reverse=True)
n10 # [9, 7, 5, 3, 2, 2, 1]

n11=[9,3,5,2,7,2,1]
n11.reverse()
n11 # [1, 2, 7, 2, 5, 3, 9]

8.元组(Tuple)

o=(1,[2,3],4,5,6,7,8)

## 修改元组
## Python中不允许修改元组的数据,包括不能删除其中的元素。
##元组是不可变的,也就是说,元组中的元素在被赋值后不能改变。但是,如果元素本身是一个可变数据类型的列表,那么其嵌套项可以被改变
o[1].append(4)
o # (1, [2, 3, 4], 4, 5, 6, 7, 8)

## 元组的内置函数两个count, index
o1=('a','b','c','d','a')
o1.index('a',1,5) # 注意是左闭右开区间   结果:4
o1.count('a') # 2

## tuple函数 uple函数的功能与list函数基本上一样的,以一个序列作为参数并把它转换为元组,如果参数是元组,那么该参数就会被原样返回
o2=[1,2,3,4,5,6,7,8,9]
o3=tuple(o2)
o3 # (1, 2, 3, 4, 5, 6, 7, 8, 9)

## 多维列表/元祖
o4=[(2,3),(4,5)]
o4[0] # (2,3)
o4[0][0] # 2
o5=o4+[(3)]
o5 # [(2, 3), (4, 5), 3]

9.字典(dict) 和Map差不多

student= {'name':'who', 'id':100, 'sex':'男', 'address':'中国上海'}
student['name'] # 'who'
student.get("address") # '中国上海'

## 字典的增删改查
    ## 添加元素
student['work']='大数据'
student # {'name': 'who', 'id': 100, 'sex': '男', 'address': '中国上海', 'work': '大数据'}
student[(1,2)]='元组数据'
student # {'name': 'who','id': 100,'sex': '男','address': '中国上海','work': '大数据',(1, 2): '元组数据'}
    
## 删除元素
# del student['sex']

    ## del删除整个字典
# del student
    
    ## clear清空整个字典
# student.clear() # {}

    ## pop删除字典指定元素并且得到值
# student.pop('name') # 'who'

    ## popitem删除字典指定元素并且得到值
'''
    随机返回并删除字典中的一对键和值(项)。为什么是随机删除呢?
    因为字典是无序的,没有所谓的“最后一项”或是其它顺序。
    在工作时如果遇到需要逐一删除项的工作,用popitem()方法效率很高
'''
# student.popitem() # ((1, 2), '元组数据')

## 修改元素 通过key修改
student['id'] = 101

## 查找元素
student['id'] # 101


## 字典的键值操作

    ## len() 测量字典中,键值对的个数
len(student) # 6

    ## keys() 返回一个包含字典所有KEY的列表
list(student.keys()) # ['name', 'id', 'sex', 'address', 'work', (1, 2)]

    ## values() 返回一个包含字典所有value的列表
list(student.values()) # ['who', 101, '男', '中国上海', '大数据', '元组数据']

    ## items() 中返回可遍历的(键, 值) 元组数组
list((student.items()))
'''结果:
    [('name', 'who'),
     ('id', 101),
     ('sex', '男'),
     ('address', '中国上海'),
     ('work', '大数据'),
     ((1, 2), '元组数据')]
 '''
## 字典遍历
    ##遍历字典的key(键)
for key in student.keys():
       key

    ## 遍历字典的value(值)
for value in student.values():
    value

     ## 遍历字典的items(元素)
for item in student.items():
    item

    ## 遍历字典的key-value(键值对)
for temp in student.items():
    print('key=%s,value=%s'%(temp[0],temp[1]))
'''结果:
    key=name,value=who
    key=id,value=101
    key=sex,value=男
    key=address,value=中国上海
    key=work,value=大数据
    key=(1, 2),value=元组数据
'''
    ## 使用枚举遍历enumerate()
for i,chr in enumerate(student):
    print('%d:%s' %(i,chr))
'''结果:
0:name
1:id
2:sex
3:address
4:work
5:(1, 2)
'''

10.集合(set)

x=set('abcde')
x # {'a', 'b', 'c', 'd', 'e'}

y=set(['h','e','l','l','o'])
y # {'e', 'h', 'l', 'o'}

## 交集
x&y # {'e'}

## 并集
x|y # {'a', 'b', 'c', 'd', 'e', 'h', 'l', 'o'}

## 差集
y-x # {'h', 'l', 'o'}

## 对称差集(在x和y中,但不会同时出现在二者中)
x^y # {'a', 'b', 'c', 'd', 'h', 'l', 'o'}
看完之后是不是觉得十分简单,那恭喜你已经入门了

未完待续,继续关注一起学习

微信公众号:大数据左右手
人要去的地方,除了远方,还有未来
欢迎关注我,一起学习,一起进步!