Buddhist computer level II & the second bomb

Write in front

At the beginning of the next chapter of the question bank, I originally wanted to use a notebook to record, but I think I still have to type more for Python learning, and the handwritten code is still a little bad. Ha ha (mainly because the writing is not good-looking and obsessive-compulsive disorder is very uncomfortable)... Don't say much, open the whole!

Python Round②

Random selection output

import random
brandlst = ['Samsung','Apple','vivo','OPPO','Meizu']
random.seed(0)
name = brandlst[random.randint(0,4)]
print(name)
  • random. Seed (): this in seed (X) represents seed. The computer cannot generate real random numbers, but only pseudo-random numbers. Selecting X can ensure that the seeds planted are the same, that is, the generated random sequence is the same.
  • random.randint(a,b): the output is an integer (including a,b) in the [a,b] interval

Count characters (including punctuation) & number of words

import jieba
txt = input("Please enter a string:")
n = len(txt)
m = len(jieba.lcut(txt))
print("There are a total of characters in this paragraph{0}Number of words, total{1}individual".format(n,m))

len is used to calculate the length of the string
-----ps: it seems that this question is not very rigorous. The stem of the question requires "calculating the number of Chinese words", but use Jieba The list generated by lcut method will include "," but comma does not belong to Chinese words. Chinese characters are directly processed by Len (the whole string)

Purchase decision

n = eval(input("Please enter quantity:"))
value = 150
if n == 1:
    cost = 150
elif (2 <= n and n <=3):
    cost = int(n*150*0.9)
elif (4 <= n and n <= 9):
    cost = int(n * 150 * 0.8)
elif (n >= 10):
    cost = int(n * 150 * 0.7)
print("The total amount is:",cost)
  • input saves the accepted result as a string. This topic uses eval to calculate the expression (can be understood as converting it into a computable number type first?)
  • The title requires an integer (excluding decimal point) to be printed, so an int() should be added

Turtle drawing (five pointed star)

from turtle import*:
for i in range(5):
	fd(200)
	right(144)
  • from turtle import *: imports the entire turtle library. If you use import turtle, you need to declare turtle fd(200), but you can write fd(200) directly in this way
  • The angle of right should be 144. Make the arrow draw an obtuse angle and turn it around

turtle.right() and the previously encountered turtle Seth () is very different. Use range() in conjunction with turtle Right(), directly define the angle to rotate in right; seth() only changes the angle
----For example, triangle drawing in round ①:
Use turtle Seth () should consider that the first rotation angle is 0, the second rotation angle is 120, and the third rotation angle is 240, so use turtle seth(i120)
Use turtle Right() each rotation angle is 240, so turn right(i120)
----ps: fd() also has an impact on graphics before and after. It depends on the examples given by the topic.

Loop out (while)

fo = open("PYP212.txt","w",encoding = "utf-8")
data = input("Please enter the name, gender and age of a group of personnel:")
woman_num = 0
total_num = 0
total_age = 0
while data:
    name,sex,age = data.split(" ")
    if sex == "female":
        woman_num += 1
    total_num += 1
    total_age += int(age)
    data = input("Please enter the name, gender and age of a group of personnel:")
average = total_age/total_num
fo.write("The average age is{:.1f},Female total{}people".format(average,woman_num))
fo.close()

Several key points:

  • while data: through the front and rear data control, ensure the correct format of input, enter the next input accurately when entering, and name the three columns respectively.
    -----The following data cannot be changed to other identifiers because it needs to receive data several more times. This data parameter just corresponds to while data for the next cycle. If it is changed to other parameters, it will jump out directly, which can not achieve the effect of repeatedly receiving data input.
  • {:. 1f}: it means to keep one decimal place. The last sentence can also be changed to: ("average age is {0:.1f}, there are {1} women". format(average,woman_num)) accurately pass the parameters.

Comprehensive practice

Output part of the table

fi = open("PYP123.csv","r")
ls = []
for i in fi:
	ls.append(i.strip("\n").split(","))
s = input("Please enter Holiday Name:")
for i in ls:
	if s == i[1]:
		print("{0}Your vacation is located in{1}and{2}between".format(i[1],i[2],i[3]))
fi.close()

Several key points:

  • Create an empty list to receive Excel data
  • Use commas for split, otherwise it will report out of range errors

Character interception

fi = open("PYP123.csv","r")
ls = []
for i in fi:
	ls.append(i.strip("\n").split(","))
fi.close()
s = input("Please enter the holiday serial number:")
txt = s.split(" ")
for i in ls:
    for a in txt:
        if a == i[0]:
            print("{0}({1})Vacation is{2}month{3}Day arrives{4}month{5}Between days".format(i[1],i[0],i[2][0:2],i[2][2:],i[3][:2],i[3][2:]))
  • There is a small episode in the middle: suddenly, the cursor becomes larger, which is very difficult to operate (I don't know what key to press...) press insert to change back to the original state (in fact, it may be that you accidentally press insert)

Input error

fi = open("PY301-vacations.csv","r")
ls = []
for i in fi:
	ls.append(i.strip("\n").split(","))
fi.close()
s = input("Please enter the holiday serial number:").split(" ")
while True:
    for i in s:
        flag = False
        for a in ls:
            if i == a[0]:
                print("{0}Vacation is{1}month{2}Day arrives{3}month{4}Between days".format(a[1],a[2][:2],a[2][2:],a[3][:2],a[3][2:]))
                flag = True
        if flag == False:
            print("Wrong holiday number entered!")
    s = input("Please enter the holiday serial number:").split(" ")
fi.close()

On the basis of question 2, add a mark. If the input serial number is correct, it will be marked as True, and the input error will be marked as False. Finally, judge whether to output "wrong input holiday number!" according to the mark. It can be seen from the analysis of the requirements of the topic that the mark changes to True when the entered serial number can be found in the two-dimensional list, and it is False in other cases, so the mark should be placed in the for loop of traversing the serial number sequence and outside the for loop of traversing the two-dimensional list.

Probe and report again!

Keywords: Python

Added by Zippyaus on Thu, 24 Feb 2022 17:26:59 +0200