1. Use recursion to list all files in the current directory ( Format requirements : Layered output )
requirement : least 4 Layer Directory : such as :
test:
-test.txt
-test_data.xls
-test1
-test1.txt
-test_data1.txt
-test2
-test2.txt
-test2_data.txt
-test3
-test3.txt
-test3_data.txt
import os
def traverse_file(path, arg=0):
for i in os.listdir(path): # Iterate over all directory names and file names under the specified directory level
dir_path = os.path.join(path, i) # The full path
if os.path.isdir(dir_path): # Determine whether it is a directory
tree_str = "\t|" * arg + '-' * 4
print(tree_str + i)
traverse_file(dir_path, arg=arg + 1)
else:
tree_str = "\t|" * arg + '-' * 4
print(tree_str + i)
if __name__ == '__main__':
root_path = input(" Please enter the absolute path of the directory :")
print(root_path.split('\\')[-1] + '\\')
traverse_file(root_path)
2. Give a score score, At random 8 A score =》 8 Sum of two output /8 = 80,
8 The distribution of scores ,score - 10 < score < score + 10
import random
score = 80
while True:
scores = random.sample(range(score - 10, score + 10), 8)
if sum(scores) / 8 == 80:
break
print(scores)
D:\Python\python.exe F:/python/2021.8.16python/day05_work.py
[70, 82, 79, 76, 86, 72, 87, 88]
Process finished with exit code 0
3. Define a class :Person
Class properties :type="student"
Object properties :name, age, gender
Method :print_info: Print the content : So-and-so is a good student.
Override... In a class :__new__ and __init__, And print __new__ and __init__ To display the called
Instantiate two objects : zhangsan, lisi And call the method :
class Person:
type = "student"
def __new__(cls, *args, **kwargs):
print("__new__")
return super(Person, cls).__new__(Person)
def __init__(self, name, age, gender):
self.name = name
self.age = age
self.gender = gender
print("__init__")
def print_info(self):
print('{} is a good student'.format(self.name))
if __name__ == '__main__':
person = Person(" Zhang San ", 18, " male ")
person.print_info()
print(person.age, person.gender, Person.type, person.type)
D:\Python\python.exe F:/python/2021.8.16python/day05_work.py
__new__
__init__
Zhang San is a good student
18 male student student
Process finished with exit code 0