Python Xiaobai counterattacks the Great God: Day1-Python basic exercises

When it comes to artificial intelligence, python is essential. Recently I also want to write a series of articles to summarize my python learning path, here is a little bit of today's content, by the way, an advertisement: my python learning path
.

Python basic learning:

1. Basic operation

Insert picture description here

2. Essential for all languages: conditions, cycles

#2.条件判断if
if 1 == 2: # 如果 if 跟随的条件为 假 那么不执行属于if 的语句,然后寻找 else
    print("假的")
else: # 寻找到 else 之后 执行属于else中的语句
    print("1==2是假的")

#3.循环操作---for
for i in range(5):
    print(i)
``

#3.循环操作---while
sum = 0
n = 99
while n > 0:
    sum = sum + n
    n = n - 1
print(sum)`


#4.break、continue、pass
#break语句可以跳出 for 和 while 的循环体
n = 1
while n <= 100:
    if n > 10:
        break
    print(n)
    n += 1

#continue语句跳过当前循环,直接进行下一轮循环
n = 1
while n < 10:
    n = n + 1
    if n % 2 == 0:
        continue
    print(n)
3.数据类型
数字

```python
#5.数据类型---Number(数字)
#Python支持int, float, complex三种不同的数字类型
a = 3
b = 3.14
c = 3 + 4j
print(type(a), type(b), type(c))

String


#5.数据类型---String(字符串)
#支持字符串拼接、截取等多种运算
a = "Hello"
b = "Python"
print("a + b 输出结果:", a + b)
#print("a[1:4] 输出结果:", a[1:4])

List


#5.数据类型---List(列表)
#列表是写在方括号 [] 之间、用逗号分隔开的元素列表。
#列表索引值以 0 为开始值,-1 为从末尾的开始位置。
list = ['abcd', 786 , 2.23, 'runoob', 70.2]
print(list[1:3])

#tinylist = [123, 'runoob']
#print(list + tinylist)

Tuple

#5.数据类型---Tuple(元组)
#tuple与list类似,不同之处在于tuple的元素不能修改。tuple写在小括号里,元素之间用逗号隔开。
#元组的元素不可变,但可以包含可变对象,如list。
t1 = ('abcd', 786 , 2.23, 'runoob', 70.2)
t2 = (1, )
t3 = ('a', 'b', ['A', 'B'])
t3[2][0] = 'X'
print(t3)

dictionary


#5.数据类型---dict(字典)
#字典是无序的对象集合,使用键-值(key-value)存储,具有极快的查找速度。
#键(key)必须使用不可变类型。
#同一个字典中,键(key)必须是唯一的。
d = {
    
    'Michael': 95, 'Bob': 75, 'Tracy': 85}
print(d['Michael'])

set

#5.数据类型---set(集合)
#set和dict类似,也是一组key的集合,但不存储value。由于key不能重复,所以,在set中,没有重复的key。
#set是无序的,重复元素在set中自动被过滤。
s = set([1, 1, 2, 2, 3, 3])
print(s)

First day homework

Homework 1: Output 9*9 multiplication formula table (note the format)

1. Through the for loop

def table():
    #在这里写下您的乘法口诀表代码吧!
    for i in range(1,10):
        for j in range(1,i+1):
           print("%d*%d=%2d"%(j,i,j*i),end=' ')
        #换行
        print(" ")


if __name__ == '__main__':
    table()

2. Through the while loop

def table():
   #设定行初始值为1
    h = 1
    #当行数小于等于9行,执行下面代码
    while h <= 9:
        #设定列初始值为1
        l = 1
        #当列小于等于行数时,执行下面代码
        while l <= h:
            #积等于行*列
            ji = h*l
            #输出行*列=积,结束的位置加空格
            print("%d*%d=%d"%(l,h,ji),end=" ")
            #注意要执行列+1不然会陷入死循环
            l+=1
        #换行
        print(" ")
        # 注意要执行行+1不然会陷入死循环
        h+=1


if __name__ == '__main__':
    table()

Assignment 2: Find a file with a specific name

Traverse the files in the "Day1-homework" directory;

Find the file whose name contains "2020";

Save the file name to the array result;

Print out in line according to the serial number and file name.

Note: There must be code execution output results when submitting the job.
The legendary os.walk() is used here,

The use of os.walk()

The function is declared as:

walk(file_path, topdown=True, οnerrοr=None, followlinks=False)

parameter

file_path is the address of the directory you want to traverse. If
topdown is true, the top directory will be traversed first, otherwise the subdirectories of top will be traversed first (default is on).
onerror requires a callable object. When the walk needs an exception, followlinks will be called. If true, It will traverse the directory that the shortcut under the directory (symbolic link under linux) actually refers to (closed by default)
. The return value of os.walk is a generator, which means we need to traverse it continuously to get All the content.
Each traversed object returns a triple (root, dirs, files)
root refers to the address of the folder that is currently being traversed
dirs is a list, the content is all in the folder The name of the directory (not including subdirectories)
files is also a list, and the content is all files in the folder (excluding subdirectories).
If the topdown parameter is true, walk will traverse the top folder, and each subfolder in the top folder table of Contents. Okay, so much, let’s see how to do homework.

#导入OS模块
import os
#待搜索的目录路径
path = "Day1-homework"
#待搜索的名称
filename = "2020"
#定义保存结果的数组
result = []

def findfiles(path):
    #在这里写下您的查找文件代码吧!
    i = 0
    for root, dirs, files in os.walk(path):
        for file in files:
            file = os.path.join(root,file)           
            if filename in file:   
                result.append("%d. %s "%(i,file))
                i+=1
            else:
                continue
        for dir in dirs:
            findfiles(dir)
    


if __name__ == '__main__':
    findfiles(path)
    for finded_file in result:
        print(finded_file) 

OK, the above is all the content of today, if you think it is good, please praise and pay attention.

Guess you like

Origin blog.csdn.net/qq_39748940/article/details/105813884