current position:Home>Advanced Python Programming - functions and modules
Advanced Python Programming - functions and modules
2022-06-24 06:40:44【Sixiaoyou】
Catalog
1.randint Left and right are closed intervals
import random
test = random.randint(1,3)
print(test)
# and Priority ratio or high
2. Empty function pass The practical effect
# effect : When writing down the logic of a function , Don't let you make mistakes
# A process Sign in Place an order payment
def login():
pass
def order():
print(' Place an order ')
3. function Parameters How to write it
# Positional arguments , Key parameters , Default parameters , Indefinite length parameter
# Positional arguments : Order of arguments , The number should correspond to the formal parameter
# Positional arguments
def sum(a,b):
return a + b
z = sum(55,66)
print(z)
def person(name,age):
return ' I am a %s, Age %s'%(name,age)
p = person(' autumn waters ',18)
print(p)
# Key parameters , Define formal parameters first , Arguments can be in different order , But the argument needs to be preceded by the parameter name
def person(name,age):
return ' I am a %s, Age %s' % (name, age)
d = person(age = 18,name=' False bamboo ')
print(d)
# Default parameters Give the form an actual data , After adding the data , Arguments don't have to be given data . Arguments give data , The actual parameter data shall prevail
def person(name,age=18):
return ' I am a %s, Age %s' %(name, age)
p = person(' autumn waters ',88)
print(p)
# There are default parameters in a function , There are also position parameters What do I do
# Location and default parameters exist at the same time , The position parameter must precede the default parameter
def person(name,age,sex=' Woman '):
return ' I am a %s, Age %s, Gender %s' %(name,age,sex)
p = person(' autumn waters ',88)
print(p)
# I'm not sure
# I don't know how many parameters there are , Add a before the parameter * perhaps **
# Add one more *, Send in the value , Put in tuple
# Add two. ** Send in the value , Put it in the dictionary
# * Can pass multiple values , The following formal parameter name , You can take any name , It is not recommended to change the name
def person(*args):
print(args)
person(' millet ',' Huawei ',' meizu ')
# Add two. ** Send in the value , Put it in the dictionary
#* Can pass multiple values , The following formal parameter name , You can take any name , It is not recommended to change the name kwargs
def person(**kwargs):
print(kwargs)
person(name=' autumn waters ',age='18',sex=' Woman ')
# There is also a function *, Also exist **
# *args Put it in **kwargs front
def person(*args,**kwargs):
print(args)
print(kwargs)
person(' millet ',' Huawei ',' meizu ','a',1,name=' autumn waters ',age='18',sex=' Woman ')
#* Multiple values can be received , The accepted value exists in the tuple
#** Multiple values can be received , The accepted value is stored in the dictionary
4. Unpack pom
username=('id','kw')
pwssword=('name','su')
# driver.find.element_by_id('su')
def loctor(loc):
driver.find.element(*loc)
# * Can unpack tuples
def person(loc):
print(loc)
print(*loc)
person(('id','kw'))
# loc Is it acceptable ('id','kw') A tuple , A data
# A data , Unpack and uncover , Disintegrate into 2 Data
# ** Can unpack the dictionary Why not just print(**loc) print function
def person(loc):
print(**loc)
person({
'name':' autumn waters ','age':'18'})
# loc It is equivalent to receiving {'name':' autumn waters ','age':'18'}
# print **loc name=' autumn waters ',age=18
# print It's a function
def print(self, *args, sep=' ', end='\n', file=None):
print('aaa')
print(name=' autumn waters ',age='18')
5. Anonymous functions :lambda expression
# lambda The subject of is an expression , Not a code block
# grammar : lambda Parameters , Parameters : expression , logic function
# Arguments before colon
# Anonymous functions do not need to return , The result itself is the return value
# Sum up Use common
def sum(a,b):
c = a+b
return c
z = sum(2,6)
print(z)
num = lambda a,b:a+b
print(num(2,6))
# Anonymous functions only perform basic simple functions
# Common functions are complex
# automation According to wait Elements of the page Some elements
driver = webdriver.Chrome()
WebDriverWait(driver,10).until(lambda x:x.driver.find_element_by_id("kw"))
loc = lambda driver:driver.driver.find_element_by_id("kw")
def loc(driver):
a = driver.find_element_by_id("kw")
return a
loc(driver)
# Use
c = lambda :True
print(c())
def c():
return True
c()
6. The derived type Data can be cycled
# Deductive grammar : [ expression for xx in range()]
# establish 1-100 A list of integers of
list1 = [i for i in range(101)]
print(list1)
for i in range(101):
# print(i+1)
list1.append(i)
print(list1)
list1 = [i+1 for i in range(101)]
print(list1)
# Create a dictionary : {key:value for i in range()}
dict1 = {
}
for i in range(0,6):
print(i)
dict1[i] = i*5
print(dict1)
# Derivation to create a dictionary
dict1 = {
i:i*5 for i in range(0,6)}
print(dict1)
# Dictionary assignment : dict1={0:0,1:5,2:10} There are no duplicate keys add value
# dict['name'] = 'xiaomin'
# dict={'name': 'xiaomin'}
# Nested dictionaries in the list [{key:value} for i in range()]
list1 =[ {
i:i*5} for i in range(0,6)]
print(list1)
# Homework after class : With normal for How to express a cycle
list1 = []
for i in range(0,6):
dict1 = {
}
dict1[i] = i*5
list1.append(dict1)
print(list1)
7.if The ternary operation of a statement if Abbreviation
# Format :result1 if Judge else result2
# if Conditions :
# Things that meet the conditions
# else:
# Things that do not meet the conditions
# Two numbers judge If the number 1 Greater than number 2 Print digit 1 Big Otherwise print the numbers 2 Big
x = 1
y = 2
if x > y:
print(' Numbers 1 Big ')
else:
print(' Numbers 2 Big ')
print(' Numbers 1 Big ') if x>y else print(' Numbers 2 Big ')
copyright notice
author[Sixiaoyou],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/175/202206240013353303.html
The sidebar is recommended
- Python simulates keyboard input and mouse operation
- Python get windows special folder path code
- Python segmented download file
- Python setting environment variables for processes
- Python uses multithreading to execute CMD command to shut down
- Python gets the number of days in the previous month
- Python generates 128 barcode (code128)
- [Python] code sharing for drawing 2D scatter diagram
- [Python] output the names of students with the highest or lowest scores and students with lower than average scores
- [Python] implement the maximum and minimum distance algorithm
guess what you like
Python parsing JSON data tutorial
Deep learning project: how to use Python and opencv for face recognition
Pychart developing Django project template common filter tutorial
Using Python to call cloud API to monitor the traffic usage of lightweight application servers
Face core app access - server Python demo
Can Python's "King" status be maintained in the next decade?
How do Python crawlers make money? Six Python crawlers make money. It's not a problem to engage in sidelines
Java or python, which is more suitable for AI development?
How to make beeps in Python for windows ECS
Three sorts (select, bubble, insert) Python version
Random recommended
- Python automatic switching environment
- Detailed explanation of python3 rounding problem
- [Master Wu's Python bakery] day 2
- [Master Wu's Python bakery] day 1
- [Master Wu's Python bakery] day 3
- [Master Wu's Python bakery] day 4
- [Master Wu's Python bakery] day 5
- [Master Wu's Python bakery] day 6
- [Master Wu's Python bakery] day 7
- [Master Wu's Python bakery] day 8
- Introduction and examples of socket programming in Python
- Python notes - permissionerror
- Python notes - deprecationwarning
- Python notes - Open Python project
- Python notes - PIL Library
- Python notes - with as statement
- How to export IPython history to Py file?
- Python multithreading combined with dataloader to load data
- Make Python not echo commands that get password input
- In c/c++ and python programming, null and none cannot be distinguished clearly
- Writing sample code for functions in Python
- Summary of operation methods of Python set (about 20 operation methods), with sample code attached
- Python -- functions
- Anonymous and recursive functions in Python
- How to query the methods (member functions) of a class or an object in Python [using the function dir()]
- Summary of operation methods of Python Dictionary (dict) (about 18 operation methods), with sample code attached
- Collect hot search lists in Python at work, which can be called a fishing artifact
- Running Django and Vue on docker
- Data classification in pandas
- About Python: docxtpl is embedded by default when inserting pictures
- How to solve the problem of CSV? (Language Python)
- Installation and use of redis (Python)
- Python implements sending mail (implements single / group mail verification code)
- On the built-in object type of Python -- number (one of the differences between py2 and PY3)
- Python God uses a problem to help you solve the problems of formal and actual parameters in Python functions
- "Project Euler Python Mini tutorial" 001-010 solution introduction
- Most beginners learn Python and web automation. In this way, they learn and give up
- Python matrices and numpy arrays
- Exciting challenge: Python crawler crawls the cover picture of station B
- After installing python3, use the yum command to report an error?