Python -> (3) study notes

Installation and set up a Linux environment

1) part of the Linux distributions include all Python packages, you can aptinstall such tools;
2) Anaconda installation: need to use a file name similar to Anaconda3-4.1.0-Linux-86_64.sh file during installation, the bash command line input bash Anaconda3-4.1.0-Linux-86_64.sh, select the installation path after receiving the license; .bashrc file modify export PATH=/home/user/anaconda/bin:$PATH, add his / bin directory to the variable $ pATH; to open a terminal by source~/.bashrcperforming a .bashrc;
. 3) install other packages: conda install package_name, pip install package_name
4) update package: conda update package_name,pip install --upgrade package_name

About interpreter

Python is a scripting language, you can write code directly in the Python interpreter, the code can also be written to a file that is in the script.
1) interpreter: Open a terminal, type a pu t hon3carriage return, then the interpreter will be in interactive mode, enter C t r l+Dexit the interpreter;
2) script file: vim to, for example, vim helloworld.pystart vim and edit hello world.py, enter the code; chmod +x helloworld.pyfile Add execute permissions; ./helloworld.pyexecute the script file (provided that the code inside #!/usr/bin/env python3), otherwise python3execution;

Code style

In Python, the space is very important, if at the beginning of the line indentation is wrong, Python interpreter will throw an error. The following guidelines are recommended conventions:

  • Use 4 spaces to indent
  • Blank line between functions
  • Two lines between classes
  • Dictionaries, lists, tuples, and a parameter list, ,after adding a space. For the dictionary, :the back also add a space
  • `Notes #

Variables and Data Types

  • keywords
  • You do not need to specify a data type;
  • Defining a plurality of single-line or variable assignments, eg,
$ python3
>>> x , y = 12, 17
>>> a
12
>>> b
17

Values ​​can be used to exchange two numbers:

>>> x, y = y , x
>>> x
17
>>> y
12

Mechanism is a tuple (tuple) of the package (to the right of the equal sign) and unpacked tuple (left), eg.,

>>> data = ("shiyanlou", "China", "Python")
>>> name, country, language = data
>>> name
'shiyanlou'
>>> country
'China'
>>> language
'Python'

Examples of simple code:

1) The following procedure is used to find the average of the N numbers. Please /home/shiyanlou/averagen.py program code written to the file, the program will require 10 digits, calculates the average of the last 10 digits.

#!/usr/bin/env python3
N = 10
sum = 0
count = 0
print("please input 10 numbers:")
while count < N:
    number = float(input())
    sum = sum + number
    count = count + 1
average = sum / N
print("N = {}, Sum = {}".format(N, sum))
print("Average = {:.2f}".format(average))

Run the program:

$ chmod +x averagen.py
$ ./averagen.py

2) In the following procedure, we use the formula C = (F - 32) / 1.8 Celsius to Fahrenheit converted.
{: 5d} meant replacing five character width integer less than the width of the blank padding used. {: 7.2f} meant replaced seven character width to retain two decimal, the decimal point can be considered a width less than the width of the spaces filled. Wherein a width of 7 means 7, .2f refers to two decimal places.

#!/usr/bin/env python3
fahrenheit = 0
print("Fahrenheit Celsius")
while fahrenheit <= 250:
    celsius = (fahrenheit - 32) / 1.8 # 转换为摄氏度
    print("{:5d} {:7.2f}".format(fahrenheit , celsius))
    fahrenheit = fahrenheit + 25

Operators and Expressions

Type conversion:

  • String -> float value: float(string);
  • String -> integer value:int(string)
  • Integer -> string:str(integer)
  • Floating-point value -> string:str(float)

A chestnut

Calculating a circle of radius 2 and the area of ​​the printout, the 10 decimal places:

$ cd /home/user/Code
$ touch CircleArea.py
$ python3 /home/user/Code/CircleArea.py
import math

# 计算圆的面积
area = 2 * 2 * math.pi

# 格式化输出圆的面积,保留10位小数
print("{:.10f}".format(area))

List

  • It can be written as comma-separated values ​​between brackets an element of the list need not be of the same type:
>>> a = [ 1, 342, 223, 'India', 'Fedora']
>>> a
[1, 342, 223, 'India', 'Fedora']
  • The zero-based index:
>>> a[0]
1
>>> a[4]
'Fedora'
>>> a[-1]
'Fedora'
  • slice
>>> a[0:-1]
[1, 342, 223, 'India']
>>> a[2:-2]
[223]
>>> a[:]
[1, 342, 223, 'India', 'Fedora']

Index sections have useful default; omitted defaults to zero the first index, the second index omitted default size of the string sections:

>>> a[:-2]
[1, 342, 223]
>>> a[-2:]
['India', 'Fedora']
 +---+-----+-----+---------+----------+
 | 1 | 342 | 223 | 'India' | 'Fedora' |
 +---+-----+-----+---------+----------+
   0    1     2       3        4          5
  -5   -4    -3      -2       -1
  • For non-negative indices, if up and down within the boundary, the length of a slice is the difference between the two indexes. For example, a[2:4]it is 2.
  • Python relating to the subject of the collection are to meet at the left and right opening and closing principle, slice, too, that the left edge of the set value can take to the right edge value can not get to. On the above list, a[0:5]using mathematical expressions can be written as [0,5), with an index value of 0,1,2,3,4, so can a get to all the values. Can also be used a [: 5], the effect is the same. And a[-5:-1], since the left and right principles opening and closing, which is a value -5,-4,-3,-2that does not include -1, in order to take the last value, may be used a[-5:], which represents the value of the last five to take the list.
  • The slicing operation may be provided the step
>>> a[1::2]
[342, 'India']

1 from the end sections to the index list, every two element values.

  • The list of join operations
>>> a + [36, 49, 64, 81, 100]
[1, 342, 223, 'India', 'Fedora', 36, 49, 64, 81, 100]
  • Modify the list of elements
>>> cubes = [1, 8, 27, 65, 125]
>>> cubes[3] = 64
>>> cubes
[1, 8, 27, 64, 125]
  • To check whether a value is present in the list
>>> a = ['ShiYanLou', 'is', 'cool']
>>> 'cool' in a
True
>>> 'Linux' in a
False
  • Get the length of the list
>>> len(a)
3
  • Check if the list is empty
if list_name: # 列表不为空
    pass
else: # 列表为空
    pass
  • Nested list
>>> a = ['a', 'b', 'c']
>>> n = [1, 2, 3]
>>> x = [a, n]
>>> x
[['a', 'b', 'c'], [1, 2, 3]]
>>> x[0]
['a', 'b', 'c']
>>> x[0][1]
'b'

range () function - to generate a sequence of values ​​(not a list)

>>> for i in range(5):
...     print(i)
...
0
1
2
3
4
>>> range(1, 5)      
range(1, 5)
>>> list(range(1, 5))
[1, 2, 3, 4]
>>> list(range(1, 15, 3))
[1, 4, 7, 10, 13]
>>> list(range(4, 15, 2))
[4, 6, 8, 10, 12, 14]
Published 33 original articles · won praise 1 · views 1254

Guess you like

Origin blog.csdn.net/weixin_44783002/article/details/104524811