preface
Recently, I went through the basics of Python systematically and learned how to learn it quickly. The normal logic is to practice cases while reading basic knowledge, which is a process of thinning books from thick to thin.
However, nowadays the pace is so fast, especially the Internet companies, excluding the time of staying at home to see the children on weekends, there is almost no time and energy for deep learning, so this article was born.
In this paper, the basic knowledge of Python can be quickly mastered by combining python knowledge directly with cases.
Name of the case
- Calculated circle area
- Input characters and output in reverse order
- Number game
- Output poetry in verse format
- Top 10 Words in statistics text (TXT)
- Web page element extraction
- Text progress bar
Calculated circle area
Print uses the format () function to format the output.
Fixed formula:
print< output string template >.format(< variable1>, < variable2>, < variable3>))Copy the code
Implementation code:
r = 25 # The radius of the circle is 25
area = 3.1415 * r * r # The formula for circles
print(area)
print('{:.2f}'.format(area) ) Print only two decimal places
Copy the code
Novice easy mistakes:
The string template format ‘{:.2f}’ before format is often miswritten, and one {} corresponds to one of the parameters in format.
Input characters and output in reverse order
The idea: Find the last element and print it.
Knowledge:
- Input uses the input function
- Calculate the length using the len () function
- The output function ends with end= “, adding an empty string after the output character
# Input text
s=input('Please enter a text:')
# calculate the length of input and assign to I I =len(s)-1
# reverse loop output
while i>=0:
print(s[i],end=' ')
i=i-1
Copy the code
Effect: The code can be executed
Number game
Generate a random number and judge the input number and the random number until the guess is successful.
Knowledge:
- Use random.randint() to generate a random number
- A while () loop that breaks out of the loop when the condition break is met and continues until the condition is met
- The input numeric eval function converts the string type to an integer in conjunction with the input
- If tripartite conditional judgment, if elif else format
Implementation code:
import random
# Generate random number
a=random.randint(0.1000)
# Count times
count=0
while True:
number=eval(input(Please enter a number between 0 and 1000:))
count=count+1
# compare two numbers
if number>a:
print('Lost big')
elif number<a:
print('Lose small')
else:
print('Got it.')
break
print('Number of guesses:',count)
Copy the code
Renderings: The code can be executed
Output poetry in verse format
Original format:
Life must be happy, don’t make the golden bottle empty to the moon.
Born my material will be useful, daughter dispersed also come back.
Output effect:
Don’t make the golden bottle empty to the moon
I was born with a thousand pieces of material will be dispersed to return
Design idea:
- Replace all punctuation marks with \n
- Text is displayed centered and aligned
Knowledge:
- Replace function line.replace(variable name, value to replace)
- Center align line.center(width)
- Function call, passing the text variable TXT into the replacement function linesplit
txt = Life must be happy, do not make the golden bottle empty to the moon. Born my material will be useful, daughter dispersed also come back. ' ' '
# define a function that replaces punctuation with \n
def linesplit(line) :
plist = [', '.'! '.'? '.', '.'. '.'! '.'? ']
for p in plist:
line=line.replace(p,'\n')
return line.split('\n')
linewidth = 30 Predetermined output width
Define a function that implements center alignment
def lineprint(line) :
global linewidth
print(line.center(linewidth))
# call function
newlines=linesplit(txt)
for newline in newlines:
lineprint(newline)
Copy the code
Count the 10 most frequently used words in a text
Let’s look at the implementation:
Step split:
- First, unify the text content to lowercase, using the lower() function
- Again, the replace() function replaces special characters in the text with Spaces
- Press Spaces to cut the text, using the split () function
- Count the number of occurrences of words
- Sort the sort() function from highest to lowest frequency
- Output in a fixed format, using the format() function
Follow the steps above to implement the code.
First, unify the text content to lowercase, using the lower() function:
def gettxt() :
# read file
txt=open('hamlet.txt'.'r').read()
txt=txt.lower()
Copy the code
Again, the replace() function replaces the special characters in the text with Spaces:
for ch in ' '!"# $% & () *, +, -, / :; The < = >? @ ^ _ '[\] {|} ~' : 'TXT = TXT. Replace ('') return TXTCopy the code
Press space to split the text, using the split () function:
hmlttxt=gettxt()
words=hmlttxt.split()
Copy the code
Count the number of occurrences of words:
counts=0
for word in words:
counts[word]=counts.get(word,0) +1
When word is not in words, the return value is 0; when word is in words, the return value is +1, so as to carry out the cumulative count
Copy the code
Sort items by frequency sort() sort()
items=list(counts.items())
items.sort(key=lambada x:x[1],reverse=True)
Copy the code
The x above can be any letter, reverse=True in reverse order, default ascending order.
To output in fixed format, use the format() function:
for i in range(10)
word,count=item[i]
print('{0: < 10} {1: > 5}'.format(word,count))
Copy the code
Complete code:
First, unify the text content to lowercase, using the lower() function
def gettxt() :
txt=open('hamlet.txt'.'r').read()
txt=txt.lower()
Replace () replaces special characters in text with Spaces
for ch in '!" # $% & * () +, -, / :; The < = >? @ [\] ^ _ '{|} ~':
txt=txt.replace(ch,' ')
return txt
Split the text by space, using the split () function
hamlettxt=gettxt()
words=hamlettxt.split()
# Count words
counts={}
for word in words:
counts[word]=counts.get(word,0) +1
Sort the sort() function from highest to lowest frequency
items=list(counts.items())
items.sort(key=lambda x:x[1],reverse=True)
Output in fixed format, using the format() function
for i in range(10):
word, count=items[i]
print("{0: < 10}, {1: > 5}".format(word,count))
Copy the code
The Web page element extracts the image URL path information
The main purpose of this feature is to replace functions and top-down design ideas.
Effect achieved:The whole function is divided into the following process:
- First, extract all the elements of the page
- Second, extract the URL path of the image
- Then, the path information is output and displayed
- Finally, save these paths to a file
We wrap each of the above steps into a function, and finally call main (), which extracts the url path of the image as the core.
- Extract all elements of the page
It involves knowledge points: file opening, reading and closing.
def gethtmllines(htmlpath) :
# File open
f=open(r,'htmlpath',encoding='utf-8')
Ls =f.readlines()
# file close
f.close()
return ls
Copy the code
- Extract the url path of the image
Source:
Knowledge:
- The captured address is stored in a list
- List split, split() function
def geturl(ls) :
urls=[]
for line in ls:
if 'img' in line:
url=line.split('src=')[-1].split('"') [1]
urls.append(url)
Copy the code
- The path information is displayed
The for loop outputs path information.
forLoop outputs path informationdef show(urls) :
count=0
for url in urls:
print('{:2} url{}'.format(count,url))
count+=1
Copy the code
- Save these paths to a file
Writing files.
def save(filepath,urls) :
f=open(filepate,'w')
for url in urls:
f.write(url+'\n')
f.close()
Copy the code
- The main() function combines the above functions
def main() :
inputfile = 'nationalgeographic.html'
outputfile = 'nationalgeographic-urls.txt'
htmlLines = getHTMLlines(inputfile)
imageUrls = extractImageUrls(htmlLines)
showResults(imageUrls)
saveResults(outputfile, imageUrls)
Copy the code
Final code: Python
# Example_8_1.py
#1. Read everything on the page line by line
def getHTMLlines(htmlpath) :
f = open(htmlpath, "r", encoding='utf-8')
ls = f.readlines()
f.close()
return ls
#2. Extract the HTTP path
def extractImageUrls(htmllist) :
urls = []
for line in htmllist:
if 'img' in line:
url = line.split('src=')[-1].split('"') [1]
print
if 'http' in url:
urls.append(url)
return urls
#3. Output the link address
def showResults(urls) :
count = 0
for url in urls:
print('{:2} URL:{}'.format(count, url))
count += 1
#4. Save the result to a file
def saveResults(filepath, urls) :
f = open(filepath, "w")
for url in urls:
f.write(url+"\n")
f.close()
def main() :
inputfile = 'nationalgeographic.html'
outputfile = 'nationalgeographic-urls.txt'
htmlLines = getHTMLlines(inputfile)
imageUrls = extractImageUrls(htmlLines)
showResults(imageUrls)
saveResults(outputfile, imageUrls)
main()
Copy the code
Summary: this small case can master the file read, write operations, you can experience the idea of the function and split() function split.
Text progress bar
Knowledge:
- Introducing time library
- Print () output format
- For I in range(): loop. At the end of the loop, the format function is used to assign its value to the slot.
Implementation code:
import time
def bar(scale) :
print('=========== Execution start ============')
for i in range(scale + 1):
a = The '*' * i
b = '. ' * (scale - i)
c = (i / scale) * 100
print({: '\ r ^ 3.0 f} % [{} - > {}]'.format(c, a, b), end = ' ')
time.sleep(0.1)
print('\n=========== End ============')
Copy the code
Effect: Output from 0% to 100%
conclusion
The basic functions of Python are described in the following sections:
- The input function implements input
- Print prints the result in combination with the format () function
- Evaluates the string length len() function
- Use random.randint() to generate a random number
- The eval function converts the string type to an integer in conjunction with input
- If tripartite conditional judgment, if elif else format
- Replace function line.replace(variable name, value to replace)
- The text content is all lowercase, using the lower() function
- Replace () replaces special characters in text with Spaces
- The text is sliced, using the split () function
- Sort the sort() function from large to small
Why do software testers choose to learn Python rather than Java
Python syntax is concise and clear, and it has a rich and powerful class library that makes it easy to do a lot of things. For starters, Python is the best language to get started with.
Developing small tools in Python is fast and lightweight. In practice, it is very suitable for teams to develop testing tools quickly when testing resources are not sufficient. And usually implements a function, Python has 1/3 to 1/5 of the code of other languages such as Java. At present, more and more big factory’s new tool development, the technology stack all chooses Python. Therefore, mastering Python automated testing techniques to enter the field of software testing and quality assurance is already the best path for newcomers to the testing industry.
If you want to complete the overall deployment of automated tests in your company, Python can help you do this easily:
- UI Automation Testing (Python+Selenium, etc.)
- Interface tests (Python Requests, etc.)
- Performance testing (Python Locust, etc.)
- Security testing (Python Scapy, etc.)
- Compatibility testing (Python+Selenium, etc.)
Imagine being able to stand up and make money while eating hot pot and singing while others are busy and miserable…
How would you feel in your heart?
How will your boss feel about you?
Collection time
Python Automation test videos, Python automation details, full set of interview questions and other knowledge content. Please click here to help yourself to the group, I hope to help you.
- ✔️ I made a public programmer yifan, do not regularly share learning dry goods
- ✔️ if this article is useful to you, remember to like 👍🏻 plus a concern, every one of your likes I seriously as a like ~
- ✔️ we’ll see you next time! 👋 👋 👋
🌻 Recommended reading:
-
2021 test development of interview questions and answers (including test base | | automation testing interfaces…). , p. 289
-
After the byteDance test job interview failed, I reviewed and summarized the reasons for my failure and decided to try again
-
Ali first internal test development learning manual (complete version), open download! It smells so good
-
Good foundation? Here are 43 easy to forget Linux operations at work.