60 Basic Exercises for Python Beginners

Follow + Star, Learn New Python Skills Daily

Due to changes in the public account's push rules, please click "View" and add "Star" to receive exciting technical sharing immediately. Reply "python" in the background of the public account to get the latest free trial class in 2023.

01-Hello World
The syntax logic of python relies entirely on indentation, it is recommended to indent with 4 spaces. If it is top-level code, it must be aligned, even a single space will cause a syntax error. In the example below, if the condition of if is met, two lines of content must be output, and both lines must be indented with the same level of indentation.
print('hello world!')

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

x = 3; y = 4   # Not recommended, should be written in two lines
print(x + y)02-print functionprint('hello world!')
print('hello', 'world!')  # Comma automatically adds the default separator: space hello world!
print('hello' + 'world!')  # Plus sign indicates string concatenation helloworld!
print('hello', 'world', sep='***')  # Separate words with *** hello***world
print('#' * 50)  # * indicates repeat 50 times
print('how are you?', end='')  # By default, print will print a newline, end='' means do not print a newline03-basic operationsOperators can be divided into: arithmetic operators, comparison operators, and logical operators. The priority 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)  # Discard remainder, keep quotient
print(5 % 2)  # Get remainder
print(5 ** 3)  # 5 to the power of 3
print(5 > 3)  # Returns True
print(3 > 5)  # Returns False
print(20 > 10 > 5)  # Python supports chained comparisons
print(20 > 10 and 10 > 5)  # Same meaning as above
print(not 20 > 10)  # False04-inputnumber = input("Please enter a number:")  # input is used to get keyboard input
print(number)
print(type(number))  # input gets data in string type

print(number + 10)  # Error, cannot operate between string and number
print(int(number) + 10)  # int can convert string 10 to number 10
print(number + str(10))  # str converts 10 to string for string concatenation05-input output basic exerciseusername = input('username: ')
print('welcome', username)   # print defaults to separate with space
print('welcome ' + username)  # Note the trailing space in quotes06-string usage basicsIn basic python, there is no difference between single and double quotes, both represent the same meaning
sentence = 'tom\'s pet is a cat'  # Single quote contains another single quote, can escape
sentence2 = "tom's pet is a cat"  # You can also use double quotes to contain single quotes
sentence3 = "tom said:\"hello world!\""
sentence4 = 'tom said:"hello world"'
# Three consecutive single or double quotes can preserve input format and allow multi-line string input
words = """
hello
world
abcd"""
print(words)

py_str = 'python'
len(py_str)  # Get length
py_str[0]  # First character
'python'[0]
py_str[-1]  # Last character
# py_str[6]  # Error, index out of range
py_str[2:4]  # Slicing, starting index included, ending index not included
py_str[2:]  # Get characters from index 2 to the end
py_str[:2]  # Get characters from the beginning to before index 2
py_str[:]  # Get all
py_str[::2]  # Step value is 2, default is 1
py_str[1::2]  # Get yhn
py_str[::-1]  # Step is negative, indicating to take from right to left

py_str + ' is good'  # Simple concatenation
py_str * 3  # Repeat the string 3 times

't' in py_str  # True
'th' in py_str  # True
'to' in py_str  # False
'to' not in py_str  # True07-list basicsLists are also sequence objects, but they are container types, and lists can contain various data
alist = [10, 20, 30, 'bob', 'alice', [1,2,3]]
len(alist)
alist[-1]  # Get the last item
alist[-1][-1]  # Because the last item is a list, the list can continue to get the index
[1,2,3][-1]  # [1,2,3] is a list, [-1] indicates the last item of the list
alist[-2][2]  # The second to last item of the list is a string, then get the character at index 2
alist[3:5]   # ['bob', 'alice']
10 in alist  # True
'o' in alist  # False
100 not in alist # True
alist[-1] = 100  # Modify the last item's value
alist.append(200)  # Append an item to the list08-tuple basicsTuples are basically the same as lists, but tuples are immutable, while 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  # Error, tuples are immutable09-dictionary basics # Dictionaries are in key-value (key-value) pairs, without order, accessed by key
 adict = {'name': 'bob', 'age': 23}
 len(adict)
 'bob' in adict  # False
 'name' in adict  # True
 adict['email'] = '[email protected]'  # If the key does not exist in the dictionary, add a new item
 adict['age'] = 25  # If the key already exists in the dictionary, modify the corresponding value
110-basic judgmentSingle data can also be used as a judgment condition. Any value that is 0, empty object is False, any non-zero number, 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')  # Any value that is 0 is False

if [1, 2]:
    print('yes')  # Non-empty objects are True

if ' ':
    print('yes')  # Space character is also a character, condition is True11-conditional expressions, ternary operatorsa = 10
b = 20

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

s = a if a < b else b  # Equivalent to the above if-else statement
print(s)12-judgment exercise: whether the username and password are correctimport getpass  # Import module

username = input('username: ')
# There is also a method called getpass in the getpass module
password = getpass.getpass('password: ')

if username == 'bob' and password == '123456':
    print('Login successful')
else:
    print('Login incorrect')13-guessing numbers: basic implementationimport random

num = random.randint(1, 10) # Randomly generate a number between 1-10
answer = int(input('guess a number: '))  # Convert user input string to integer
if answer > num:
    print('Too high')
elif answer < num:
    print('Too low')
else:
    print('Correct guess')

print('the number:', num)14-score classification 1score = int(input('Score: '))

if score >= 90:
    print('Excellent')
elif score >= 80:
    print('Good')
elif score >= 70:
    print('Fair')
elif score >= 60:
    print('Pass')
else:
    print('You need to work hard')
15-score classification 2score = int(input('Score: '))

if score >= 60 and score < 70:
    print('Pass')
elif 70 <= score < 80:
    print('Fair')
elif 80 <= score < 90:
    print('Good')
elif score >= 90:
    print('Excellent')
else:
    print('You need to work hard')
16-rock paper scissorsimport random

all_choices = ['rock', 'scissors', 'paper']
computer = random.choice(all_choices)
player = input('Please choose: ')

# print('Your choice:', player, "Computer's choice:", computer)
print("Your choice: %s, Computer's choice: %s" % (player, computer))
if player == 'rock':
    if computer == 'rock':
        print('Draw')
    elif computer == 'scissors':
        print('You WIN!!!')
    else:
        print('You LOSE!!!')
elif player == 'scissors':
    if computer == 'rock':
        print('You LOSE!!!')
    elif computer == 'scissors':
        print('Draw')
    else:
        print('You WIN!!!')
else:
    if computer == 'rock':
        print('You WIN!!!')
    elif computer == 'scissors':
        print('You LOSE!!!')
    else:
        print('Draw')
17-improved rock paper scissorsimport random

all_choices = ['rock', 'scissors', 'paper']
win_list = [['rock', 'scissors'], ['scissors', 'paper'], ['paper', 'rock']]
prompt = """(0) rock
(1) scissors
(2) paper
Please choose (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 Draw, \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 guessedimport random

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

while running:
    answer = int(input('guess the number: '))
    if answer > num:
        print('Too high')
    elif answer < num:
        print('Too low')
    else:
        print('Correct guess')
        running = False

I have a lot of technical dry goods, fans can enjoy for free (click here)19-guess the number, 5 chancesimport random

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

while counter < 5:
    answer = int(input('guess the number: '))
    if answer > num:
        print('Too high')
    elif answer < num:
        print('Too low')
    else:
        print('Correct guess')
        break
    counter += 1
else:  # If the loop is broken, it will not be executed, only if it is not broken will it be executed
    print('the number is:', num)20-while loop, accumulate to 100because the number of loops is known, it is recommended to use for loop
sum100 = 0
counter = 1

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

print(sum100)21-while-breakbreak ends the loop, code inside the loop after break will not be executed.

while True:
    yn = input('Continue(y/n): ')
    if yn in ['n', 'N']:
        break
    print('running...')
22-while-continueCalculate the sum of even numbers within 100.
continue skips the remaining part of this loop and returns 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 to traverse data objectastr = '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 implementation of Fibonacci sequenceFirst give two numbers in the list, and the subsequent number is always the sum of the previous two numbers.
fib = [0, 1]

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

print(fib)26-nine-nine multiplication tablefor 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]
# Specified by the user to multiply to how much
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-step-by-step implementation of list comprehension# The result of 10+5 is placed in the list
[10 + 5]
# The expression 10+5 is calculated 10 times
[10 + 5 for i in range(10)]
# 10+i, where i comes from the loop
[10 + i for i in range(10)]
[10 + i for i in range(1, 11)]
# Filter through if, only those that meet the if condition participate in the operation of 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]
# Generate a list of IP addresses
['192.168.1.%s' % i for i in range(1, 255)]28-best of three rock paper scissorsimport random

all_choices = ['rock', 'scissors', 'paper']
win_list = [['rock', 'scissors'], ['scissors', 'paper'], ['paper', 'rock']]
prompt = """(0) rock
(1) scissors
(2) paper
Please choose (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 Draw, \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 operations on file objects# The three steps of file operations: open, read/write, close
# cp /etc/passwd /tmp
f = open('/tmp/passwd')  # Default opens the plaintext file in r mode
data = f.read()  # read() reads all content
print(data)
data = f.read()  # As reading and writing proceed, the file pointer moves forward.
# Because the first f.read() has already moved the file pointer to the end, reading again will have no data
# So data is an empty string
f.close()

f = open('/tmp/passwd')
data = f.read(4)  # Read 4 bytes
f.readline()  # Read to newline, n ends
f.readlines()  # Read each line of data and put it in the list
f.close()

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

##############################
f = open('image address', 'rb')  # Open non-text files with parameter b
f.read(4096)
f.close()

##################################
f = open('/tmp/myfile', 'w')  # 'w' opens the file, if the file does not exist, create it
f.write('hello world!\n')
f.flush()  # Immediately synchronize the data in the cache to the disk
f.writelines(['2nd line.\n', 'new line.\n'])
f.close()  # When closing the file, the data is saved to the disk

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

#########################
f = open('/tmp/passwd')
f.tell()  # View the position of the file pointer
f.readline()
f.tell()
f.seek(0, 0)  # The first number is the offset, the second is the number is relative position.
              # Relative position 0 means the beginning, 1 means current, 2 means end
f.tell()
f.close()
30-copying filesCopying files means opening the source file in r mode and opening the target file in w mode, then reading the source file data and writing it to the target file.
The following is [not recommended] way, but it works:
f1 = open('/bin/ls', 'rb')
f2 = open('/root/ls', 'wb')

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

f1.close()
f2.close()
31-copying files read 4K each time, until finished:
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)  # Read 4K each time
    if not data:
        break
    dst_fobj.write(data)

src_fobj.close()
dst_fobj.close()
32-position parametersNote: The numbers in positional parameters are in character form
import sys

print(sys.argv)  # sys.argv is the argv list in the sys module

# python3 position_args.py
# python3 position_args.py 10
# python3 position_args.py 10 bob33-function application-Fibonacci sequencedef gen_fib(l):
    fib = [0, 1]

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

    return fib  # Return the list, not return variable fib

a = gen_fib(10)
print(a)
print('-' * 50)
n = int(input("length: "))
print(gen_fib(n))  # Will not pass the variable n, but assign the value represented by n to the formal parameter34-function-copy fileimport 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])
# Execution method
# cp_func.py /etc/hosts /tmp/zhuji.txt35-function-nine-nine multiplication tabledef 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 basicsEvery 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)
In call_star.py call the star module:
import star

print(star.hi)
star.pstar()
star.pstar(30)
37-generate password/verification codeThis file is named: randpass.py
Idea:
1. Set a basic string for randomly extracting characters, this example uses uppercase and lowercase letters plus numbers
2. Loop n times, each time randomly extract a character
3. Concatenate each character and save it to the variable result
from random import choice
import string

all_chs = string.ascii_letters + string.digits  # Uppercase and lowercase letters plus numbers

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 methodsfrom random import randint

alist = list()  # []
list('hello')  # ['h', 'e', 'l', 'l', 'o']
list((10, 20, 30))  # [10, 20, 30]  # Tuple to list
astr = str()  # ''
str(10)  # '10'
str(['h', 'e', 'l', 'l', 'o'])  # Convert list to string
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 methods 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 methodspy_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')  # Count how many times l appears
py_str.count('lo')
py_str.endswith('!')  # Ends with!?
py_str.endswith('d!')
py_str.startswith('a')  # Starts with a? 
py_str.islower()  # Are all letters lowercase? Other characters do not matter
py_str.isupper()  # Are all letters uppercase? Other characters do not matter
'Hao123'.isdigit()  # Are all characters numbers?
'Hao123'.isalnum()  # Are all characters letters and numbers?
'  hello\t    '.strip()  # Remove whitespace characters at both ends, commonly used
'  hello\t    '.lstrip()
'  hello\t    '.rstrip()
'how are you?'.split()
'hello.tar.gz'.split('.')
'.'.join(['hello', 'tar', 'gz'])

41-string formatting
"%s is %s years old" % ('bob', 23)  # Commonly used
"%s is %d years old" % ('bob', 23)  # Commonly used
"%s is %d years old" % ('bob', 23.5)  # %d is integer commonly used
"%s is %f years old" % ('bob', 23.5)
"%s is %5.2f years old" % ('bob', 23.5)  # %5.2f is width 5, 2 decimal places
"97 is %c" % 97
"11 is %#o" % 11  # %#o means octal with prefix
"11 is %#x" % 11
"%10s%5s" % ('name', 'age')  # %10s means total width 10, right aligned, commonly used
"%10s%5s" % ('bob', 25)
"%10s%5s" % ('alice', 23)
"%-10s%-5s" % ('name', 'age')  # %-10s means left aligned, commonly used
"%-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 the shutil moduleimport shutil

with open('/etc/passwd', 'rb') as sfobj:
    with open('/tmp/mima.txt', 'wb') as dfobj:
        shutil.copyfileobj(sfobj, dfobj) # Copy file object

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
# Set the permissions of mima2.txt to be the same as /etc/shadow
shutil.copymode('/etc/shadow', '/tmp/mima2.txt')
# Set the metadata of mima2.txt to be the same as /etc/shadow
# Metadata is checked using stat /etc/shadow
shutil.copystat('/etc/shadow', '/tmp/mima2.txt')
shutil.chown('/tmp/mima2.txt', user='zhangsan', group='zhangsan')43-exercise: generate text filesimport 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('Input data, enter end to finish')
    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 methodsalist = [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)  # Remove the first 24
alist.index('bob')  # Return index
blist = alist.copy()  # Equivalent to blist = alist[:]
alist.insert(1, 15)  # Insert number 15 at index 1
alist.pop()  # Default pop the last item
alist.pop(2) # Pop the item at index 2
alist.pop(alist.index('bob'))
alist.sort()
alist.reverse()
alist.count(20)  # Count how many times 20 appears in the list
alist.clear()  # Clear
alist.append('new')
alist.extend('new')
alist.extend(['hello', 'world', 'hehe'])
45-check valid identifierimport 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@12346-create user, set random passwordrandpass 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 johnI have a lot of technical dry goods, fans can enjoy for free (click here)47-list exercise: simulate stack operationstack = []

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}  # Store functions in dictionary
    prompt = """(0) push it
(1) pop it
(2) view it
(3) exit
Please input your choice(0/1/2/3): """

    while True:
        # input() gets string, use strip() to remove whitespace at both ends, then take the character at index 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-implement unix2dos function in Linux systemimport 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-animation program: @passing through a line# \r is carriage return without line feed

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
150-basic usage of dictionaryadict = 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 dictionaryadict = dict([('name', 'bob'),('age', 25)])
len(adict)
hash(10)  # Determine if the given data is immutable, only immutable data can be used as key
adict.keys()
adict.values()
adict.items()
# get method is commonly used, important
adict.get('name')  # Get the value corresponding to name in the dictionary, if not return None
print(adict.get('qq'))  # None
print(adict.get('qq', 'not found'))  # No qq, return specified content
print(adict.get('age', 'not found'))
adict.update({'phone': '13455667788'})
52-common methods of set# Sets are equivalent to dictionaries without values, so they are also represented by {}
myset = set('hello')
len(myset)
for ch in myset:
    print(ch)

aset = set('abc')
bset = set('cde')
aset & bset  # Intersection
aset.intersection(bset)  # Intersection
aset | bset  # Union
aset.union(bset)  # Union
aset - bset  # Difference
aset.difference(bset)  # Difference
aset.add('new')
aset.update(['aaa', 'bbb'])
aset.remove('bbb')
cset = set('abcde')
dset = set('bcd')
cset.issuperset(dset)  # Is cset a superset of dset?
cset.issubset(dset)  # Is cset a subset of dset?
53-set example: take out the lines that are in the second file but not in the first file# cp /etc/passwd .
# cp /etc/passwd mima
# vim mima  -> modify, different from 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/loginimport 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-measure time for ten million addition operationsimport time

result = 0
start = time.time()  # Returns the timestamp before the operation
for i in range(10000000):
    result += i
end = time.time()   # Returns the timestamp after the operation
print(result)
print(end - start)
56-common methods of time moduleimport time

t = time.localtime()  # Returns the current time as a nine-tuple
 time.gmtime()  # Returns the Greenwich 0-hour time as a nine-tuple
 time.time()  # Commonly used, seconds between 1970-1-1 8:00 and now, timestamp
 time.mktime(t)  # Convert nine-tuple time to timestamp
 time.sleep(1)
 time.asctime()  # If there are parameters, it is in nine-tuple form
 time.ctime()  # Returns the current time, the parameter is timestamp, commonly used
 time.strftime("%Y-%m-%d") # Commonly used
 time.strptime('2018-07-20', "%Y-%m-%d")  # Returns the nine-tuple time format
 time.strftime('%H:%M:%S')

###########################################
from datetime import datetime
from datetime import timedelta
datetime.today()  # Returns the current time as a datetime object
datetime.now()  # Same as above, can use timezone as parameter
datetime.strptime('2018/06/30', '%Y/%m/%d')  # Returns datetime object
dt = datetime.today()
datetime.ctime(dt)
datetime.strftime(dt, "%Y%m%d")

days = timedelta(days=90, hours=3)  # Commonly used
dt2 = dt + days
dt2.year
dt2.month
dt2.day
dt2.hour57-common methods of os moduleimport os

os.getcwd()  # Show current path
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')  # Check if test.txt is a file
os.path.islink('zhuji')  # Check if zhuji is a soft link
os.path.isdir('/etc')
os.path.exists('/tmp')  # Check if it exists
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')  # Return the absolute path of test.txt in the current directory58-pickle storage deviceimport pickle
"""Previously, writing to files could only write strings. If you want to write any data object (numbers, lists, etc.) to a file,
And when it comes out, the data type does not change, you use 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-basic exception handlingtry:   # Put statements that may throw exceptions in try to execute
    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-complete syntax of exception handlingtry:
    n = int(input("number: "))
    result = 100 / n
except (ValueError, ZeroDivisionError):
    print('invalid number')
except (KeyboardInterrupt, EOFError):
    print('\nBye-bye')
else:
    print(result)  # Else clause executed only when no exception occurs
finally:
    print('Done')  # Statements that must be executed regardless of whether an exception occurs

Fan Benefits:Recruiting 99 novice learners who want to learn Python (only 99 students), free to take you from zero to entry level, live teaching every night and provide zero-based entry material package, add my WeChat: ADT9009, you can get it!!

60 Basic Exercises for Python Beginners

Reply "python" in the background of the public account to get the latest free trial class in 2023.

Leave a Comment