Common functions involved: string related operations list related operations generate **** calendar, determine leap year IO operations basic math calculations bubble sort turtle Draw pentacle

#1, string case conversion

Str_random = 'you can DO whatever you want to DO with python' print(str_random.title()) # capitalize the first letter of each word Print (str_random.capitalize()) # capitalize(str_random.lower()) # capitalize(str_random.upper()) # capitalizeCopy the code
! [](https://p1-tt-ipv6.byteimg.com/large/pgc-image/07f8ec7e1b68455dbb1efd1932a108d1)

#2, determine the type of string (you can write test case yourself)

Print ('test case 1') str_random = 'python3.7/Java/C++' print(str_random.islower()) # Print (str_random.isupper()) print(str_random.istitle()) print(str_random.isspace()) # check if all characters are whitespace Print (str_random.isalnum()) print(str_random.isalnum()) print(str_random.isalpha()) print(str_random.isalnum()) print(str_random.isalpha()) print(str_random.isalnum()) print(str_random.isalnum()) print(str_random.isalnum()) print(str_random.isalnum()) # check if all characters are numbersCopy the code
! [](https://p1.pstatp.com/origin/pgc-image/9079d0b9507143e3b582927af3354d33)

#3, count the number of days in any month

import calendar year = int(input('please enter the year: ')) month = int(input('please enter the month: ')) DaysofMonth = calendar.monthrange(year, month) print('%s year %s month has %s (weekday, days)' % (year, month, DaysofMonth)) #weekady is the first weekday of the month. For example, if input is October 2020, (weekday, days)=(3,31) October 1 is Thursday.Copy the code
! [](https://p6-tt-ipv6.byteimg.com/large/pgc-image/14f34196217847bf978d0ff9c7c72fad)

#4, get the date of the day before yesterday, yesterday, and today

import datetime
today = datetime.date.today()
oneday = datetime.timedelta(days = 1)
yesterday = today - oneday
thedaybeforeyesterday = today - 2 * oneday
print(thedaybeforeyesterday, '\n', yesterday, '\n', today)
Copy the code
! [](https://p3-tt-ipv6.byteimg.com/large/pgc-image/dd0c207c1c3941aa9a9f52a1a398b040)

#5, generate calendar

import calendar year = int(input('please enter the year: ')) month = int(input('please enter the month: ')) print(calendar.month(year, month)) print(calendar.calendar(year)) print(calendar.calendar(year)) print(calendar.calendar(year)Copy the code
! [](https://p1.pstatp.com/origin/pgc-image/15b69967c1904f8aa233f9259d90c287)

#6, check if it’s a leap year

year = int(input('please enter the year: ')) if (year % 4) == 0 and (year % 100) ! = 0 or (year % 400) == 0: print('%s is leap year' % (year)) else: print('%s is NOT leap year' % (year)) 12345Copy the code
! [](https://p1-tt-ipv6.byteimg.com/large/pgc-image/61e4e23d49e14c4ba9b73bceac11ad94)

#7, file IO operation

with open('test.txt', 'wt') as out_txt: Write ('this text will be written into file \n you can see me now.') with open('test.txt', 'rt') as in_txt: # print content = in_txt.read() print(content) 123456Copy the code
! [](https://p1.pstatp.com/origin/pgc-image/6f9648ee1e4c4f15ab07c4d22d0e4fd2)

Print the path to the specified file, for example.mp3

import os path = r'C:\Users\python_music download' musicpathlist = [] for root, dirs, files in os.walk(path): For file in files: if os.path.splitext(file)[1] == '.mp3': Append (os.path.join(path, file)) print(MusicPathList) 12345678Copy the code
! [](https://p6-tt-ipv6.byteimg.com/large/pgc-image/3f46b5b8755647f8bf2f05fb8dae3ce1)

#9, output all subfolder paths under a path

import os filepath = r'C:\python test\test_202009' for i in os.listdir(filepath): If os.path.isdir(subfilepath): subfilepath = (os.path.join(filepath, I)) # if os.path.isdir(subfilepath): Print (subfilepath) 1234567Copy the code
! [](https://p1-tt-ipv6.byteimg.com/large/pgc-image/6677684ca36443c785324d37beb28576)

#10, regular matching, take 51Job as an example

Import re file = open('51job.txt', encoding=' utF-8 ') You can also use the request module contents = STR (file.readlines()) # to read the contents pattern_tag1 = re.compile(r'{"type":.*?"tags":.*?"job_name":"(.*?)".*?"adid":""}', Re. # S) match the job title pattern_tag2 = re.com running (r '{" type ":. *?" tags ":. *?" company_name ":" (. *?) ". *? "adid" : ""}'. Re. # S) match the company name pattern_tag3 = re.com running (r '{" type ":. *?" tags ":. *?" providesalary_text ":" (. *?) ". *? "adid" : ""}'. Re. # S) match the salary pattern_tag4 = re.com running (r '{" type ":. *?" tags ":. *?" workarea_text ":" (. *?) ". *? "adid" : ""}'. Re. # S) match the work place pattern_tag5 = re.com running (r '{" type ":. *?" tags ":. *?" updatedate ":" (. *?) ". *? "adid" : ""}'. Tag2_list = Re.findall (pattern_tag1, contents) # Store items in the form of a list tag2_list = Re.findall (pattern_tag2, contents) contents) tag3_list = re.findall(pattern_tag3, contents) tag4_list = re.findall(pattern_tag4, Tag5_list = re.findall(pattern_tag5, contents) print(tag1_list, len(tag1_list)) len(tag2_list)) print(tag3_list, len(tag3_list)) print(tag4_list, len(tag4_list)) print(tag5_list, Len (tag5_list) # 5 above the class information (also can increase the matching other information) can be integrated in the same list file. The close () 12345678910111213141516171819Copy the code
! [](https://p9-tt-ipv6.byteimg.com/large/pgc-image/37d6b03bf61c4bc1999118f2735ca46c)

#11, simply operate Excel, take the content of the 5 types of information matched in Example 10 as an example

Import XLWT file1 = xlwt.workbook () sheet = file1.add_sheet('job_info') # create worktable row0 = [" serial number ", "position name" and "company name", "work", "salary", "released"] # 1 line for I in range (0, len (row0)) : Sheet. Write (0, I, row0[I]) # for j in range(0, len(tag1_list)): Write (j+1, 1, tag1_list[j]) Write (j+1, 3, tag3_list[j]) # providesalARY_text write(j+1, 4, Tag4_list [j]) # tag4_list[j]) # tag4_list Save ('test_51job.xls') # save 1234567891011121314Copy the code
! [](https://p1.pstatp.com/origin/pgc-image/a7a1c47ed19b4672a2fe00e433dac0f0)

#12, decimal to binary, octal, hexadecimal

num = int(input('please enter a number: '))
print('decimal number is:', num)
print('binary number is:', bin(num))
print('octonary number is:', oct(num))
print('hexadecimal number is:', hex(num))
12345
Copy the code
! [](https://p1.pstatp.com/origin/pgc-image/738079449bcb42e98ecd27738a637609)

#13, find the greatest common divisor of two numbers

x = int(input('please enter a number: ')) y = int(input('please enter another number: ')) def gcd(a, b): if a < b: a, b = b, a while b ! = 0: temp = a % b a, b = b, temp return a print('the greatest common divisor of %s and %s is %s' % (x, y, gcd(x, y))) 12345678910Copy the code
! [](https://p26-tt.byteimg.com/large/pgc-image/9e00d3cef45f4f7bbccca726a22d8bac)

#14, find the least common multiple of two numbers

x = int(input('please enter a number: '))
y = int(input('please enter another number: '))
bigger = max(x, y)
smaller = min(x, y)
for i in range(1, smaller + 1):
    if bigger * i % smaller == 0:
        print('the least common multiple of %s and %s is %s' % (x, y, bigger * i))
        break
12345678
Copy the code
! [](https://p1-tt-ipv6.byteimg.com/large/pgc-image/4302bd08dbf949d5880fa298fa7d83d7)

#15, generate the Fibonacci sequence

n = int(input('please enter a number: '))
def fib(n):
    if n == 1:
        return [1]
    if n == 2:
        return [1, 1]
    fib = [1, 1]
    for i in range(2, n):
        fib.append(fib[-1] + fib[-2])
    return fib
print(fib(n))
1234567891011
Copy the code
! [](https://p1-tt-ipv6.byteimg.com/large/pgc-image/36358572dbfd4f45a2d3b763c010d9b9)

#16, get maximum and minimum values

numbers = list(map(int, input('please enter the numbers and split with space:').split()))
print('the max number is %s' % (max(numbers)))
print('the min number is %s' % (min(numbers)))
123
Copy the code
! [](https://p1-tt-ipv6.byteimg.com/large/pgc-image/1bb8d8d146f84bfda49656905aa40b84)

#17, judge odd and even

numbers = list(map(int, input('please enter the numbers and split with space:').split()))
for i in range(len(numbers)):
    if numbers[i] % 2 == 0:
        print('%s is an even number.' % numbers[i])
    else:
        print('%s is an odd number.' % numbers[i])
123456
Copy the code
! [](https://p1.pstatp.com/origin/pgc-image/3b728f0e3f3743f185467ac47f7f6812)

#18, compute the square and cube roots of x

x = float(input('please enter a number x = '))
print('x square root is %.5f' % (x ** (1 / 2)))
print('x cube root is %.5f' % (x ** (1 / 3)))
123
Copy the code
! [](https://p26-tt.byteimg.com/large/pgc-image/a7197fc1335c4b2690f8757efb00cf0b)

#19, output 9*9 times table,

for i in range(1, 10):
    for j in range(1, i + 1):
        print('%d * %d = %d' ', ' % (i, j, i * j), end = '')
    print('\n') 
1234
Copy the code
! [](https://p1.pstatp.com/origin/pgc-image/b90eac3738ef4a528b896c236ec65657)

#20, compute the factorial n factorial.

n = int(input('please enter a number: '))
Factorial = n
for i in range(1, n):
    Factorial *= i
print('%s! = %s' % (n, Factorial))
12345
Copy the code
! [](https://p6-tt-ipv6.byteimg.com/large/pgc-image/1115ed1a679a497ca8296cf6d69cb3fb)

#21, calculate a squared +b squared +c squared +…

array = list(map(int, input('please enter the numbers and split with space:').split()))
sum_array = 0
for i in range(len(array)):
    sum_array += array[i] * array[i]
print(sum_array)
12345
Copy the code
! [](https://p26-tt.byteimg.com/large/pgc-image/c73a00ea0d8c4084a295f7087a8f9aeb)

#22, compute x to the n

x = float(input('please enter x = '))
n = int(input('please enter n = '))
print('the %sth power of %.2f is %.2f' % (n, x, x ** n))
123
Copy the code
! [](https://p26-tt.byteimg.com/large/pgc-image/8a74f07fcc914f258ebeac611286b0f8)

#23, change the case of characters in list

list_name = ['Tom', 'Robert', 'Jimmt', 'Lucy', 'Aaron', 'Jack', 'Peter']
print([i.capitalize() for i in list_name])
print([i.upper() for i in list_name])
print([i.lower() for i in list_name])
1234
Copy the code
! [](https://p9-tt-ipv6.byteimg.com/large/pgc-image/dea6a8c2cbb74e938d9c46d3f70abfa7)

#24, the dictionary key and value are swapped to produce a new dictionary

dict_x = {'Jan': '1', 'Feb' : '2', 'Mar' : '3', 'Apr' : '4'}
print(dict_x)
dict_y = {b : a for a, b in dict_x.items()}
print(dict_y)
1234
Copy the code
! [](https://p6-tt-ipv6.byteimg.com/large/pgc-image/10c5cd27fbd04eb8bff50654b50c80f7)

Print each element in the list one at a time

list_name = ['Tom', 'Robert', 'Jimmt', 'Lucy', 'Aaron', 'Jack', 'Peter'] for i in range(len(list_name)): print('%s is getting rich! ' % (list_name[i])) 123Copy the code
! [](https://p1.pstatp.com/origin/pgc-image/d40c38b7ec3c47aeaeea1c5942aa8788)

Print the characters of each element in the list one by one

list_com = ['writing', 'encourage', 'you', 'enroll', 'advantage', 'course']
for i in range(len(list_com)):
    for j in range(len(list_com[i])):
        print(list_com[i][j], end = ' ')
1234
Copy the code
! [](https://p9-tt-ipv6.byteimg.com/large/pgc-image/ec172c4023f74d97bd919b4f9ad82f5b)

#27, merge lists and remove duplicate elements

,7,465,1,9,563,4 list_a = [456867132] list_b =,45,123,1,54,867,8,7 [546465456] print (list_a + list_b) # two lists, Print (list(set list_a + list_b)) print(list(set list_a + list_b)) Sorted (list(set list_a + list_b)))) #Copy the code
! [](https://p6-tt-ipv6.byteimg.com/large/pgc-image/f4d46ec131f24612aea3846116f2b2ae)

#28, randomly generated captcha, can cancel the loop

import random, string
count = 0
while True:
    num_random = '0123456789'
    str_random = string.ascii_letters
    ver_code = random.sample(num_random + str_random, 6)
    ver_code = ''.join(ver_code)
    print(ver_code)
    count += 1
    if count >= 10:
        break
1234567891011
Copy the code
! [](https://p1.pstatp.com/origin/pgc-image/82344d0b97a3493ab3aebe9c2fba7dd7)

#29, bubble sort

List_random =,15,48,9,6,41,8,59,4,498,94,84,96,56,554,56,114,564,45,64 [456] def the BubbleSort () : for i in range(len(list_random) - 1): for j in range(len(list_random) - 1 - i): if list_random[j] > list_random[j + 1]: list_random[j], list_random[j + 1] = list_random[j + 1], list_random[j] return list_random print(BubbleSort()) 12345678Copy the code
! [](https://p6-tt-ipv6.byteimg.com/large/pgc-image/1fb120455ee449a59bfa9c866a021d75)

#30, Turtle draws the five-pointed star

import turtle
turtle.pensize(15)
turtle.pencolor('yellow')
turtle.speed(3)
turtle.fillcolor('red')
turtle.hideturtle()
turtle.begin_fill()
for _ in range(5):
    turtle.forward(200)
    turtle.right(144)
turtle.end_fill()
turtle.penup()
turtle.goto(-20,-180)
turtle.color('violet')
turtle.write('Five-pointed Star', font=('Arial', 25, 'normal'))
turtle.mainloop()
12345678910111213141516
Copy the code
! [](https://p1.pstatp.com/origin/pgc-image/ee0b00d6213b4f9ba00f5dc57029f940)

Very simple little cases! After all, learning needs a sense of achievement

That’s what keeps me going!

PS: If you need Python learning materials, please click on the link below to obtain them

Free Python learning materials and group communication solutions click to join