Python自用

Python的第一次使用


//a+是追加的意思 file=fp等于写入文件
print("helloworld")
print("89.2")
fp = open('F:/python/test1/text.txt','a+')
print('ee',file=fp)
fp.close();

# 转义字符

print(“helloworld\t”)
print(“89.2\n”)
print(‘hllor\rword’)
print(‘hlll\bdd’)
print(‘http:\\www.baidu.com’)
print(‘‘sen’’)
print(r’hello\n’)

执行结果

word
hlldd
http:\\www.baidu.com
'sen'
hello\n

# 赋值规则

name = 'maliya'
print(name)
print(id(name),type(name))
==执行结果==
maliya
2686693451184 <class 'str'>

n1=90
print(type(n1))
print('2',0b1011111)
print('8',0o176)
print('16',0x1EAF)
==执行结果==
<class 'int'>
2 95
8 126
16 7855

a1=1.1
a2=2.2
print(a1,type(a1))
print(a1+a2)
from decimal import Decimal
print(Decimal('1.1')+Decimal('2.2'))
==执行结果==
1.1 <class 'float'>
3.3000000000000003
3.3

name='111'  
n1=2
flag=True
print(int(name)+n1) ## name必须是纯数字
print(int(flag))
113
1
=====float类似

# 注释

#coding:utf-8
#单行
‘’’
注释
‘’’

# 函数

prest=input("input a number:")
s2=input("input 2:")
print(int(prest)+int(s2))#类型为str

input a number:1
input 2:2
3

print(2**3)## 次方
print(2//1.1)## 整除
8
1.0

#################
print(2**3)## 次方
print(2//1.1)## 整除
print(9//-4)##一正一负向下取整
print(9%-4)# 9- -4*-3 算法 
结果
8
1.0
-3
-3

#####
a=b=c=4
print(type(b),type(a),id(a),id(b))
a/=3
print(a)
a,b,c = 20,39,40 #赋值
print(c)
a,b=b,a   # 交换值
print(a,b)

<class 'int'> <class 'int'> 3061632860496 3061632860496
1.3333333333333333
40
39 20

# 逻辑

a,b=10,2
print(a>b)
print(a<b)
print(a==b) # value
print(a is b) # id
print(a is not b) # not id
print(a==1 and b==2) # and 同时成立
print(a!=1)
print(a==1 or b==2) # or
f=True
print(not f)
s='helloworld'
print('w' in s) # 字符在里面
print(4&8)
print(4|8)
print(4<<2)
print(4>>2)
print(bool(False),bool(None),bool(''),bool([]))

True
False
False
False
True
False
True
True
False
True
0
12
16
1
False False False False

################
money = 1000
s = int(input("input a number"))
if money>=s:
    money=money-s
    print(money)

if s%2==0:
    print(s,'oushu')
else:
    print(s,"qishu")
#############
input a number3
997
3 qishu
########


if money>=90 and money<=100:
    print("a")
elif money<=90 and money>=80:
    print("b")
else:
    print("c")

 input a number08
c

############################

answer = input("yes or no")
money = 1000
s = int(input("input a number"))
if answer=='y':
    if money>=200:
        print("senge")
    else:
        print("senge2")
else:
    answer=='n'
    print('no')
##########
input a number2
yes or non
no


print( str(answer)+"" if answer>=s else str(s)+"") ##三元表达式
input a number4
yes or no3
4



r=range(10)
w=range(1,10,2) # 1 到10 步长2 
print(list(w))
print(r)
print(list(r))
print(9 in r)

############
a=1
while a <10:
    print(a)
    a+=1
for item in 'Python':
    print(item)


####文章输入三次 使用了 break
for item in range(3):
    pwd=input("input a  number")
    if pwd =='8888':
        print("correct")
        break
    else:
        print('no')



########## 只要整数
for item in range(1,51):
    if item%5!=0:
        continue
    print(item)

#################
a=0
while(a<3):
    pwd=input("input a number")
    if pwd=='8843':
        print("ok")
    else:
        print("no")
    a+=1
else:
    print("chulai")
############## while else

################ 
for i in range(1,4):
    for j in range(1,5):
        print('*',end='\t') ##不换行输出
    print()

############99乘法表
for i in range(1,10):
    for j in range(1,i+1):
        print(i,'*',j,'=',i*j,end='\t')
    print()

################# 连续几行 相同奇数
for i in range(4):
    for j  in range(1,10):
        if j%2!=0:
            print(j,end="\t")
    print()

##############


################### 数组操作
lst5=[10,29,30]
lst5.append(100)## 单个
lst5.extend([10,299,323,23]) # 添加多个
lst5.insert(1,90) ##任意位置
lst5[1:]=lst2 ## 相当于切掉 10, 10, 29, 39, 323, 233, 23
lst5.remove(10)
lst5.pop(1) ##移除第一个位置
lst5.pop() #默认最后一个 [10, 39, 323, 233]
lst5[1:3] ## 切片但不删除 产生新的
lst5[1:3]=[] ##切片删除
lst5.clear()
print(list(lst5))

lst6=[10,29,32,23]
lst6[2]=100
lst6.sort()#10, 23, 29, 100E##
lst6.sort(reverse=True) ## 逆序
s1=sorted(lst6,reverse=True) ## 新的序列
print(type(s1))
print(lst6)


#### for 的高级写法
lst=[i*i for i in range(1,10)]
print(lst)

# 字典

#set
sc={'zs':12,'dfd':123}
print(sc)
st=dict(name='jack',sen='dd')
print(st)

#get
print(sc['zs'])
print(st.get('name'))    ## 区别就是一个查不出来会报错一个会none

#in not in
print('zs' in sc)
print('zs' not in sc)

#del
del sc['zs']
sc['see'] = 12
sc['see'] = 13  # 重新更改
print(sc)

###getkey
print(sc.keys())
print(sc.values())
print(sc.items())
print(list(sc.items())) ##原数组

##遍历
for item in sc:
    print(item,sc[item],sc.get(item)) ##实际key

#zip
items=['furu','sd','dfd']
price=[1,2,3]
list1=zip(items,price)
print(list(list1))
list2={a.upper():b for a,b in zip(items,price)}
print(list2)

#元组 不可变序列
t=("PT","123",98)
print(t)
t2=tuple(("pyt","world","2"))
print(t2)
t3=(10,) ##一个元素必须加逗号
print(t3)
t4=() #空元祖
t5=tuple()

t6=(10,[20,30],9)
t6[1].append(30)##
print(t6) ## 因为中间的索引不能改变只能加进去

q=("pth",3,43)
for item in q:
    print(item)


############结果
{'zs': 12, 'dfd': 123}
{'name': 'jack', 'sen': 'dd'}
12
jack
True
False
{'dfd': 123, 'see': 13}
dict_keys(['dfd', 'see'])
dict_values([123, 13])
dict_items([('dfd', 123), ('see', 13)])
[('dfd', 123), ('see', 13)]
dfd 123 123
see 13 13
[('furu', 1), ('sd', 2), ('dfd', 3)]
{'FURU': 1, 'SD': 2, 'DFD': 3}
('PT', '123', 98)
('pyt', 'world', '2')
(10,)
(10, [20, 30, 30], 9)
pth
3
43

Process finished with exit code 0

# 集合

在这里插入图片描述

##集合
s={1,2,3,4,4}  ## 不能重复
print(s)
s1=set(range(5))
print(s1)
s2=set([1,2,3,4,5]) #
s3=set((1,2,3,4,67))
s2.add(6)
s3.add(7)
s2.update({100,200,3300}) ## 多次
s2.remove(3300)
s2.discard(3300) ##不会报错出现没有
s1.issubset(s2) # 子集
s1.issuperset(s2) # a是b子集 那b就是a超集
s1.isdisjoint(s2) # 是否交集
print(s1.isdisjoint(s2))
s4={10,20,30,40}
s5={20,30,40,50,60}
print(s4.intersection(s5))  #交集
print(s4 & s5) #等价交集
print(s4.union(s5)) #并集
print(s4 | s5) # 等同
##差集操作 只有自己有的两个里
print(s4.difference(s5)) #{10}
##对称差集操作
print(s4.symmetric_difference(s5)) #{50, 10, 60}
#集合生成式
s11=[i*i for i in range(10)]
print(s11)
print(s1==s2)
print(s2)
print(s3) ##集合无序
print(10 in s2)

#结果
{1, 2, 3, 4}
{0, 1, 2, 3, 4}
False
{40, 20, 30}
{40, 20, 30}
{40, 10, 50, 20, 60, 30}
{40, 10, 50, 20, 60, 30}
{10}
{50, 10, 60}
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
False
{1, 2, 3, 4, 5, 6, 100, 200}
{1, 2, 67, 3, 4, 7}
False

# 字符串

在这里插入图片描述
在这里插入图片描述

#
# s='3fhello,hello'
# print(s.index('he')) # index 会报错
# print(s.find('he')) # find 好一点 会-1
# print(s.rindex('he'))
# print(s.rfind('he'))
# s1='hello.python'
# s2=s1.upper()
# s3=s1.lower()
# print(s3)
# print(s2)
# print(s3==s2)
# print(s2 is s3)
# print(s3.center(20,"*")) #填充左右
# print(s3.ljust(20,'*')) #右填充
# print(s3.rjust(20,'*'))
# print(s3.zfill(20))
# s4='hello world python'
# s5='hello|world|python'
# print(s4.split())
# print(s5.split(sep='|'))
# print(s5.split(sep='|',maxsplit=1)) #['hello', 'world|python'] 分一组
# print(s4.rsplit())
# print(s5.rsplit(sep='|',maxsplit=1))
# #########
# print(s.isidentifier()) ## 是否为标识符
# print(s.isalpha()) # 字符
# print(s.replace('hello','se'))
# print(s.replace('hello','se',1))  ##最大替换次数
#
# lst=['hello','sdf','fdf']
# print('|'.join(lst)) #hello|sdf|fdf
# print('&'.join('senge')) #s&e&n&g&e

# print("apple">"app") #  true
# print(chr(97))
# print(ord("森"))
# '''
# ==与is的比较
# --比较的value  is 比较id
# '''
# a='a'
# b='a'
# print(a==b)
# print(a is b) #  type(id)
# s='adfdf,bdfdfd'
# s1=s[:5]
# s2=s[:6]
# s3=s[6:]
# ##=====================[star:end:stop]
# print(s1)
# print(s2)
# print(s3)
# s4=s[::-1]  ## 反过来
# print(s4)

##new day 4 17
######### 格式化字符串 #[1] % 占位符
# name='123'
# age=23
# print('w%s,%d' % (name,age)) ##
# #
# print('wo{0},{1}'.format(name,age))
# #
# #print(f'wfwdfd{name},{age}') ## 版本太低
# ##
#
# print('%10d' % 99)
# print('%.3f' % 3.1424242) #
# print('%10.3f' % 3.141312321)
# print('{0}'.format(3.141523223))
# print('{0:.3}'.format(3.141523223))
# print('{0:.3f}'.format(3.141523223))
# print('{:10.3f}'.format(3.141523223))
# print('{:10.3f}'.format(3.141523223)) ## 第一位最多写0
#
# ##
# s='森哥'
# print(s.encode(encoding='GBK'))
# print(s.encode(encoding='UTF-8'))
# byte = s.encode(encoding='UTF-8')
# print(byte.decode(encoding='UTF-8')) ## 解释只能同样的加码

# 函數

# def calc(a,b):
#     c=a+b
#     return c
# print(calc(1,2))
# print(calc(b=1,a=3)) ##关键字进去
# ##########可变对象改变值 不可变不改
# def fun(num):
#     odd=[]
#     even=[]
#     for i in num:
#         if i%2:
#             odd.append(i)
#         else:
#             even.append(i)
#     return odd,even
# lst=[10,23,24,52,344,342,243]
# print(fun(lst))
#
# def fun1(a,b=10):
#     print(a,b)
# fun1(2) ## 单参数函数
# fun1(2,3)
# print("hello") ## 默认有个end=t 换行
#
# def fun2(*a):    ##可变位置新参数
#     print(a)
#     print(a[0])
# fun2(1,123,2)
#
# def fun3(**a):        ####可变关键字新参
#     print(a)
# fun3(a=123)
# def fun4(*ages,**s): ##最多这么写 顶多出现一次这两种
#     print()
# ##########
# def fun5(a,b,c):
#     print('a=',a)
#     print('a=',b)
#     print('a=',c)
# fun5(10,29,30)
# fun5(*[1,2,3])
# dic={'a':1,'b':23,'c':3}
# fun5(**dic) ##关键字传参
# ####
# def fun6(a,b,*,c,d):
#     print(a)
#     print(b)
#     print(c)
#     print(d)
# fun6(10,20,c=23,d=123) #只能关键字传过去
# ######顺序问题
# def fun7(a,b,*,c,d,**args):
#     pass
# def fun8(*age,**args):
#     pass
# def fun():
#     global  age
#     age=20
#     print(age)
# fun()
# ##递归
# def fac(n):
#     if n==1:
#         return 1
#     else:
#         return n*fac(n-1)
# print(fac(6))
#
# try:
#     n1=2
# except ZeroDivisionError:
#     print("sdf")
# except ValueError:
#     print("sdf")
# else: ##没有异常就这个
#     print("dsf")
# finally: ##必须执行
#     print("")


# import traceback
# try:
#     print(1/0)
# except:
#     traceback.print_exc()

# class Person(object):
#     def __init__(self,name,age):
#         self.name=name
#         self.age=age
#     def info(self):
#         print(self.name)
#
# class Sen(Person):
#     print("dsff")
#
#
#
# class Student(Person):
#     #n1='12'
#     def __init__(self,name,age,stuid): ##初始化
#         # self.name= name
#         # self.age=age
#        super().__init__(name,age)
#        self.stuid=stuid
#     def __new__(cls, *args, **kwargs):
#         print("new {0}".format(id(cls)))
#         obj = super().__new__(cls)
#         print('{0}'.format(id(obj)))
#     #ee
#     def eat(self):
#         print("df",self.name,self.age)
#     @staticmethod #静态
#     def method():
#         print("sdfsdfs")
#     @classmethod
#     def cm(cls):
#         print("dsfsf")
#
#     def info(self):
#         print("senge")
#     def __str__(self): ##tostring重写
#         return "{0}{1}".format(self.name,self.age)
#     def __add__(self, other): ## add方法
#         return self.name+other.name
#     def __len__(self):
#         return len(self.name)



# print(id(Student))
# st1=Student("sem",23,111)
# #st1.gender="d" ## 动态添加属性
# Student.method()
# Student.cm()
# #st1.info() ##重写方法
# print(dir(st1))
# #print(st1.age)
# #print(st1.stuid) ##同时可以多继承
# print(st1)
# print(st1.__dict__)
# print(st1.__class__)
# print(Student.__base__)
# print(Student.__mro__)
# print(Student.__subclasses__())
# str2=Student("se",123,23)
# s=st1+str2
# print(s)
# lst=[1,2,3,4]
# print(lst.__len__()) ##
# print(len(st1)) ## 重写len

########### new  init new完在init

# class cpu:
#     pass
# class Computer:
#     def __init__(self,cpu):
#         self.cpu=cpu
# cpu1=cpu()
# cpu2=cpu1
# print(id(cpu1))
# print(id(cpu2))
# com = Computer(cpu1)
# import  copy
# c2=copy.copy(com)  ## 浅复制 如果有属性也只是指向
# print(c2)
# c3=copy.deepcopy(com) ## 深拷贝
# print(c3)

模块

在这里插入图片描述

import  math
print(id(math))
print(math.pi)
print(dir(math))
print(pow(2,3))
from first import fun1
print(fun1(1,2))

if __name__=='__main__': ##只有在主才会运行
    print(fun1(10,29))
import se.cal as a ## 如果是包的话这么导入还有别名
from se.cal import a ##或者
print(a.a)

import sys
import time
print(sys.getsizeof(24)) ##获取内存
print(sys.getsizeof(31))
print(time.time())
print(time.localtime(time.time()))
import urllib.request
print(urllib.request.urlopen("http://www.baidu.com").read())

#编码格式

在这里插入图片描述
在这里插入图片描述

#encoding= 可以设置
##python 默认utf-8
# file=open('a.txt','a')
#print(file.readlines())
# file.write("dfsf")
file1=open('a.txt','a')
lst=['java','go','python']
file1.writelines(lst)
file1.close()


在这里插入图片描述

##实现了上下文管理
class MyCont(object):
    def __enter__(self):
        print("enter")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("exit")
    def fun1(self):
        print("se")

with MyCont() as file3:
    file3.fun1()

with open('a.txt','r') as file2:
    print(file2.read())

os 函数

在这里插入图片描述
在这里插入图片描述

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值