60 basic exercises for getting started with Python

Article directory

01-Hello World

Python's grammatical logic is completely based on indentation, and it is recommended to indent 4 spaces. If it is a top-level code, it must be written in the top case, even if there is only one space, there will be a grammatical error. In the following example, two lines of content must be output if the if condition is satisfied, and both lines of content must be indented and have the same indentation level.

print('hello world!')

if 3 > 0:
    print('OK')
    print('yes')

x = 3; y = 4   # 不推荐,还是应该写成两行
print(x + y)

02-print function

print('hello world!')
print('hello', 'world!')  # 逗号自动添加默认的分隔符:空格 hello world!
print('hello' + 'world!')  # 加号表示字符拼接 helloworld!
print('hello', 'world', sep='***')  # 单词间用***分隔 hello***world
print('#' * 50)  # *号表示重复 50 遍
print('how are you?', end='')  # 默认 print 会打印回车,end=''表示不要回车

03-Basic operations

  • Operators can be divided into: arithmetic operators, comparison operators and logical operators. The order of precedence is: Arithmetic Operators > Comparison Operators > Logical Operators. It is best to use parentheses to increase the readability of the code.
print(5 / 2)  # 2.5
print(5 // 2)  # 丢弃余数,只保留商
print(5 % 2)  # 求余数
print(5 ** 3)  # 5 的 3 次方
print(5 > 3)  # 返回 True
print(3 > 5)  # 返回 False
print(20 > 10 > 5)  # python 支持连续比较
print(20 > 10 and 10 > 5)  # 与上面相同含义
print(not 20 > 10)  # False

04-input

number = input("请输入数字:")  # input 用于获取键盘输入
print(number)
print(type(number))  # input 获得的数据是字符型

print(number + 10)  # 报错,不能把字符和数字做运算
print(int(number) + 10)  # int 可将字符串 10 转换成数字 10
print(number + str(10))  # str 将 10 转换为字符串后实现字符串拼接

05- Input and output basic exercises

username = input('username: ')
print('welcome', username)   # print 各项间默认以空格作为分隔符
print('welcome ' + username)  # 注意引号内最后的空格

06-Basic use of strings

In python, there is no difference between single and double quotes, they mean the same

sentence = 'tom\'s pet is a cat'  # 单引号中间还有单引号,可以转义
sentence2 = "tom's pet is a cat"  # 也可以用双引号包含单引号
sentence3 = "tom said:\"hello world!\""
sentence4 = 'tom said:"hello world"'
# 三个连续的单引号或双引号,可以保存输入格式,允许输入多行字符串
words = """
hello
world
abcd"""
print(words)

py_str = 'python'
len(py_str)  # 取长度
py_str[0]  # 第一个字符
'python'[0]
py_str[-1]  # 最后一个字符
# py_str[6]  # 错误,下标超出范围
py_str[2:4]  # 切片,起始下标包含,结束下标不包含
py_str[2:]  # 从下标为 2 的字符取到结尾
py_str[:2]  # 从开头取到下标是 2 之前的字符
py_str[:]  # 取全部
py_str[::2]  # 步长值为 2,默认是 1
py_str[1::2]  # 取出 yhn
py_str[::-1]  # 步长为负,表示自右向左取

py_str + ' is good'  # 简单的拼接到一起
py_str * 3  # 把字符串重复 3 遍

't' in py_str  # True
'th' in py_str  # True
'to' in py_str  # False
'to' not in py_str  # True

07 - List Basics

A list is also a sequence object, but it is a container type, and the list can contain various data

alist = [10, 20, 30, 'bob', 'alice', [1,2,3]]
len(alist)
alist[-1]  # 取出最后一项
alist[-1][-1]  # 因为最后一项是列表,列表还可以继续取下标
[1,2,3][-1]  # [1,2,3] 是列表,[-1] 表示列表最后一项
alist[-2][2]  # 列表倒数第 2 项是字符串,再取出字符下标为 2 的字符
alist[3:5]   # ['bob', 'alice']
10 in alist  # True
'o' in alist  # False
100 not in alist # True
alist[-1] = 100  # 修改最后一项的值
alist.append(200)  # 向**列表中追加一项

08-tuple basics

Tuples are basically the same as lists, except that tuples are immutable and lists are mutable.

atuple = (10, 20, 30, 'bob', 'alice', [1,2,3])
len(atuple)
10 in atuple
atuple[2]
atuple[3:5]
# atuple[-1] = 100  # 错误,元组是不可变的

09-Dictionary Basics

 # 字典是 key-value(键-值)对形式的,没有顺序,通过键取出值
 adict = {
    
    'name': 'bob', 'age': 23}
 len(adict)
 'bob' in adict  # False
 'name' in adict  # True
 adict['email'] = '[email protected]'  # 字典中没有 key,则添加新项目
 adict['age'] = 25  # 字典中已有 key,修改对应的 value

10-Basic judgment

Individual data can also be used as a judgment condition. Any number and empty object with a value of 0 is False, and any non-zero number or non-empty object is True.

if 3 > 0:
    print('yes')
    print('ok')

if 10 in [10, 20, 30]:
    print('ok')

if -0.0:
    print('yes')  # 任何值为 0 的数字都是 False

if [1, 2]:
    print('yes')  # 非空对象都是 True

if ' ':
    print('yes')  # 空格字符也是字符,条件为 True

11-Conditional expressions, ternary operators

a = 10
b = 20

if a < b:
    smaller = a
else:
    smaller = b
print(smaller)

s = a if a < b else b  # 和上面的 if-else 语句等价
print(s)

12-judgment exercise: whether the user name and password are correct

import getpass  # 导入模块

username = input('username: ')
# getpass 模块中,有一个方法也叫 getpass
password = getpass.getpass('password: ')

if username == 'bob' and password == '123456':
    print('Login successful')
else:
    print('Login incorrect')

13-Guess the number: basic implementation

import random

num = random.randint(1, 10) # 随机生成 1-10 之间的数字
answer = int(input('guess a number: '))  # 将用户输入的字符转成整数
if answer > num:
    print('猜大了')
elif answer < num:
    print('猜小了')
else:
    print('猜对了')

print('the number:', num)

14-Grade Category 1

score = int(input('分数:'))

if score >= 90:
    print('优秀')
elif score >= 80:
    print('好')
elif score >= 70:
    print('良')
elif score >= 60:
    print('及格')
else:
    print('你要努力了')

15-Grade Category 2

score = int(input('分数:'))

if score >= 60 and score < 70:
    print('及格')
elif 70 <= score < 80:
    print('良')
elif 80 <= score < 90:
    print('好')
elif score >= 90:
    print('优秀')
else:
    print('你要努力了')

16 - rock paper scissors

import random

all_choices = ['石头', '剪刀', '布']
computer = random.choice(all_choices)
player = input('请出拳:')

# print('Your choice:', player, "Computer's choice:", computer)
print("Your choice: %s, Computer's choice: %s" % (player, computer))
if player == '石头':
    if computer == '石头':
        print('平局')
    elif computer == '剪刀':
        print('You WIN!!!')
    else:
        print('You LOSE!!!')
elif player == '剪刀':
    if computer == '石头':
        print('You LOSE!!!')
    elif computer == '剪刀':
        print('平局')
    else:
        print('You WIN!!!')
else:
    if computer == '石头':
        print('You WIN!!!')
    elif computer == '剪刀':
        print('You LOSE!!!')
    else:
        print('平局')

17 - Improved rock paper scissors

import random

all_choices = ['石头', '剪刀', '布']
win_list = [['石头', '剪刀'], ['剪刀', '布'], ['布', '石头']]
prompt = """(0) 石头
(1) 剪刀
(2) 布
请选择 (0/1/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:
    print('\033[31;1mYou WIN!!!\033[0m')
else:
    print('\033[31;1mYou LOSE!!!\033[0m')

18- Guess the number until you get it right

import random

num = random.randint(1, 10)
running = True

while running:
    answer = int(input('guess the number: '))
    if answer > num:
        print('猜大了')
    elif answer < num:
        print('猜小了')
    else:
        print('猜对了')
        running = False

19 - Guess the number, 5 chances

import random

num = random.randint(1, 10)
counter = 0

while counter < 5:
    answer = int(input('guess the number: '))
    if answer > num:
        print('猜大了')
    elif answer < num:
        print('猜小了')
    else:
        print('猜对了')
        break
    counter += 1
else:  # 循环被 break 就不执行了,没有被 break 才执行
    print('the number is:', num)

20-while loop, counting up to 100

Because the number of loops is known, it is recommended to use the for loop in actual use

sum100 = 0
counter = 1

while counter < 101:
    sum100 += counter
    counter += 1

print(sum100)

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

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

23-for loop through data objects

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 usage and number 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)

25- List to realize the 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)

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

27 - List comprehension step by step

# 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-Rock, paper, scissors best of three games

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

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

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

32-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

33-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 代表的值赋值给形参

34-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

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

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

37-Generate Password/Verification Code

The name of this file is: randpass.py
Ideas:
1. Set a basic string for randomly extracting characters. In this example, use uppercase and lowercase letters plus numbers.
2. Cycle n times, randomly extracting a character each time.
3. Stitching each character Get up 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))

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

39-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=',')

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

41 - String Formatting

"%s is %s years old" % ('bob', 23)  # 常用
"%s is %d years old" % ('bob', 23)  # 常用
"%s is %d years old" % ('bob', 23.5)  # %d 是整数 常用
"%s is %f years old" % ('bob', 23.5)
"%s is %5.2f years old" % ('bob', 23.5)  # %5.2f 是宽度为 5,2 位小数
"97 is %c" % 97
"11 is %#o" % 11  # %#o 表示有前缀的 8 进制
"11 is %#x" % 11
"%10s%5s" % ('name', 'age')  # %10s 表示总宽度为 10,右对齐,常用
"%10s%5s" % ('bob', 25)
"%10s%5s" % ('alice', 23)
"%-10s%-5s" % ('name', 'age')  # %-10s 表示左对齐,常用
"%-10s%-5s" % ('bob', 25)
"%10d" % 123
"%010d" % 123

"{} is {} years old".format('bob', 25)
"{1} is {0} years old".format(25, 'bob')
"{:<10}{:<8}".format('name', 'age')

42-Common methods of shutil module

import shutil

with open('/etc/passwd', 'rb') as sfobj:
    with open('/tmp/mima.txt', 'wb') as dfobj:
        shutil.copyfileobj(sfobj, dfobj) # 拷贝文件对象

shutil.copyfile('/etc/passwd', '/tmp/mima2.txt')
shutil.copy('/etc/shadow', '/tmp/')  # cp /etc/shadow /tmp/
shutil.copy2('/etc/shadow', '/tmp/')  # cp -p /etc/shadow /tmp/
shutil.move('/tmp/mima.txt', '/var/tmp/')  # mv /tmp/mima.txt /var/tmp/
shutil.copytree('/etc/security', '/tmp/anquan') # cp -r /etc/security /tmp/anquan
shutil.rmtree('/tmp/anquan')  # rm -rf /tmp/anquan
# 将 mima2.txt 的权限设置成与/etc/shadow 一样
shutil.copymode('/etc/shadow', '/tmp/mima2.txt')
# 将 mima2.txt 的元数据设置成与/etc/shadow 一样
# 元数据使用 stat /etc/shadow 查看
shutil.copystat('/etc/shadow', '/tmp/mima2.txt')
shutil.chown('/tmp/mima2.txt', user='zhangsan', group='zhangsan')

43 - Exercise: Generating Text Files

import os

def get_fname():
    while True:
        fname = input('filename: ')
        if not os.path.exists(fname):
            break
        print('%s already exists. Try again' % fname)

    return fname

def get_content():
    content = []
    print('输入数据,输入 end 结束')
    while True:
        line = input('> ')
        if line == 'end':
            break
        content.append(line)

    return content

def wfile(fname, content):
    with open(fname, 'w') as fobj:
        fobj.writelines(content)

if __name__ == '__main__':
    fname = get_fname()
    content = get_content()
    content = ['%s\n' % line for line in content]
    wfile(fname, content)

44 - List Methods

alist = [1, 2, 3, 'bob', 'alice']
alist[0] = 10
alist[1:3] = [20, 30]
alist[2:2] = [22, 24, 26, 28]
alist.append(100)
alist.remove(24)  # 删除第一个 24
alist.index('bob')  # 返回下标
blist = alist.copy()  # 相当于 blist = alist[:]
alist.insert(1, 15)  # 向下标为 1 的位置插入数字 15
alist.pop()  # 默认弹出最后一项
alist.pop(2) # 弹出下标为 2 的项目
alist.pop(alist.index('bob'))
alist.sort()
alist.reverse()
alist.count(20)  # 统计 20 在列表中出现的次数
alist.clear()  # 清空
alist.append('new')
alist.extend('new')
alist.extend(['hello', 'world', 'hehe'])

45 - Check for legal identifiers

import sys
import keyword
import string

first_chs = string.ascii_letters + '_'
all_chs = first_chs + string.digits

def check_id(idt):
    if keyword.iskeyword(idt):
        return "%s is keyword" % idt

    if idt[0] not in first_chs:
        return "1st invalid"

    for ind, ch in enumerate(idt[1:]):
        if ch not in all_chs:
            return "char in postion #%s invalid" % (ind + 2)

    return "%s is valid" % idt

if __name__ == '__main__':
    print(check_id(sys.argv[1]))  # python3 checkid.py abc@123

46-Create a user and set a random password

For the randpass module, see "37-Generate Password/Verification Code"

import subprocess
import sys
from randpass import gen_pass

def adduser(username, password, fname):
    data = """user information:
%s: %s
"""
    subprocess.call('useradd %s' % username, shell=True)
    subprocess.call(
        'echo %s | passwd --stdin %s' % (password, username),
        shell=True
    )
    with open(fname, 'a') as fobj:
        fobj.write(data % (username, password))

if __name__ == '__main__':
    username = sys.argv[1]
    password = gen_pass()
    adduser(username, password, '/tmp/user.txt')
# python3 adduser.py john

47-List Exercise: Simulating Stack Operations

stack = []

def push_it():
    item = input('item to push: ')
    stack.append(item)

def pop_it():
    if stack:
        print("from stack popped %s" % stack.pop())

def view_it():
    print(stack)

def show_menu():
    cmds = {
    
    '0': push_it, '1': pop_it, '2': view_it}  # 将函数存入字典
    prompt = """(0) push it
(1) pop it
(2) view it
(3) exit
Please input your choice(0/1/2/3): """

    while True:
        # input() 得到字符串,用 strip() 去除两端空白,再取下标为 0 的字符
        choice = input(prompt).strip()[0]
        if choice not in '0123':
            print('Invalid input. Try again.')
            continue

        if choice == '3':
            break

        cmds[choice]()
        
if __name__ == '__main__':
    show_menu()

48- Realize unix2dos function in Linux system

import sys

def unix2dos(fname):
    dst_fname = fname + '.txt'

    with open(fname) as src_fobj:
        with open(dst_fname, 'w') as dst_fobj:
            for line in src_fobj:
                line = line.rstrip() + '\r\n'
                dst_fobj.write(line)

if __name__ == '__main__':
    unix2dos(sys.argv[1])

49 - Animator: @through a line#

\r is a carriage return without a newline

import time

length = 19
count = 0

while True:
    print('\r%s@%s' % ('#' * count, '#' * (length - count)), end='')
    try:
        time.sleep(0.3)
    except KeyboardInterrupt:
        print('\nBye-bye')
        break
    if count == length:
        count = 0
    count += 1

50-Dictionary basic usage

adict = dict()  # {}
dict(['ab', 'cd'])
bdict = dict([('name', 'bob'),('age', 25)])
{
    
    }.fromkeys(['zhangsan', 'lisi', 'wangwu'], 11)

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

print("%(name)s: %(age)s" % bdict)

bdict['name'] = 'tom'
bdict['email'] = '[email protected]'

del bdict['email']
bdict.pop('age')
bdict.clear()

51-Common methods of dictionaries

adict = dict([('name', 'bob'),('age', 25)])
len(adict)
hash(10)  # 判断给定的数据是不是不可变的,不可变数据才能作为 key
adict.keys()
adict.values()
adict.items()
# get 方法常用,重要
adict.get('name')  # 取出字典中 name 对应的 value,如果没有返回 None
print(adict.get('qq'))  # None
print(adict.get('qq', 'not found'))  # 没有 qq,返回指定内容
print(adict.get('age', 'not found'))
adict.update({
    
    'phone': '13455667788'})

52-Set common methods

# 集合相当于是无值的字典,所以也用{}表示
myset = set('hello')
len(myset)
for ch in myset:
    print(ch)

aset = set('abc')
bset = set('cde')
aset & bset  # 交集
aset.intersection(bset)  # 交集
aset | bset  # 并集
aset.union(bset)  # 并集
aset - bset  # 差补
aset.difference(bset)  # 差补
aset.add('new')
aset.update(['aaa', 'bbb'])
aset.remove('bbb')
cset = set('abcde')
dset = set('bcd')
cset.issuperset(dset)  # cset 是 dset 的超集么?
cset.issubset(dset)  # cset 是 dset 的子集么?

53-Collection example: take out the lines that exist in the second file but not in the first file

# cp /etc/passwd .
# cp /etc/passwd mima
# vim mima  -> 修改,与 passwd 有些区别

with open('passwd') as fobj:
    aset = set(fobj)

with open('mima') as fobj:
    bset = set(fobj)

with open('diff.txt', 'w') as fobj:
    fobj.writelines(bset - aset)

54-Dictionary Exercise: Simulate Registration/Login

import getpass

userdb = {
    
    }

def register():
    username = input('username: ')
    if username in userdb:
        print('%s already exists.' % username)
    else:
        password = input('password: ')
        userdb[username] = password

def login():
    username = input('username: ')
    password = getpass.getpass("password: ")
    if userdb.get(username) != password:
        print('login failed')
    else:
        print('login successful')

def show_menu():
    cmds = {
    
    '0': register, '1': login}
    prompt = """(0) register
(1) login
(2) exit
Please input your choice(0/1/2): """

	while True:
	         choice = input(prompt).strip()[0]
	         if choice not in '012':
	             print('Invalid inupt. Try again.')
	             continue
	         if choice == '2':
	             break
	 
	         cmds[choice]()
 
if __name__ == '__main__':
    show_menu()

55-Calculate the time of adding operation for tens of millions of times

import time

result = 0
start = time.time()  # 返回运算前时间戳
for i in range(10000000):
    result += i
end = time.time()   # 返回运算后时间戳
print(result)
print(end - start)

56- Common methods of time-related modules

import time

t = time.localtime()  # 返回当前时间的九元组
time.gmtime()  # 返回格林威治 0 时区当前时间的九元组
time.time()  # 常用,与 1970-1-1 8:00 之间的秒数,时间戳
time.mktime(t)  # 把九元组时间转成时间戳
time.sleep(1)
time.asctime()  # 如果有参数,是九元组形式
time.ctime()  # 返回当前时间,参数是时间戳,常用
time.strftime("%Y-%m-%d") # 常用
time.strptime('2018-07-20', "%Y-%m-%d")  # 返回九元组时间格式
time.strftime('%H:%M:%S')

###########################################
from datetime import datetime
from datetime import timedelta
datetime.today()  # 返回当前时间的 datetime 对象
datetime.now()  # 同上,可以用时区作参数
datetime.strptime('2018/06/30', '%Y/%m/%d')  # 返回 datetime 对象
dt = datetime.today()
datetime.ctime(dt)
datetime.strftime(dt, "%Y%m%d")

days = timedelta(days=90, hours=3)  # 常用
dt2 = dt + days
dt2.year
dt2.month
dt2.day
dt2.hour

Common methods of 57-os module

import os

os.getcwd()  # 显示当前路径
os.listdir()  # ls -a
os.listdir('/tmp')  # ls -a /tmp
os.mkdir('/tmp/mydemo')  # mkdir /tmp/mydemo
os.chdir('/tmp/mydemo')  # cd /tmp/mydemo
os.listdir()
os.mknod('test.txt')  # touch test.txt
os.symlink('/etc/hosts', 'zhuji')  # ln -s /etc/hosts zhuji
os.path.isfile('test.txt')  # 判断 test.txt 是不是文件
os.path.islink('zhuji')  # 判断 zhuji 是不是软链接
os.path.isdir('/etc')
os.path.exists('/tmp')  # 判断是否存在
os.path.basename('/tmp/abc/aaa.txt')
os.path.dirname('/tmp/abc/aaa.txt')
os.path.split('/tmp/abc/aaa.txt')
os.path.join('/home/tom', 'xyz.txt')
os.path.abspath('test.txt')  # 返回当前目录 test.txt 的绝对路径

58-pickle memory

import pickle
"""以前的文件写入,只能写入字符串,如果希望把任意数据对象(数字、列表等)写入文件,
取出来的时候数据类型不变,就用到 pickle 了
"""

# shop_list = ["eggs", "apple", "peach"]
# with open('/tmp/shop.data', 'wb') as fobj:
#     pickle.dump(shop_list, fobj)

with open('/tmp/shop.data', 'rb') as fobj:
    mylist = pickle.load(fobj)

print(mylist[0], mylist[1], mylist[2])

59 - Exception Handling Basics

try:   # 把有可能发生异常的语句放到 try 里执行
    n = int(input("number: "))
    result = 100 / n
    print(result)
except ValueError:
    print('invalid number')
except ZeroDivisionError:
    print('0 not allowed')
except KeyboardInterrupt:
    print('Bye-bye')
except EOFError:
    print('Bye-bye')

print('Done')

60-Exception Handling Complete Syntax

try:
    n = int(input("number: "))
    result = 100 / n
except (ValueError, ZeroDivisionError):
    print('invalid number')
except (KeyboardInterrupt, EOFError):
    print('\nBye-bye')
else:
    print(result)  # 异常不发生时才执行 else 子句
finally:
    print('Done')  # 不管异常是否发生都必须执行的语句

# 常用形式有 try-except 和 try-finally

Guess you like

Origin blog.csdn.net/zea408497299/article/details/125238327