current position:Home>Quick start - Python Basics

Quick start - Python Basics

2022-02-02 06:12:14 User 4648189936722

After reading this article , But for Python Linguistic characteristics 、 Have a certain understanding of coding style , And can write simple Python Program .

One 、 Installation and operation

Of each system Python Please refer to the installation tutorial by yourself , No more details here .

Check Python edition , Enter at the command line python that will do , At the same time, it will enter the command line interaction mode , You can perform... Here python command .

If... Is installed in the computer python2.x and python3.x Two versions , Input python Running 2.x edition . Want to run 3.x, You need to enter python3.

Enter at the command line python

Solo-mac:~ solo$ python
Python 2.7.10 (default, Aug 17 2018, 19:45:58)
[GCC 4.2.1 Compatible Apple LLVM 10.0.0 (clang-1000.0.42)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

 Copy code 

Enter at the command line python3

Solo-mac:~ solo$ python3
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 26 2018, 23:26:24)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>

 Copy code 

Input exit() You can exit command line mode .

Command line run python file

If you have written a python file , Want to run it from the command line , Enter this directory , Enter at the command line python file name .py that will do .

For example, there is a file on the desktop hello.py, The content is to print a sentence :

print("Hello, Python")

 Copy code 

Want to run it , Enter the first Desktop Catalog , Then enter... On the command line python hello.py You can run :

Solo-mac:Desktop solo$ python hello.py
Hello, Python

 Copy code 

Two 、 Variables and simple data types

2.1 Variable naming rule

  • Variable names can only contain letters 、 Numbers and underscores . Variable names can start with letters or underscores , But you can't type it in numbers head , for example , You can name the variable message_1, But it can't be named 1_message.
  • Variable names cannot contain spaces , But you can use an underline to separate the words . for example , Variable name greeting_message feasible , But the variable name greeting message Error will be raised .
  • Don't put Python Keywords and function names are used as variable names , Do not use Python Keep words for special purposes , Such as print.
  • Variable names should be short and descriptive . for example ,name Than n good ,student_name Than s_n good ,name_length Than length_of_persons_name good .
  • Be careful with lowercase letters l And capital letters O, Because they can be mistaken for numbers 1 and 0.

Variable names should be lowercase , Although there is no mandatory provision , But the rules commonly known as agreement .

2.2 character string

A string is a series of characters . stay Python in , It's all strings in quotation marks , The quotation marks can be single quotation marks , Or double quotes , It can also be used at the same time . Such as :

"This is a string." 
'This is also a string.'
"I love 'python'"

 Copy code 

2.2.1 Simple operation of string

The following describes the simple operation of string .

title()

title() Show each word in uppercase , Change the initial of each word to uppercase .

>>> name = 'solo coder'
>>> name.title()
'Solo Coder'

 Copy code 
upper()、lower()

Change the string to all uppercase or all lowercase .

>>> name
'solo coder'
>>> name.upper()
'SOLO CODER'
>>> name.lower()
'solo coder'
>>> name
'solo coder'

 Copy code 

Be careful :title()、upper()、lower() Does not change the original string , Just output a new string .

2.2.2 Merge ( Splicing ) character string

Python Use the plus sign (+) To merge strings .

>>> first = 'solo'
>>> last = 'coder'
>>> full = first + ' ' + last
>>> full
'solo coder'

 Copy code 

2.2.3 Use tabs or line breaks to add white space

In programming , White space refers to any nonprinting character , Such as space 、 Tabs and line breaks .

To add tabs to a string , Character combinations can be used \t, To add a newline character to a string , Character combinations can be used \n .

>>> print('\tPython')
	Python
>>> print('Hello,\nPython')
Hello,
Python

 Copy code 

2.2.4 Delete blanks

rstrip() Remove right margin ,lstrip() Delete the left margin ,strip() Delete the blanks at both ends .

>>> msg = ' Python '
>>> msg
' Python '
>>> msg.rstrip()
' Python'
>>> msg.lstrip()
'Python '
>>> msg.strip()
'Python'
>>> msg
' Python '

 Copy code 

Note that after executing the space removal command , And print it out msg, Or the original string , This explanation strip() It doesn't change the original string .

2.2.5 Python 2 Medium print sentence

stay Python 2 in ,print The syntax of the statement is slightly different :

>>> python2.7
>>> print "Hello Python 2.7 world!" 
Hello Python 2.7 world!

 Copy code 

stay Python 2 in , There is no need to put the content to be printed in parentheses . Technically speaking ,Python 3 Medium print It's a function , So brackets are essential . There are some Python 2 print Statements also contain parentheses , But its behavior is related to Python 3 Slightly different . In short , stay Python 2 In the code , There are some print Statement contains parentheses , Some do not contain .

2.3 Numbers

2.3.1 Integers

stay Python in , You can add integers (+) reduce (-) ride (*) except (/) operation .

>>> 2 + 3 
5
>>> 3 - 2 
1
>>> 2 * 3 
6
>>> 3 / 2 
1.5

 Copy code 

Python It also supports the order of operations , So you can use multiple operations in the same expression . You can also use parentheses to fix Change the operation order , Give Way Python Perform operations in the order you specify , As shown below :

>>> 2 + 3*4
14
>>> (2 + 3) * 4 20

 Copy code 

2.3.2 Floating point numbers

Python All numbers with decimal points are called floating point numbers . Most programming languages use this term , It points out the fact that : The decimal point can appear anywhere in the number .

To a large extent , When you use floating-point numbers, you don't have to think about their behavior . You just type in the numbers you want to use ,Python They are usually handled the way you want them to be :

>>> 0.1 + 0.1
0.2
>>> 0.2 + 0.2 9 0.4
>>>2 * 0.1
0.2
>>>2 * 0.2
0.4

 Copy code 

But it should be noted that , The number of decimal places contained in the result may be uncertain :

>>> 0.2 + 0.1 
0.30000000000000004 
>>> 3 * 0.1 
0.30000000000000004

 Copy code 

All languages have this problem , There is nothing to worry about .Python Will try to find a way , To represent the results as accurately as possible , But because of the way numbers are represented inside computers , It's hard in some cases . We'll learn more about how to deal with it later .

2.3.3 Using functions str() Avoid typos

If you splice numbers with strings , There will be a type error . To avoid this problem , have access to str() Convert a number to a string and then operate .

>>> age = 18
>>> print('my age is ' + age)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
>>> print('my age is ' + str(age))
my age is 18

 Copy code 

2.3.4 Python 2 The integer

stay Python 2 in , Dividing two integers gives slightly different results :

>>> python2.7 
>>> 3 / 2
1

 Copy code 

Python The result returned is 1, instead of 1.5. stay Python 2 in , The result of integer division contains only the integer part , The decimal part Points deleted . Please note that , When calculating integer results , The approach taken is not to round , Instead, delete the decimal part directly .

stay Python 2 in , To avoid this , Make sure that at least one of the operands is a floating-point number , The result will also be Floating point numbers :

>>> 3 / 2
1
>>> 3.0 / 2
1.5
>>> 3 / 2.0 
1.5
>>> 3.0 / 2.0 
1.5

 Copy code 

from Python 3 Switch to Python 2 Or from Python 2 Switch to Python 3 when , This division behavior is often confusing . When using or writing code that uses both floating-point numbers and integers , We must pay attention to this abnormal behavior .

2.3.5 notes

stay Python in , Pound mark for annotation (#) identification . The contents after the well number will be changed Python The interpreter ignores . Such as

#  Say hello to everyone 
print("Hello Python people!")

 Copy code 

3、 ... and 、 list

A list consists of a series of elements arranged in a specific order .

stay Python in , In square brackets ([]) To represent a list , And use commas to separate the elements .

>>> list = []
>>> list.append('haha')
>>> list.append('heihei')
>>> list.append('hehe')
>>> list
['haha', 'heihei', 'hehe']
>>> list[0]
'haha'

 Copy code 

To get the last element, you can use -1, Such as list[-1] Is to get the last element ,list[-2] Is to get the penultimate element .

3.1 Add, delete, modify and search the list

3.1.1 Modifying elements

Modify the element directly with the index

>>> list[0] = 'nihao'
>>> list
['nihao', 'heihei', 'hehe']

 Copy code 

3.1.2 Additive elements

You can add... At the end , You can also insert... Anywhere .

Add... At the end :append

>>> list.append('wa')
>>> list
['nihao', 'heihei', 'hehe', 'wa']

 Copy code 

Insert :insert

>>> list.insert(1, 'hello')
>>> list
['nihao', 'hello', 'heihei', 'hehe', 'wa']

 Copy code 

3.1.3 Remove elements

There are three ways to delete :

  • del: Delete by index
  • pop(): Delete the last element of the list and return the value of the last element . You can also transfer the index to delete the value at any position .
  • remove(): Delete... By value
>>> list
['nihao', 'hello', 'heihei', 'hehe', 'wa']
>>> del list[1]
>>> list
['nihao', 'heihei', 'hehe', 'wa']
>>> list.pop()
'wa'
>>> list.remove('hehe')
>>> list
['nihao', 'heihei']

 Copy code 

to pop() Pass the index to delete values in other locations

>>> list
['nihao', 'heihei']
>>> list.pop(0)
'nihao'
>>> list
['heihei']

 Copy code 

Be careful :

Method remove() Delete only the first specified value . If the value to be deleted may appear more than once in the list , You need to use a loop to determine if all of these values have been deleted .

If you're not sure you should use del Statement or pop() Method , Here's a simple criterion : If you want to remove an element from the list , And no longer use it in any way , Just use del sentence ; If you're going to be able to use it after deleting the element , Just use the method pop().

3.2 Organization list

This section describes the sorting of lists 、 reverse 、 Calculate the length and other operations .

There are two main ways to sort lists :

  • Usage method sort() Sort the list permanently
  • Using functions sorted() Sort the list temporarily

3.2.1 Usage method sort() Sort the list permanently

Use sort() Method will change the original list . If you want to reverse the sort , Just to sort() Method pass parameter reverse=True.

>>> list
['zhangsan', 'lisi', 'bob', 'alex']
>>> list.sort()
>>> list
['alex', 'bob', 'lisi', 'zhangsan']
>>> list.sort(reverse=True)
>>> list
['zhangsan', 'lisi', 'bob', 'alex']

 Copy code 

3.2.2 Using functions sorted() Sort the list temporarily

function sorted() Allows you to display list elements in a specific order , It doesn't affect their original order in the list .

If you want to reverse the sort , Just to sorted() Pass parameters reverse=True.

>>> list = ['douglas','alex','solo','super']
>>> sorted(list)
['alex', 'douglas', 'solo', 'super']
>>> list
['douglas', 'alex', 'solo', 'super']
>>> sorted(list, reverse=True)
['super', 'solo', 'douglas', 'alex']
>>> list
['douglas', 'alex', 'solo', 'super']

 Copy code 

3.2.3 Reverse list

To reverse the order of the list elements , Serviceable method reverse(). reverse() The original list will also be changed .

reverse() It will only reverse the original order , No additional alphabetical sorting .

>>> list
['douglas', 'alex', 'solo', 'super']
>>> list.reverse()
>>> list
['super', 'solo', 'alex', 'douglas']

 Copy code 

3.2.4 Determine the length of the list

Using functions len() You can quickly learn the length of the list .

>>> list
['super', 'solo', 'alex', 'douglas']
>>> len(list)
4

 Copy code 

3.3 Operation list

3.3.1 loop

Use for…in loop .

python Indent to distinguish code blocks , So you need to indent correctly

>>> cats
['super', 'solo', 'alex', 'douglas']
>>> for cat in cats:
...     print(cat)
...
super
solo
alex
douglas

 Copy code 

3.3.2 range()

Python function range() It allows you to easily generate a series of numbers .

>>> for value in range(1,5):
...     print(value)
...
1
2
3
4

 Copy code 

Be careful :range() A series of values containing the first parameter but not the second parameter will be generated .

Use range() Create a list of

>>> numbers = list(range(1,6))
>>> numbers
[1, 2, 3, 4, 5]

 Copy code 

range() You can also specify steps . The following example generated from 0 Start , To 11 An even number of :

>>> nums = list(range(0,11,2))
>>> nums
[0, 2, 4, 6, 8, 10]

 Copy code 

3.3.3 Simple calculation of the list

There are several dedicated to dealing with lists of numbers Python function .

  • min(): Calculate the minimum
  • max(): Calculate the maximum
  • sum(): Calculate the sum
>>> numbers
[1, 2, 3, 4, 5]
>>> min(numbers)
1
>>> max(numbers)
5
>>> sum(numbers)
15

 Copy code 

3.3.4 List of analytical

List parsing will for The loop and the code that creates the new element merge into a single line , And automatically attach new elements .

>>> squares = [value**2 for value in range(1,11)]
>>> squares
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

 Copy code 

To use this grammar , First, a descriptive list , Such as squares; then , Specify an open bracket , And define an expression , Used to generate the values you want to store in the list . In this example , Expression for value ** 2, It means Calculate the square value . Next , Write a for loop , Used to provide a value to an expression , Add the right square bracket . In this example , for The cycle is for value in range(1,11), It will be worth 1~10 To the expression value ** 2. Please note that , there for There is no colon at the end of the statement .

3.4 section

To create slices , You can specify the index of the first and last element to be used . And functions range() equally ,Python Stop after reaching the element before the second index you specify . To output the first three elements in the list , Need to specify index 0~3, This will output 0、1 and 2 The elements of .

>>> names = ['aa','bb','cc','dd']
>>> print(names[1:4])
['bb', 'cc', 'dd']

 Copy code 

If you don't specify the first index ,Python Will automatically start at the beginning of the list :

>>> print(names[:4])
['aa', 'bb', 'cc', 'dd']

 Copy code 

If no termination index is specified , Automatically get to the end of the list

>>> print(names[2:])
['cc', 'dd']

 Copy code 

You can also use negative index , For example, return the last three elements

>>> print(names[-3:])
['bb', 'cc', 'dd']

 Copy code 

Traversing slices

>>> for name in names[1:3]:
...     print(name)
...
bb
cc

 Copy code 

3.5 Copy list

You can use slices to quickly copy lists , Do not specify start index and end index .

>>> names
['aa', 'bb', 'cc', 'dd']
>>> names2 = names[:]
>>> names2
['aa', 'bb', 'cc', 'dd']

 Copy code 

A new list copied out of slices , It's a completely different list from the original list , Changing one doesn't actually affect the other list .

>>> names.append('ee')
>>> names
['aa', 'bb', 'cc', 'dd', 'ee']
>>> names2
['aa', 'bb', 'cc', 'dd']

 Copy code 

And if you simply assign a value, it will names Assign a value to names2, You can't get two lists , In fact, they all point to the same list . If you change one of them , The other will also be changed .

>>> names
['aa', 'bb', 'cc', 'dd']
>>> names2 = names
>>> names2
['aa', 'bb', 'cc', 'dd']
>>> names.append('ee')
>>> names
['aa', 'bb', 'cc', 'dd', 'ee']
>>> names2
['aa', 'bb', 'cc', 'dd', 'ee']

 Copy code 

3.6 Tuples

Python A value that cannot be modified is called immutable , And immutable lists are called tuples .

Tuples look like lists , But use parentheses instead of square brackets to identify . After defining tuples , You can use the index to access its elements , It's like accessing list elements .

>>> food = ('apple', 'orange')
>>> food[0]
'apple'
>>> food[1]
'orange'
>>> food[1] = 'banana'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'tuple' object does not support item assignment

 Copy code 

The traversal usage is consistent with the list .

Four 、 conditional

Every one of them if The core of the statement is a value of True or False The expression of , This expression is called a conditional test .

  • Check for equality , use ==

  • Check if it's not equal , use !=

  • Number comparison ><>=<=

  • Multiple conditions and and

  • Multiple conditions or or

  • Determine whether the list contains an element in

    >>> names
    ['aa', 'bb', 'cc', 'dd', 'ee']
    >>> 'bb' in names
    True
    
     Copy code 
  • Determine whether the list does not contain an element

    >>> names
    ['aa', 'bb', 'cc', 'dd', 'ee']
    >>> 'ff' not in names
    True
    
     Copy code 

if sentence

ordinary if-else

>>> a = 10
>>> if a > 10:
...     print('hello')
... else:
...     print('bye')
...
bye

 Copy code 

if-elif-else

>>> if a<5:
...     print(a<5)
... elif 5<a<10:
...     print('5<a<10')
... else:
...     print('a>10')
...
a>10

 Copy code 

5、 ... and 、 Dictionaries

stay Python in , A dictionary is a series of keys - It's worth it . Each key is associated with a value , You can use the key to access the value associated with it . The value associated with the key can be a number 、 character string 、 Lists and even dictionaries . in fact , Any Python Object is used as a value in the dictionary .

5.1 Look up the dictionary

Using dictionaries

stay Python in , The dictionary is in curly brackets {} A series of keys in - Value pairs indicate .

>>> user = {'name':'bob', 'sex':'male', 'age':20}
>>> user
{'name': 'bob', 'sex': 'male', 'age': 20}

 Copy code 

Access the values in the dictionary

To get the value associated with the key , You can specify the dictionary name and the key in brackets .

>>> user
{'name': 'bob', 'sex': 'male', 'age': 20}
>>> user['name']
'bob'
>>> user['age']
20

 Copy code 

Add key value pair

A dictionary is a dynamic structure , You can add keys to it at any time — It's worth it .

>>> user['city']='beijing'
>>> user
{'name': 'bob', 'sex': 'male', 'age': 20, 'city': 'beijing'}

 Copy code 

Change the value in the dictionary

To change the value in the dictionary , You can specify the dictionary name in turn 、 The key enclosed in square brackets and the new value associated with that key .

>>> cat = {}
>>> cat['color'] = 'white'
>>> cat['age'] = 4
>>> cat
{'color': 'white', 'age': 4}
>>> cat['age'] = 6
>>> cat
{'color': 'white', 'age': 6}

 Copy code 

Delete key value pair

For information no longer needed in the dictionary , You can use del Statement will correspond to the key — Delete value pairs completely . Use del When the sentence is , You must specify the dictionary name and the key to delete .

>>> del cat['color']
>>> cat
{'age': 6}

 Copy code 

5.2 Ergodic dictionary

Dictionaries can be used to store information in various ways , So there are many ways to traverse the dictionary : It can traverse all the keys in the dictionary — It's worth it 、 Key or value .

Traverse all key value pairs items()

>>> cat
{'age': 6, 'color': 'white', 'city': 'beijing'}
>>> for k,v in cat.items():
...     print(k + '-' + str(v))
...
age-6
color-white
city-beijing

 Copy code 

adopt for k,v in cat.items() Traverse all key value pairs in the same way ,k Representative Key ,v Representative value .

Be careful : Even when traversing the dictionary , key — The return order of value pairs is also different from the storage order .Python Don't care about keys — The order in which value pairs are stored , It only tracks the relationship between the key and the value .

Traverse all keys keys()

If you don't need a value , It can be used keys() Traverse all the keys .

>>> cat
{'age': 6, 'color': 'white', 'city': 'beijing'}
>>> for k in cat.keys():
...     print(k.title())
...
Age
Color
City

 Copy code 

The above example is printed out cat All keys for , With string title() Method to capitalize the first letter of each word .

When traversing the dictionary, all keys will be traversed by default ,for k in cat.keys() and for k in cat The effect is the same .

Traverse all keys in order , You can use sorted() Sort , This makes Python List all the keys in the dictionary , And sort the list before traversing .

>>> for k in sorted(cat.keys()):
...     print(k.title())
...
Age
City
Color

 Copy code 

Traverse all values values()

>>> for value in cat.values():
...     print(str(value))
...
6
white
beijing

 Copy code 

Eliminate duplicates if necessary , have access to set()

>>> cat
{'age': 6, 'color': 'white', 'city': 'beijing', 'city2': 'beijing'}
>>> for value in cat.values():
...     print(str(value))
...
6
white
beijing
beijing
>>> for value in set(cat.values()):
...     print(str(value))
...
beijing
white
6

 Copy code 

5.3 nesting

You can nest dictionaries in a list 、 Nesting lists in dictionaries and nesting dictionaries in dictionaries . I'm not going to do that here .

6、 ... and 、 User input and while loop

6.1 User input

function input() Pause the program , Wait for the user to enter some text . After getting user input ,Python Store it in a variable , For your convenience .

>>> msg = input('Please input your name: ')
Please input your name: solo
>>> msg
'solo'

 Copy code 

If you're using Python 2.7, The function... Should be used raw_input() To prompt the user for input . This function is associated with Python 3 Medium input() equally , Also interpret the input as a string .

Python 2.7 Also contains functions input(), But it interprets user input as Python Code , And try to run them . If you're using Python 2.7, Please use raw_input() instead of input() To get input .

If you want to convert the input into numbers , It can be used int() To convert .

6.2 while loop

for The loop is used to create a code block for each element in the collection , and while The cycle goes on and on , Until the specified conditions are not met .

>>> num = 1
>>> while num <= 5:
...     print(str(num))
...     num += 1
...
1
2
3
4
5

 Copy code 

break

To quit immediately while loop , No longer run the rest of the code in the loop , And regardless of the results of the conditional tests , You can use break sentence .break Statement is used to control the program flow , You can use it to control which lines of code execute , Which lines of code are not executed , This allows the program to execute the code you want to execute according to your requirements .

continue

To return to the beginning of the loop , And according to the result of condition test, decide whether to continue to execute the loop , You can use continue sentence , It is not like break Statement to stop executing the rest of the code and exit the loop .

7、 ... and 、 function

Python With keywords def To define a function , The function name is given with a colon : ending , The contents of the indent after the colon are the function body .

>>> def greet():
...     print('Hello World!')
...
>>> greet()
Hello World!

 Copy code 

7.1 Function parameter

You can pass arguments to a function . The following example is a directional function greet() Passed an argument name. among name It's a parameter ,solo Is the argument .

>>> def greet(name):
...     print('Hello,' + name)
...
>>> greet('solo')
Hello,solo

 Copy code 

There are many ways to pass arguments to functions , You can use positional arguments , This requires the order of arguments to be the same as the order of formal parameters ; You can also use keyword arguments , Its Each argument in the consists of a variable name and a value ; You can also use lists and dictionaries .

Location parameter

When you call a function ,Python Each argument in a function call must be associated with a parameter in the function definition . So , The simplest way to relate is based on the order of arguments . This association is called positional argument .

>>> def student(name, age):
...     print('Hello, My name is ' + name + ', I am ' + str(age) + ' years old')
...
>>> student('solo', 18)
Hello, My name is solo, I am 18 years old

 Copy code 

Arguments passed in the order defined by formal parameters are called positional arguments .

Keyword arguments

The keyword argument is the name passed to the function — It's worth it . Keyword arguments allow you to ignore the order of arguments in a function call , It also clearly points out the purpose of each value in the function call .

>>> student(age=18, name='solo')
Hello, My name is solo, I am 18 years old

 Copy code 

Next, the example in the location argument ,student(name, age) The first parameter of the method is name, The second parameter is age . We use keyword arguments to indicate which one is passed , Even if the order is written out of order, the result will not be out of order .

The default value is

When you write a function , You can specify a default value for each parameter . When an argument is provided to a formal parameter in the calling function ,Python The specified argument value will be used ; otherwise , The default value of the formal parameter will be used . therefore , After a parameter is assigned a default value , You can omit the corresponding arguments in the function call . Use default values to simplify function calls , The typical usage of functions can also be clearly pointed out .

>>> def student(name, age=18):
...     print('Hello, My name is ' + name + ', I am ' + str(age) + ' years old')
...
>>> student('bob')
Hello, My name is bob, I am 18 years old
>>> student('nicole')
Hello, My name is nicole, I am 18 years old
>>> student('bob', 20)
Hello, My name is bob, I am 20 years old

 Copy code 

Above , to student() The second parameter of the function definition age Set the default value 18, If only one parameter is passed when calling , Whatever it is age All are 18. When passing two parameters , The arguments passed will override the default value .

Be careful : When using default values , In the formal parameter list, the formal parameter without default value must be listed first , Then list the arguments with default values . This makes Python Still able to correctly interpret location arguments .

7.2 Return value

Functions do not always display output directly , contrary , It can process some data , And return one or a set of values . The function returns The value of is called the return value . In the function , You can use return Statement to return the value to the line of code that called the function . The return value allows you to move most of the heavy work of the program into functions , So as to simplify the main program .

>>> def student(name):
...     return name
...
>>> name = student('solo')
>>> name
'solo'

 Copy code 

Return dictionary

Function can return any type of value , Including more complex data structures such as lists and dictionaries . for example , The following function accepts name and age , And return a dictionary of people :

>>> def build_person(name,age):
...     person = {'name':name, 'age':age}
...     return person
...
>>> p = build_person('solo',18)
>>> p
{'name': 'solo', 'age': 18}

 Copy code 

7.3 Pass any number of arguments

occasionally , You don't know in advance how many arguments a function needs to take , Fortunately Python Allows functions to collect any number of arguments from the calling statement .

>>> def person(*args):
...     print(args)
...
>>> person('name','age','address')
('name', 'age', 'address')

 Copy code 

A function is defined above person() , There is only one parameter *args . The name of the parameter *args The asterisk in makes Python Create a file called args Empty tuples of , And encapsulates all the values received in the tuple .

Use a combination of positional arguments and any number of arguments

If you want a function to accept different types of arguments , Formal parameters that accept any number of arguments must be placed last in the function definition .Python First match location arguments and keyword arguments , Then collect the remaining arguments into the last parameter .

>>> def person(city, *args):
...     print('city: ' + city + ', other args:')
...     for value in args:
...             print(value)
...
>>> person('beijing', 'name', 'age', 'tel')
city: beijing, other args:
name
age
tel

 Copy code 

function person() There are two parameters , first city Is an ordinary positional argument , the second *args It's a variable parameter .

Use any number of keyword arguments

occasionally , You need to accept any number of arguments , But I don't know in advance what information will be passed to the function . under these circumstances , Functions can be written to accept any number of keys — It's worth it —— Accept as much as the call statement provides . One such example is to create a user profile : You know you will receive information about users , But I'm not sure what kind of information it will be .

def build_profile(first, last, **user_info):
	profile = {}
	profile['first_name'] = first
	profile['last_name'] = last

	for key,value in user_info.items():
		profile[key] = value

	return profile

user = build_profile('steven', 'bob', city='beijing', age=18)

print(user)

 Copy code 

Execute code , The output is :

{'first_name': 'steven', 'last_name': 'bob', 'city': 'beijing', 'age': 18}

 Copy code 

7.4 Import and export

Functions can be stored in a separate file called a module , Then import the module into the main program .import Statement allows the code in the module to be used in the currently running program file .

7.4.1 Import the entire module

The module has the extension .py The file of , Contains the code to be imported into the program .

cat.py

def eat(food):
    print('I am cat, I eat ' + food)

 Copy code 

animal.py

import cat

cat.eat('fish')

 Copy code 

Console output

I am cat, I eat fish

 Copy code 

7.4.2 Import specific functions

You can also import specific functions in the module , The syntax of this import method is as follows :

from module_name import function_name 

 Copy code 

By separating function names with commas , You can import any number of functions from the module as needed :

from module_name import function_0, function_1, function_2 

 Copy code 

The above example only imports cat.py Medium eat() Method

from cat import eat

eat('fish')

 Copy code 

Get the same result .

7.4.3 Use as Give the function an alias

If the name of the function to be imported may conflict with an existing name in the program , Or the name of the function is too long , You can specify a short and unique alias —— Another name for the function , It's like a nickname . To assign this special nickname to a function , You need to do this when importing it .

from cat import eat as cat_eat

cat_eat('fish')

 Copy code 

take cat.py Medium eat() Method imports and specifies an alias cat_eat, When using, you can use alias directly .

7.4.4 Use as Assign an alias to a module

You can also give the module an alias . By giving the module a short alias , Let you It is easier to call functions in modules .

General grammar :import module_name as mn

import cat as c

c.eat('fish')

 Copy code 

7.4.5 Import all functions in the module

Use the asterisk (*) The operator allows Python Import all functions in the module :

cat.py

def eat(food):
    print('I am cat, I eat ' + food)


def run():
    print('cat run')

 Copy code 

animal.py

from cat import *

eat('fish')
run()

 Copy code 

Output results

I am cat, I eat fish
cat run

 Copy code 

Because of importing Each function , Each function can be called by name , Instead of using a period representation . However , Use not written by yourself Large modules , It's best not to use this import method : If the name of a function in the module matches the name used in your project Same as , May lead to unexpected results : Python You may encounter multiple functions or variables with the same name , And then cover the function , and Not all functions are imported separately .

The best thing to do is , Or just import the functions you need to use , Either import the whole module and use the period notation . It can Make the code clearer , Easier to read and understand .

7.5 Function writing guide

  • Function should be given a descriptive name

  • Function names should contain only lowercase letters and underscores

  • Each function should contain a comment that briefly describes its function , This comment should follow the function definition , And use the document string format .

  • When a parameter is assigned a default value , No spaces on either side of the equal sign :

    def function_name(parameter_0, parameter_1='default value')
    
     Copy code 

    For keyword arguments in function calls , This agreement should also be followed :

    function_name(value_0, parameter_1='value')
    
     Copy code 
  • If a program or module contains more than one function , You can use two empty lines to separate adjacent functions , This makes it easier to know where the previous function ended , Where does the next function start .

  • be-all import Statements should be placed at the beginning of the file , The only exception is , Comments are used at the beginning of the file to describe the entire program .

8、 ... and 、 class

8.1 Create and use classes

class Cat():
    def __init__(self, name, color):
        self.name = name
        self.color = color

    def eat(self):
        print('cat ' + self.name + ' color ' + self.color + ', now eat')

    def run(self):
        print('cat ' + self.name + ' color ' + self.color + ', now run')


my_cat = Cat('Spring', 'white')
print(my_cat.name)
print(my_cat.color)
my_cat.eat()
my_cat.run()

 Copy code 

The class created above Cat , And instantiated my_cat, Then the class method is called. eat() and run(). Output results :

Spring
white
cat Spring color white, now eat
cat Spring color white, now run

 Copy code 

A function in a class is called a method .__init__() Is the construction method of function , When a new instance is created in each file Python Will run it automatically . Note that the constructor name must be this , It's prescribed .

In the example above __init__(self, name, color) There are three formal parameters , First parameter self essential , It must also precede the other parameters . Other parameters can be adjusted as needed .self Is a reference to the instance itself , Gives instances access to properties and methods in the class .

You can also access properties directly through instances :my_cat.name. This is not recommended in other languages .

stay Python 2.7 Create class in

stay Python 2.7 When creating a class in , Minor modifications are needed —— Include the word... In parentheses object:

class ClassName(object):

 Copy code 

8.2 Attributes of a class

8.2.1 Set default values for properties

Each attribute in a class must have an initial value , Even if the value is 0 Or empty string . In some cases , For example, when setting the default value , In the method __init__() It is possible to specify this initial value in ; If you do this for an attribute , You don't need to include a formal parameter that provides an initial value for it .

Redefinition Cat , Attribute in construction method age Set the default value .

class Cat():
    def __init__(self, name, color):
        self.name = name
        self.color = color
        self.age = 3

    def eat(self):
        print('cat ' + self.name + ' color ' + self.color + ', now eat')

    def run(self):
        print('cat ' + self.name + ' color ' + self.color + ', now run')

    def print_age(self):
        print('cat`s age is ' + str(self.age))

 Copy code 

8.2.2 Modify the value of the property

The value of an attribute can be modified in three different ways : Modify directly through the instance , Set by method .

1. Directly modify the value of the property

To modify the value of the property , The easiest way is to access it directly through an instance .

class Cat():
    def __init__(self, name, color):
        self.name = name
        self.color = color
        self.age = 3

    def eat(self):
        print('cat ' + self.name + ' color ' + self.color + ', now eat')

    def run(self):
        print('cat ' + self.name + ' color ' + self.color + ', now run')

    def print_age(self):
        print('cat`s age is ' + str(self.age))


my_cat = Cat('Spring', 'white')

my_cat.print_age()
my_cat.age = 4
my_cat.print_age()

 Copy code 

The output is

cat`s age is 3
cat`s age is 4

 Copy code 

The above example goes directly through my_cat.age = 4 Revised age The value of the property .

2. Method to modify the value of the property

Then update the code , Join in update_age() Method to modify age Properties of .

class Cat():
    def __init__(self, name, color):
        self.name = name
        self.color = color
        self.age = 3

    def eat(self):
        print('cat ' + self.name + ' color ' + self.color + ', now eat')

    def run(self):
        print('cat ' + self.name + ' color ' + self.color + ', now run')

    def print_age(self):
        print('cat`s age is ' + str(self.age))

    def update_age(self, age):
        self.age = age


my_cat = Cat('Spring', 'white')
my_cat.print_age()
my_cat.update_age(10)
my_cat.print_age()

 Copy code 

Run code output :

cat`s age is 3
cat`s age is 10

 Copy code 

8.3 Inherit

When one class inherits another , It automatically gets all the properties and methods of another class ; The original class is called the parent class , The new class is called a subclass . A subclass inherits all the properties and methods of its parent class , You can also define your own properties and methods .

class Animal():
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def run(self):
        print('Animal ' + self.name + ' run')

class Cat(Animal):
    def __init__(self, name, age):
        super().__init__(name, age)


cat = Cat('Tony', 2)
cat.run()

 Copy code 

Run the program , Output :

Animal Tony run

 Copy code 

First define the class Animal, It also defines Cat Inherited from Animal. Animal Called the parent class , Cat Called subclass . Through the output, you can verify , The subclass inherits the method of the parent class .

In the construction method of subclass, the construction method of parent class must be implemented first :super().__init__(name, age).

You can also define your own methods for subclasses , Or override the method of the parent class .

class Animal():
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def run(self):
        print('Animal ' + self.name + ' run')

class Cat(Animal):
    def __init__(self, name, age):
        super().__init__(name, age)

    def play(self):
        print('Cat ' + self.name + ' play')

    def run(self):
        print('Cat ' + self.name + ' run')


cat = Cat('Tony', 2)
cat.run()
cat.play()

 Copy code 

Let's change the program ,Animal Class invariant ,Cat Class still inherits Animal , But he defined his own method play() And rewrites the parent class method run() . Run the program , Get the output :

Cat Tony run
Cat Tony play

 Copy code 

Python2.7 Inheritance in

stay Python 2.7 in , Inheritance syntax is slightly different ,ElectricCar The definition of class is similar to the following :

class Car(object):
	def __init__(self, make, model, year):
    	--snip--
    
class ElectricCar(Car):
	def __init__(self, make, model, year):
		super(ElectricCar, self).__init__(make, model, year)
		--snip--

 Copy code 

function super() Two arguments are required : Subclass name and object self. To help Python Associate a parent class with a subclass , These arguments are essential . in addition , stay Python 2.7 When using inheritance in , Be sure to specify... In parentheses when defining the parent class object.

8.4 Import class

When a file is too long , You can pull some of the code out , Then import it into the main file .

There are many ways to import :

  • Import a single class

    If car.py Class is defined in Car

    from car import Car
    
     Copy code 
  • Import multiple classes from a module

    If car.py It contains three classes Car , Battery and ElectricCar .

    Import only one class :

    from car import ElectricCar
    
     Copy code 

    Import multiple classes , The middle is separated by commas :

    from car import Car, ElectricCar
    
     Copy code 
  • Import the entire module

    You can also import the entire module , Use the period notation again to access the required classes . This import method is simple , The code is also easy to read . Because the code that creates the class instance contains the module name , Therefore, there is no conflict with any name used in the current file .

    import car
    my_car = car.Car()
    
     Copy code 
  • Import all the classes in the module

    Each class in the module to be imported , You can use the following syntax :

    from module_name import *
    
     Copy code 

    This type of import is not recommended , There are two reasons .

    First , If you just look at the beginning of the file import sentence , Just You can clearly know which classes the program uses , Will be helpful ; However, this import method does not clearly indicate that you use Which classes of . This type of import can also cause name confusion . If you accidentally import a program file with its He has a class with the same name , Will cause errors that are difficult to diagnose . This import is introduced here , Because although it is not recommended to make In this way , But you might see it in someone else's code .

    When you need to import many classes from a module , It is best to import the entire module , And use module_name.class_name grammar Visiting and asking questions . In doing so , All the classes used are not listed at the beginning of the file , But you know exactly where in the program We used the imported module ; You also avoid possible name conflicts for each class in the import module .

Nine 、 Files and exceptions

9.1 Reading data from a file

To use the information in a text file , First of all, you need to read the information into memory . So , You can read the entire contents of the file at once , It can also be read step by step, one line at a time .

9.1.1 Read entire file

with open('test.txt') as file_obj:
    contents = file_obj.read()
    print(contents)

 Copy code 

open() Used to open a file , Parameter is the path of the file .

keyword with Close the file after you no longer need to access it . With with You just open the file , And use it when you need it ,Python Self meeting Automatically turn it off when appropriate .

Compared to the original file , The only difference in this output is that there is an empty line at the end . Why is there such an empty line ? because read() An empty string is returned when the end of the file is reached , When the empty string is displayed, it is a blank line . To delete extra empty lines , Can be found in print Use in statement rstrip().

The file path can be a relative path , It could be an absolute path .

9.1.2 Read line by line

with open('test.txt') as file_obj:
    for line in file_obj:
        print(line.rstrip())

 Copy code 

Check the file one line at a time , You can use for loop .

9.2 write file

with open('test.txt', 'w') as file_obj:
    file_obj.write("I love python")

 Copy code 

In this example , call open() Two arguments are provided when , The first argument is also the name of the file to open ; The second argument ('w') tell Python, We're going to open this file in write mode .

Optional mode :

  • r : read-only .
  • w : Just write . If the file does not exist, create , If the file exists, empty it first , Write again .
  • a : Additional mode , The written content is appended to the original file . If the file does not exist, create .
  • r+ : Can read but write .

If you omit the pattern arguments ,Python The file will be opened in the default read-only mode .

9.3 abnormal

Exceptions are used try-except Code block processing .try-except Block of code to Python Performs the specified operation , At the same time to tell Python What happens when something unusual happens .

try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")

 Copy code 

else Code block

try:
    print(5/0)
except ZeroDivisionError:
    print("You can't divide by zero!")
else:
	print("no exception")

 Copy code 

If try The code in ran successfully , No exception occurred , execute else Code in a code block .

9.4 use json Store the data

Python Use in json.dump() and json.load() To store and read json file .

import json

userInfo = {'username': 'jack', 'age': 18}

with open('test.txt', 'w') as obj:
    json.dump(userInfo, obj)

with open('test.txt') as obj:
    content = json.load(obj)
    print(content)

 Copy code 

In the example above json.dump() Put the data in test.txt in , And with json.load() Take the data out of the file and print .

Please import before use json modular .

Ten 、 unit testing

First define a function to splice names name_function.py

def get_formatted_name(first, last):
    full_name = first + ' ' + last
    return full_name.title()

 Copy code 

Then write a test class to test this function

import unittest
from name_function import get_formatted_name

class NamesTestCase(unittest.TestCase):

    def test_name_function(self):
        full_name = get_formatted_name('david', 'alex')
        self.assertEqual(full_name, 'David Alex')


unittest.main()

 Copy code 

Test class to inherit unittest.TestCase , adopt self.assertEqual Assert whether the result is the same as expected .

Common assertion methods

Method purpose
assertEqual(a, b) verify a == b
assertNotEqual(a, b) verify a != b
assertTrue(x) verify x by True
assertFalse(x) verify x by False
assertIn(item, list) verify item stay list in
assertNotIn(item, list) verify item be not in list in

setUp() Method

If you are in the TestCase Class contains methods setUp() ,Python Will run it first , Then run each to test_ The way to start .

Usually used to do some initialization operations .


#### summary pyton Its language characteristics and coding style are relatively easy to understand , It's also the foundation , This article is just a preliminary study python A cushion for , You should learn how to use it well , It's also a process and a good start .

In this paper, from juejin.cn/post/684490…, If there is any infringement , Please contact to delete .

copyright notice
author[User 4648189936722],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/02/202202020611530304.html

Random recommended