Python入门学习

Python文档阅读和Python语法点拾遗

Python文档阅读

这是一个英语阅读生词总结笔记(大雾)

Some prompts :

  • (>>>) (three greater-than signs) primary prompt
  • (…) secondary prompt

Operators :

  • (//) to do floor division and get a integer result (discarding any flactional result)
  • (\)** to calculate power
  • (_) if you use Python as a calculator you can type _ to get the last printed expression (ps. Don not assign the value to it)
  • use round(a, b) to keep a in the b decimal place
  • (j or J) use the J suffix to indicate the imaginary part

String operators :
quotes : 单引号
double quotes : 双引号
backslashes : 反斜线
(\) use \‘ to escape the single quote
(\n) \n means newline

String operation :
If you don’t want character prefaced by \ to be interpreted as special characters, you can use raw string by adding an r before the first quote.

1
2
3
4
5
>>> print('C:\some\name')
C:\some
ame
>>> print(r'C:\some\name')
C:\some\name

using triple-quotes : ''' or """ so that the strings literals can span multiple lines. and use \at the end of the line to avoid that end of lines are automatically included in the string.
The following example:

1
2
3
4
5
print("""\
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to
""")
1
2
3
Usage: thingy [OPTIONS]
-h Display this usage message
-H hostname Hostname to connect to

Strings can be concatenated (glued together) with the + operator and repeated with *.
Two or more string literals next to each other are automatically concatenated.

1
2
3
4
>>> text = ('Put several strings within parentheses '
... 'to have them joined together.')
>>> text
'Put several strings within parentheses to have them joined together.'

This feature is only work with two literals, not with variables or expressions.

The string indices alse can be negative number,to counting from the right.
negetive indices start from -1

slicing slicing is used to obtain the substring
There follwing examples :

1
2
3
4
5
>>> word = 'Python'
>>> word[0:2] # characters from position 0 (included) to 2 (excluded)
'Py'
>>> word[2:5] # characters from position 2 (included) to 5 (excluded)
'tho'

The start is always included, and end always excluded.This make sure that s[:i] + s[i:] always equal to s.

Note : an omitted first index defaults to zero.

Python strings are immutable, so assigning to an indexed position in the string result in an error.

List :
Lists can contain different types, but usually the items all have the same type.
List also can be indexed and sliced.(same as string)

1
2
3
4
5
6
>>> squares[0]  # indexing returns the item
1
>>> squares[-1]
25
>>> squares[-3:] # slicing returns a new list
[9, 16, 25]

List also support operations like concatenation.

1
2
>>> squares + [36, 49, 64, 81, 100]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

Unlike string, list is a mutable type, it is possible to change their content.
You can also add new items at the end of the list, by using the append() method (we will see more about methods later):

1
2
3
4
>>> cubes.append(216)  # add the cube of 6
>>> cubes.append(7 ** 3) # and the cube of 7
>>> cubes
[1, 8, 27, 64, 125, 216, 343]

Assignment to slices is also possible, and this can even change the size of the list or clear it entirely:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> letters
['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> # replace some values
>>> letters[2:5] = ['C', 'D', 'E']
>>> letters
['a', 'b', 'C', 'D', 'E', 'f', 'g']
>>> # now remove them
>>> letters[2:5] = []
>>> letters
['a', 'b', 'f', 'g']
>>> # clear the list by replacing all the elements with an empty list
>>> letters[:] = []
>>> letters
[]

build-in function len() also applies to lists.
nest list is also allowed.

Contains in while
The condition may also be a string or list value, in fact any sequence; anything with a non-zero length is true, empty sequences are false.

Indentation is Python’s way of grouping statements.

The keyword argument end can be used to avoid the newline after the output, or end the output with a different string:

1
2
3
4
5
6
>>> a, b = 0, 1
>>> while a < 1000:
... print(a, end=',')
... a, b = b, a+b
...
0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,

More Control Flow Tools

if Statements
The else part is optional.
The keyword ‘elif’ is short for ‘else if’,and is useful to avoid excessive indentation.An if … elif … elif … sequence is a substitute for the switch or case statements found in other languages.

for Statements
Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example (no pun intended):

1
2
3
4
5
6
7
8
>>> # Measure some strings:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print(w, len(w))
...
cat 3
window 6
defenestrate 12

The range() Function
the built-in function range() can make the sequence of numbers.
These following example:

1
2
3
4
5
6
7
8
>>> for i in range(5):
... print(i)
...
0
1
2
3
4

It is possible to let the range start at another number, or to specify a different increment:

1
2
3
4
5
6
7
8
range(5, 10)
5, 6, 7, 8, 9

range(0, 10, 3)
0, 3, 6, 9

range(-10, -100, -30)
-10, -40, -70

A strange thing happens if you just print a range:

1
2
>>> print(range(10))
range(0, 10)

Here is the solution:

1
2
>>> list(range(4))
[0, 1, 2, 3]

break and continue statements and else Clauses on Loops:
break and continue are like in C++.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print(n, 'equals', x, '*', n//x)
... break
... else:
... # loop fell through without finding a factor
... print(n, 'is a prime number')
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3

In this code, the else is belongs to the for loop, not the if statement.
The loop’s else clause runs when no break occurs.

pass Statement :
It can be used when a statement is required syntactically but the program requires no action.
pass can be used is as a place-holder for a function or conditional body when you are working on new code

Defining Functions :
Other names can also point to that same function object and can also be used to access the function:

1
2
3
4
5
>>> fib
<function fib at 10042ed0>
>>> f = fib
>>> f(100)
0 1 1 2 3 5 8 13 21 34 55 89

The example for the defining function:

1
2
3
4
5
6
7
8
9
10
11
def ask_ok(prompt, retries=4, reminder='Please try again!'):
while True:
ok = input(prompt)
if ok in ('y', 'ye', 'yes'):
return True
if ok in ('n', 'no', 'nop', 'nope'):
return False
retries = retries - 1
if retries < 0:
raise ValueError('invalid user response')
print(reminder)

This function can be called in several ways:
giving only the mandatory argument: ask_ok(‘Do you really want to quit?’)
giving one of the optional arguments: ask_ok(‘OK to overwrite the file?’, 2)
or even giving all arguments: ask_ok(‘OK to overwrite the file?’, 2, ‘Come on, only yes or no!’)

Python语法点拾遗

1
2
3
4
5
6
7
import表示引入某一个模块。

import [... ] as (...) 表示引入一个 [...] 模块并且重命名为 (...)。

from [...] import (...) 表示从[...]模块中引入(...)函数。

from [...] import (...) as {...}表示从[...]模块中引入(...)函数并且重命名为 {...}。

Python入门学习

https://dicemy.com/55956

作者

Dicemy

发布于

2020-12-07

更新于

2022-02-12

许可协议

评论