Python 基础知识(四)-----语句,表达式及流程控制

一. 语句与表达式

1. 代码风格

  1. 代码格式指南
    (1)PEP8
    (2) 缩进
    (3) 一行不超过79个字符
    (4) 空行

2. 赋值语句

  1. 基本赋值
(x,y)=(5,10)
x
5
y
10
  1. 序列赋值
[a,b,c]=(1,2,3)
a
1
b
2
a,b,c='uke'
a
'u'
b
'k'
c
'e'
  1. 扩展序列解包赋值
    (1) *变量,获取剩余元素到list
s='youpin'
a,b,*c=s
a
'y'
b
'o'
c
['u', 'p', 'i', 'n']
a,*b,c=s
a
'y'
b
['o', 'u', 'p', 'i']
c
'n'
a,b,c,*d='uke'
a
'u'
b
'k'
c
'e'
d
[]
  1. 多目标赋值
    (1)a=b=0
a=b=c='uke'
a
'uke'
b
'uke'
c
'uke'
a,b=[],[]
a.append(3)
a
[3]
b
[]
  1. 参数化赋值
x=5
y=6
x=x+y
x
11
l=[1,2]
l.extend([3,5,7])
l
[1, 2, 3, 5, 7]
l+=[9,10]
l
[1, 2, 3, 5, 7, 9, 10]

3. 表达式

  1. 函数调用
  2. 方法调用
  3. 字面值
  4. 打印操作
    (1)print(): sep=‘分隔符’, end='终止符‘, file=‘指定文件’
s='sss'
url='www.codeclassroom.com'
print(s,url)
sss www.codeclassroom.com
url2='www.uke.cc'
print(s,url,url2,sep='|')
sss|www.codeclassroom.com|www.uke.cc
print(s,url,url2,end='...\n')
sss www.codeclassroom.com www.uke.cc...
print(s,url,url2,end='...\n',file=open('result,txt','w'))

4. 流程控制

  1. if…语句
    (1)一般格式
score=95
if score>=90:
    print('excellent')
elif score>=80:
    print('good')
elif score >= 60:
    print('pass')
else:
    print('fail')

(2) 多重分支

def add(x):
    print(x+10)


operation={
    'add':add,
    'update':lambda x:print(x*2),
    'delete':lambda x:print(x*3)
}

def default_methond(x):
    print('doing nothing')

operation.get('delete',default_methond)(10)

(3)三元运算符
a. a=Y if X else Z

score=75
result="pass" if score >=60 else "fail"
print(result)
  1. while 循环
    (1) 一般格式
x="youpinketang"

while x:
    print(x,end=' ')
    x=x[1:]
a,b=0,10

while a < b:
    print(a)
    a += 1

(2) break (跳出循环)

while True:
    name=input('input your name:')
    if name == 'stop':
        break
    age=input('input your age:')
    print('hello:{},your age is:{},welcome'.format(name,age))
else:    
    print('loop end')

(3) continue ( 跳到原来的地方,不是继续)

x=10

while x:
    x -= 1
    if x %2 !=0:
        continue
    print(x,end=' ')

(4) pass
(5) else

for x in range(1,5):
    if x == 6:
        print('found',x)
        break
else:
     print('not found')
  1. for 循环
sum = 0
for x in [1,2,3,4,5]:
    sum += x

print(sum)
emp={
    'name':'Tom',
    'department':'technology',
    'job':'development',
    'salary':9000.00
}

for key in emp:
    print('{} => {}'.format(key,emp.get(key,'not found')))
for value in emp.values():
    print(value)

找s1和s2重叠的字母

s1='youpinketang.com'
s2='codeclassroom.com'

result=[]

for x in s1:
    if x in s2:
        result.append(x)

print(result)

l=[x for x in s1 if x in s2]
print(l)

(1) range() (不是list)

for x in range(1,100,2):
    print(x)

(2) enumerate() (获取索引)

s= 'youpinketang'

for idx,item in enumerate(s):
    print('{}) {}'.format(idx+1,item))
发布了11 篇原创文章 · 获赞 0 · 访问量 186

猜你喜欢

转载自blog.csdn.net/mangogogo321/article/details/104085736
今日推荐