迭代碎碎练_Express for i in 序列

迭代碎碎练

Python程序设计教程_江红_余青松_编著

Express for i in 序列                                     #迭代序列里所有内容,并计算生成列表n
Express for i in 序列 if cond_expr                 #按条件迭代,并计算生成列表  

print('Introducing Python')

# 注释1
'''
   注释2
'''
"""
   注释3
"""
print('Code structure')
alphabet = ''
alphabet += 'abcdefg' + \
            'hijklmnop' +\
            'qrstuv' +\
            'wxyz'
print(alphabet)

disaster = True
if disaster:
    print('Woe!')
else:
    print('Wheel!')

some_list = []
if some_list:
    print("There's something in here")
else:
    print("Hey,it's empty")

count = 1
while count <= 5:
    print(count)
    count += 1

accusation = {'room':'ballroom',
              'weapon':'lead pipe',
              'person':'Col. Mustard'}
for card in accusation:
    print('返回字典的键 = ',card)
for value in accusation.values():
    print('返回字典的值 = ',value)
for item in accusation.items():
    print('返回字典的键值对 = ',item)
for card,contents in accusation.items():
    print(card, contents)

cheeses = []
for cheese in cheeses:
    print('This shop has some lovely', cheese)
    break
else:
    print('This is not much of a cheese shop,is it? ')

found_one = False
for cheese in cheeses:
    found_one = True
    print("This shop has some lovely ",cheese)
    break
if not found_one:
    print('This is not much of a cheese shop,is it?')

print('-'*10,'分割线','-'*10)
days = ['Monday','Tuesday','Wednesday']
fruits = ['banana','orange','peach']
drinks = ['coffee','tea','beer']
desserts = ['tiramisu','ice cream','pie','pudding']

for day,fruit,drink,dessert in zip(days,fruits,drinks,desserts):
    print(day,":drink",drink,"-eat",fruit,"-enjoy",dessert)


english = ['Monday','Tuesday','Wednesday']
french = ['Lundi','Mardi','Mercredi']
print(zip(english,french))
print(list(zip(english,french)))
print(dict(zip(english,french)))

for x in range(0,3):
    #print('换行输入每个数 = ',x)
    print('',x,end=',')    #不换行输出
#print('\n')
print(list(range(0,3)))

for x in range(2,-1,-1):
    #print('反向创建序列= ',)
    print(x)
print(list(range(2,-1,-1)))
print(list(range(0,11,2)))


print(list([(x,y,x*y) for x in range(4) for y in range(1,4) if x>=y]))
x = [i**2 for i in range(10)]
print('x = ',x)

y = [j**3 for j in range(30) if j%2 == 0]
print('y = ',y)

h = [h for h in range(101)]
print(sum(h))

zh = [z for z in range(10)]             #自然数的和
print(sum(zh))

zh1 = [z**1 for z in range(10)]         #自然数的1次方的和  
print(sum(zh1))

jh = [jh for jh in range(101) if jh%2 == 1]    #奇数自然数的和
print('奇数和= ',sum(jh))

oh = [oh for oh in range(101) if oh%2 == 0]    #偶数自然数的和
print('偶数和= ',sum(oh))


zh2 = [z**2 for z in range(100)]         #自然数的2次方的和  
print(sum(zh2))


zh3 = [z**3 for z in range(100)]         #自然数的3次方的和  
print(sum(zh3))

 

posted @ 2021-11-27 17:30  CDPJ  阅读(59)  评论(0编辑  收藏  举报