总结python基本操作

1、用户交互

name = input("your name:")
age = input("your age:")  #input 接受的所有数据都是字符串,即便你输入的是数字,但依然会被当成字符串来处理
print( type(age) )
#int integer =整数  把字符串转成int,用int(被转的数据)
#str string =字符串 把数据转成字符串用str(被转的数据)
print("Your name:",name)
#print("You can still live for ",  death_age - int(age)," years ....")
print("You can still live for " +  str(death_age - int(age)) +" years ....")

2、if elif else

if 条件1:
自拍
elif 条件2:

else:
跳舞

a=1
b=2
if a>b:
   print("Yes")
elif a==b:
   print("第三") 
else:
   print("any")

3、注释

#单行注释
‘’‘多行注释’’’
“”" 多行注释 “”"

4、逻辑运算符

and 且,并且
只有两个条件全部为True(正确)的时候, 结果才会为True(正确)

条件1 and 条件2
5>3 and 6<2 True

or 或,或者
只要有一个条件为True,则结果为Ture,
5>3 or 6<2
真 或 假

not 不

not 5>3 == False
not 5<3 == True

短路原则
对于and 如果前面的第一个条件为假,那么这个and前后两个条件组成的表达式 的计算结果就一定为假,第二个条件就不会被计算

对于or
如果前面的第一个条件为真,那么这个or前后两个条件组成的表达式 的计算结果就一定为真,第二个条件就不会被计算

5、while循环

while 条件:

else:

num = 1
while num <= 10:
    num += 1
    if num == 5:
        break
    print(num)
else:
    print("This is else statement")
# break 中断,打断循环
# else 循环正常结束才执行

while 条件1:

while 条件2:

num1 = 0

while num1<=5:
    print(num1,end="_")
    num2 = 0
    while num2<=7:
        print(num2,end="-")
        num2+=1
        
    num1+=1
    print() #  print(end="\n")

6、布尔值

只有2种状态,分别是
真 True
假 False

7、格式化输出

name = input("Name:")
age = int(input("Age:"))
job = input("Job:")
salary = input("Salary:")

if salary.isdigit(): #长的像不像数字,比如200d , '200'
    salary = int(salary)
# else:
# print()
# exit("must input digit") #退出程序

msg = '''
--------- info of %s --------
Name: %s
Age : %d
Job : %s
Salary: %f
You will be retired in %s years
-------- end ----------
''' % (name,name ,age ,job ,salary, 65-age )
#d => digit       s => string
print(msg)

8、for循环

for i in range(1,101):
    if i % 2 == 1:
        print("loop:",i)
for i in range(100):
    if i < 50 or i > 70:
        print(i)



for i in range(1,101,2): # 2 => 步长
    print("loop:",i)

9、列表


索引(下标) ,都是从0开始
切片
.count 查某个元素的出现次数
.index 根据内容找其对应的位置
“haidilao ge” in a

   a=['wuchao','jinxin','xiaohu','sanpang','ligang']

# 查  切片 []
print(a[1:])#取到最后
print(a[1:-1])#取到倒数第二值
print(a[1:-1:1])#从左到右一个一个去取
print(a[1::2])#从左到右隔一个去取
print(a[3::-1])
b=a[3::-1]
print(b)#['sanpang', 'xiaohu', 'jinxin', 'wuchao']
print(a[-2::-1])
print(a[1:-1:-2])

#count:计算某元素出现次数
 t=['to', 'be', 'or', 'not', 'to', 'be'].count('to')
 print(t)
 #index
first_lg_index = a.index("ligang")

增加
a.append() 追加
a.insert(index, “内容”)
a.extend 扩展

 a=['wuchao','jinxin','xiaohu','sanpang','ligang']

# 添加 append insert

a.append('xuepeng')  #默认插到最后一个位置
print(a)

a.insert(1,'xuepeng') #将数据插入到任意一个位置
print(a)

extend
a = [1, 2, 3]
b = [4, 5, 6]
a.extend(b)
print(a)
print(b)

修改
a[index] = “新的值”
a[start:end] = [a,b,c]

 a=['wuchao','jinxin','xiaohu','sanpang','ligang']

# 修改

a[1]='haidilao'
print(a)
a[1:3]=['a','b']
print(a)

删除
remove(“内容”)
pop(index)
del a, del a[index]
a.clear() 清空


#删除 remove pop del
 a=['wuchao','jinxin','xiaohu','sanpang','ligang']


a.remove(a[0])
print(a)
b=a.pop(1) #返回值
print(a)
print(b)

del a[0]
print(a)
del a
print(a)
a.remove(['wuchao','jinxin'])
print(a)

排序
sort ()
reverse()

# reverse
a = ['wuchao', 'jinxin', 'xiaohu','ligang', 'sanpang', 'ligang']
a.reverse()
print(a)

# sort
x = [4, 6, 2, 1, 7, 9]
x.sort(reverse=True)
print(x)#[1, 2, 4, 6, 7, 9]

身份判断
>>> type(a) is list
True
>>>

10、字典

字典两大特点:无序,键唯一
字典的创建 / 增

dic={'name':'alex'}

dic2=dict((('name','alex'),))
print(dic2)

dic3=dict([['name','alex'],])
print(dic3)

dic1={'name':'alex'}
dic1['age']=18
print(dic1)
#增
#键存在,不改动,返回字典中相应的键对应的值
ret=dic1.setdefault('age',34)
print(ret)

#键不存在,在字典中中增加新的键值对,并返回相应的值
ret2=dic1.setdefault('hobby','girl')
print(dic1)
print(ret2)

dic4={'age': 18, 'name': 'alex', 'hobby': 'girl'}
# dic5={'1':'111','2':'222'}
dic5={'1':'111','name':'222'} #name覆盖

dic4.update(dic5)
print(dic4)
print(dic5)

查 通过键去查找

dic3={'age': 18, 'name': 'alex', 'hobby': 'girl'}

print(dic3['name'])

print(list(dic3.keys()))
print(list(dic3.values()))
print(list(dic3.items()))

dic3={'age': 18, 'name': 'alex', 'hobby': 'girl'}
dic3['age']=55
print(dic3)

dic5 = {'name': 'alex', 'age': 18, 'class': 1}

dic5.clear() # 清空字典
print(dic5)
del dic5['name'] #删除字典中指定键值对
print(dic5)

print(dic5.pop('age')) #删除字典中指定键值对,并返回该键值对的值
ret=dic5.pop('age')
print(ret)
print(dic5)

a = dic5.popitem() #随机删除某组键值对,并以元组方式返回值
print(a, dic5)

del dic5        #删除整个字典
print(dic5)

其他操作以及涉及到的方法

dic6=dict.fromkeys(['host1','host2','host3'],'test')
print(dic6)#{'host3': 'test', 'host1': 'test', 'host2': 'test'}

dic6['host2']='abc'
print(dic6)

dic6=dict.fromkeys(['host1','host2','host3'],['test1','tets2'])
print(dic6)#{'host2': ['test1', 'tets2'], 'host3': ['test1', 'tets2'], 'host1': ['test1', 'tets2']}

dic6['host2'][1]='test3'
print(dic6)#{'host3': ['test1', 'test3'], 'host2': ['test1', 'test3'], 'host1': ['test1', 'test3']}
#--------------------------------------------------------------------
dic={5:'555',2:'666',4:'444'}
dic.has_keys(5)
print(5 in dic)
print(sorted(dic.items()))
dic5={'name': 'alex', 'age': 18}

for i in dic5:
    print(i,dic5[i])

for i,v in dic5.items():
    print(i,v)

11、String 操作

a="Let's go "
print(a)
#1   * 重复输出字符串
print('hello'*20)

#2 [] ,[:] 通过索引获取字符串中字符,这里和列表的切片操作是相同的,具体内容见列表
print('helloworld'[2:])

#关键字 in
print(123 in [23,45,123])
print('e2l' in 'hello')

#4 %   格式字符串
print('alex is a good teacher')
print('%s is a good teacher' % 'alex')

#5
a='123'
b='abc'
d='44'
# c=a+b
# print(c)

c= ''.join([a,b,d])
print(c)

摘一些重要的字符串方法

print(st.count('l'))
print(st.center(50,'#'))   #  居中
print(st.startswith('he')) #  判断是否以某个内容开头
print(st.find('t'))
print(st.format(name='alex',age=37))  # 格式化输出的另一种方式   待定:?:{}
print('My tLtle'.lower())
print('My tLtle'.upper())
print('\tMy tLtle\n'.strip())
print('My title title'.replace('itle','lesson',1))
print('My title title'.split('i',1))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值