10 basic exercises for getting started with Python (2)

1-while-break

break is to end the loop. After the break, the code in the loop body will not be executed.

while True:
    yn = input('Continue(y/n): ')
    if yn in ['n', 'N']:
        break
    print('running...')

2-while-continue

Calculates the sum of even numbers up to 100.

continue is to skip the rest of the loop and return to the loop condition.

sum100 = 0
counter = 0


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


print(sum100)

3-for loop through the data object

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]))

4-range usage and digital accumulation

# 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)

5- list implements Fibonacci sequence

Given two numbers first in the list, the next number is always the sum of the first two numbers.

fib = [0, 1]


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


print(fib)

6-nine-nine multiplication table

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()

7- Step by step implementation of list comprehension

# 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)]

8-Rock-paper-scissors best-of-three

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')

9- Basic operation of file object

# 文件操作的三个步骤:打开、读写、关闭
# 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()

10-Copy files

To copy a file is to open the source file with r, open the target file with w, read the source file data, and write it to the target file.

Here's the [NOT RECOMMENDED] way, but it will work:

f1 = open('/bin/ls', 'rb')
f2 = open('/root/ls', 'wb')


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


f1.close()
f2.close()

11-Copy files

Read 4K each time, until the end of reading:

src_fname = '/bin/ls'
dst_fname = '/root/ls'


src_fobj = open(src_fname, 'rb')
dst_fobj = open(dst_fname, 'wb')


while True:
    data = src_fobj.read(4096)  # 每次读取 4K
    if not data:
        break
    dst_fobj.write(data)


src_fobj.close()
dst_fobj.close()

12 - Positional parameters

Note: Numbers in positional parameters are in character form

import sys


print(sys.argv)  # sys.argv 是 sys 模块里的 argv 列表


# python3 position_args.py
# python3 position_args.py 10
# python3 position_args.py 10 bob

13-Function Application-Fibonacci Sequence

def gen_fib(l):
    fib = [0, 1]


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


    return fib  # 返回列表,不返回变量 fib


a = gen_fib(10)
print(a)
print('-' * 50)
n = int(input("length: "))
print(gen_fib(n))  # 不会把变量 n 传入,是把 n 代表的值赋值给形参

14-function-copy file

import sys


def copy(src_fname, dst_fname):
    src_fobj = open(src_fname, 'rb')
    dst_fobj = open(dst_fname, 'wb')


    while True:
        data = src_fobj.read(4096)
        if not data:
            break
        dst_fobj.write(data)


    src_fobj.close()
    dst_fobj.close()


copy(sys.argv[1], sys.argv[2])
# 执行方式
# cp_func.py /etc/hosts /tmp/zhuji.txt

15-Function-99 Multiplication Table

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


mtable(6)
mtable(9)

16 - Module Basics

Every file with a py extension is a module.

star.py:
hi = 'hello world!'


def pstar(n=50):
    print('*' * n)


if __name__ == '__main__':
    pstar()
    pstar(30)

Call the star module in call_star.py:

import star


print(star.hi)
star.pstar()
star.pstar(30)

17-Generate Password/Verification Code

This file is named: randpass.py

Ideas:

1. Set a basic string for randomly extracting characters. In this example, use uppercase and lowercase letters plus numbers

2. Loop n times, randomly take out a character each time

3. Stitch each character together and save it in the variable result

from random import choice
import string


all_chs = string.ascii_letters + string.digits  # 大小写字母加数字


def gen_pass(n=8):
    result = ''


    for i in range(n):
        ch = choice(all_chs)
        result += ch


    return result


if __name__ == '__main__':
    print(gen_pass())
    print(gen_pass(4))
    print(gen_pass(10))

18 - Sequence Object Methods

from random import randint


alist = list()  # []
list('hello')  # ['h', 'e', 'l', 'l', 'o']
list((10, 20, 30))  # [10, 20, 30]  元组转列表
astr = str()  # ''
str(10)  # '10'
str(['h', 'e', 'l', 'l', 'o'])  # 将列表转成字符串
atuple = tuple()  # ()
tuple('hello')  # ('h', 'e', 'l', 'l', 'o')
num_list = [randint(1, 100) for i in range(10)]
max(num_list)
min(num_list)

19 - Sequence object method 2

alist = [10, 'john']
# list(enumerate(alist))  # [(0, 10), (1, 'john')]
# a, b = 0, 10   # a->0  ->10


for ind in range(len(alist)):
    print('%s: %s' % (ind, alist[ind]))


for item in enumerate(alist):
    print('%s: %s' % (item[0], item[1]))


for ind, val in enumerate(alist):
    print('%s: %s' % (ind, val))


atuple = (96, 97, 40, 75, 58, 34, 69, 29, 66, 90)
sorted(atuple)
sorted('hello')
for i in reversed(atuple):
    print(i, end=',')

20 - String Methods

py_str = 'hello world!'
py_str.capitalize()
py_str.title()
py_str.center(50)
py_str.center(50, '#')
py_str.ljust(50, '*')
py_str.rjust(50, '*')
py_str.count('l')  # 统计 l 出现的次数
py_str.count('lo')
py_str.endswith('!')  # 以!结尾吗?
py_str.endswith('d!')
py_str.startswith('a')  # 以 a 开头吗?
py_str.islower()  # 字母都是小写的?其他字符不考虑
py_str.isupper()  # 字母都是大写的?其他字符不考虑
'Hao123'.isdigit()  # 所有字符都是数字吗?
'Hao123'.isalnum()  # 所有字符都是字母数字?
'  hello\t    '.strip()  # 去除两端空白字符,常用
'  hello\t    '.lstrip()
'  hello\t    '.rstrip()
'how are you?'.split()
'hello.tar.gz'.split('.')
'.'.join(['hello', 'tar', 'gz'])
'-'.join(['hello', 'tar', 'gz'])

Guess you like

Origin blog.csdn.net/JACK_SUJAVA/article/details/131923781