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