Python文档阅读

本文详细介绍了Python的基础语法,包括字符串操作、列表使用方法、流程控制语句如if和for循环等,并提供了定义函数的方法和实例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

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.

>>> 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:

print("""\
Usage: thingy [OPTIONS]
     -h                        Display this usage message
     -H hostname               Hostname to connect to
""")
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.

>>> 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 :

>>> 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)

>>> 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.

>>> 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):

>>> 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:

>>> 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:

>>> 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):

>>> # 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:

>>> 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:

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:

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

Here is the solution:

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

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

>>> 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:

>>> 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:

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!’)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值