python入门的120个基础练习(3/12)

21-while-break
break是结束循环,break之后、循环体内代码不再执行。
while True:
yn = input('Continue(y/n): ')
if yn in ['n', 'N']:
break
print('running...')

22-while-continue
计算100以内偶数之和。
continue是跳过本次循环剩余部分,回到循环条件处。
sum100 = 0
counter = 0

while counter < 100:
    counter += 1
    # if counter % 2:
    if counter % 2 == 1:
        continue
    sum100 += counter

print(sum100)

23-for循环遍历数据对象
astr = 'hello'
alist = [10, 20, 30]
atuple = ('bob', 'tom', 'alice')
adict = {'name': 'john', 'age': 23}

for ch in astr:
    print(ch)

for i in alist:
    print(i)

for name in atuple:
    print(name)

for key in adict:
    print('%s: %s' % (key, adict[key]))

24-range用法及数字累加
# range(10) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# >>> list(range(10))
# range(6, 11) # [6, 7, 8, 9, 10]
# range(1, 10, 2) # [1, 3, 5, 7, 9]
# range(10, 0, -1) # [10, 9, 8, 7, 6, 5, 4, 3, 2, 1]
sum100 = 0

for i in range(1, 101):
    sum100 += i

print(sum100)

25-列表实现斐波那契数列
列表中先给定两个数字,后面的数字总是前两个数字之和。
fib = [0, 1]

for i in range(8):
    fib.append(fib[-1] + fib[-2])

print(fib)

26-九九乘法表
for i in range(1, 10):
for j in range(1, i + 1):
print('%s*%s=%s' % (j, i, i * j), end=' ')
print()

# i=1 ->j: [1]
# i=2 ->j: [1,2]
# i=3 ->j: [1,2,3]
#由用户指定相乘到多少
n = int(input('number: '))

for i in range(1, n + 1):
    for j in range(1, i + 1):
        print('%s*%s=%s' % (j, i, i * j), end=' ')
    print()

27-逐步实现列表解析
# 10+5的结果放到列表中
[10 + 5]
# 10+5这个表达式计算10次
[10 + 5 for i in range(10)]
# 10+i的i来自于循环
[10 + i for i in range(10)]
[10 + i for i in range(1, 11)]
# 通过if过滤,满足if条件的才参与10+i的运算
[10 + i for i in range(1, 11) if i % 2 == 1]
[10 + i for i in range(1, 11) if i % 2]
# 生成IP地址列表
['192.168.1.%s' % i for i in range(1, 255)]

28-三局两胜的石头剪刀布
import random

all_choices = ['石头', '剪刀', '布']
win_list = [['石头', '剪刀'], ['剪刀', '布'], ['布', '石头']]
prompt = """(0) 石头
(1) 剪刀
(2) 布
请选择(0/1/2): """
cwin = 0
pwin = 0

while cwin < 2 and pwin < 2:
    computer = random.choice(all_choices)
    ind = int(input(prompt))
    player = all_choices[ind]

    print("Your choice: %s, Computer's choice: %s" % (player, computer))
    if player == computer:
        print('\033[32;1m平局\033[0m')
    elif [player, computer] in win_list:
        pwin += 1
        print('\033[31;1mYou WIN!!!\033[0m')
    else:
        cwin += 1
        print('\033[31;1mYou LOSE!!!\033[0m')

29-文件对象基础操作
# 文件操作的三个步骤:打开、读写、关闭
# cp /etc/passwd /tmp
f = open('/tmp/passwd') # 默认以r的方式打开纯文本文件
data = f.read() # read()把所有内容读取出来
print(data)
data = f.read() # 随着读写的进行,文件指针向后移动。
# 因为第一个f.read()已经把文件指针移动到结尾了,所以再读就没有数据了
# 所以data是空字符串
f.close()

f = open('/tmp/passwd')
data = f.read(4)  # 读4字节
f.readline()  # 读到换行符\n结束
f.readlines()  # 把每一行数据读出来放到列表中
f.close()

################################
f = open('/tmp/passwd')
for line in f:
    print(line, end='')
f.close()

##############################
f = open('图片地址', 'rb')  # 打开非文本文件要加参数b
f.read(4096)
f.close()

##################################
f = open('/tmp/myfile', 'w')  # 'w'打开文件,如果文件不存在则创建
f.write('hello world!\n')
f.flush()  # 立即将缓存中的数据同步到磁盘
f.writelines(['2nd line.\n', 'new line.\n'])
f.close()  # 关闭文件的时候,数据保存到磁盘

##############################
with open('/tmp/passwd') as f:
    print(f.readline())

#########################
f = open('/tmp/passwd')
f.tell()  # 查看文件指针的位置
f.readline()
f.tell()
f.seek(0, 0)  # 第一个数字是偏移量,第2位是数字是相对位置。
              # 相对位置0表示开头,1表示当前,2表示结尾
f.tell()
f.close()

30-拷贝文件
拷贝文件就是以r的方式打开源文件,以w的方式打开目标文件,将源文件数据读出后,写到目标文件。
以下是【不推荐】的方式,但是可以工作:
f1 = open('/bin/ls', 'rb')
f2 = open('/root/ls', 'wb')

data = f1.read()
f2.write(data)

f1.close()
f2.close()

————————————————

作者:ChiefZHG

原文链接:https://blog.csdn.net/weixin_45

你可能感兴趣的:(python入门的120个基础练习(3/12))