前方高能——Python概念總結(jié)

Arithmetic Expressions*

addition: <Number> + <Number> = <Number>

  • outputs the sum of the two input numbers

multiplication: <Number> * <Number> = <Number>

  • outputs the product of the two input numbers

subtraction: <Number> - <Number> = <Number>

  • outputs the difference between the two input numbers

division: <Number> / <Number> = <Number>

  • outputs the result of dividing the first number by the second Note: if both numbers are whole numbers, the result is truncated to just the whole number part.

Variables and Assignment

Names

A <name> in Python can be any sequence of letters, numbers, and underscores (_) that does not start with a number. We usually use all lowercase letters for variable names, but capitalization must match exactly. Here are some valid examples of names in Python (but most of these would not be good choices to actually use in your programs):

  • my_name
  • one2one
  • Dorina
  • this_is_a_very_long_variable_name
    Assignment Statement

An assignment statement assigns a value to a variable:

- <name> = <expression>

After the assignment statement, the variable <name> refers to the value of the <expression> on the right side of the assignment. An <expression> is any Python construct that has a value.

Multiple Assignment

We can put more than one name on the left side of an assignment statement, and a corresponding number of expressions on the right side:

<name1>, <name2>, ... = <expression1>, <expression2>, ...

All of the expressions on the right side are evaluated first. Then, each name on the left side is assigned to reference the value of the corresponding expression on the right side. This is handy for swapping variable values. For example,

  • s, t = t, s

would swap the values of s and t so after the assignment statement s now refers to the previous value of t, and t refers to the previous value of s.

Note: what is really going on here is a bit different. The multiple values are packed in a tuple (which is similar to the list data type introduced in Unit 3, but an immutable version of a list), and then unpacked into its components when there are multiple names on the left side. This distinction is not important for what we do in CS101, but does become important in some contexts.

Procedures

A procedure takes inputs and produces outputs. It is an abstraction that provides a way to use the same code to operate on different data by passing in that data as its inputs.

Defining a procedure:

def <Name>(<Parameters>):

  <Block>

The <Parameters> are the inputs to the procedure. There is one <Name> for each input in order, separated by commas. There can be any number of parameters (including none).

To produce outputs:

return <Expression>, <Expression>, ...

There can be any number of expressions following the return (including none, in which case the output of the procedure is the special value None).

Using a procedure:

<''Procedure''>(<Input>, <Input>, ...)

The number of inputs must match the number of parameters. The value of each input is assigned to the value of each parameter name in order, and then the block is evaluated.

If Statements

The if statement provides a way to control what code executes based on the result of a test expression.

if <TestExpression>:

<Block>

The code in <Block> only executes if the <TestExpression> has a True value.

Alternate clauses. We can use an else clause in an if statement to provide code that will run when the <TestExpression> has a False value.

if <TestExpression>:

<BlockTrue>

else:

    <BlockFalse>

Logical Operators

The and and or operators behave similarly to logical conjunction (and) and disjunction (or). The important property they have which is different from other operators is that the second operand expression is evaluated only when necessary.

  • <Expression1> and <Expression2>
  • If Expression1 has a False value, the result is False and Expression2 is not evaluated (so even if it would produce an error it does not matter). If Expression1 has a True value, the result of the and is the value of Expression2.
  • <Expression1> or <Expression2>
    If Expression1 has a True value, the result is True and Expression2 is not evaluated (so even if it would produce an error it does not matter). If Expression1 has a False value, the result of the or is the value of Expression2'.

Loops

Loops provide a way to evaluate the same block of code an arbitrary number of times.

While Loops

A while loop provides a way to keep executing a block of code as long as a test expression is True.

    while <TestExpression>:
    
          <Block>

If the <TestExpression> evaluates to False, the while loop is done and execution continues with the following statement. If the <TestExpression> evaluates to True, the <Block> is executed. Then, the loop repeats, returning to the <TestExpression> and continuing to evaluate the <Block> as long as the <TestExpression> is True.

For Loops

A for loop provides a way to execute a block once for each element of a collection:

for <Name> in <Collection>:
<Block>

The loop goes through each element of the collection, assigning that element to the <Name> and evaluating the <Block>. The collection could be a String, in which case the elements are the characters of a string; a List, in which case the elements are the elements of the list; a Dictionary, in which case the elements are the keys in the dictionary; or many other types in Python that represent collections of objects.

Strings

A string is sequence of characters surrounded by quotes. The quotes can be either single or double quotes, but the quotes at both ends of the string must be the same type. Here are some examples of strings in Python:

  • "silly"
  • 'string'
  • "I'm a valid string, even with a single quote in the middle!"

String Operations

length: len(<String>) = <Number>

  • Outputs the number of characters in <String>

string concatenation: <String> +
<String> = <String>

  • Outputs the concatenation of the two input strings (pasting the string together with no space between them)

string multiplication: <String> * <Number> = <String>

  • Outputs a string that is <number> copies of the input <string> pasted together

INDEXING STRINGS

The indexing operator provides a way to extract subsequences of characters from a string.

string indexing: <String>[<Number>] = <String>

  • Outputs a single-character string containing the character at position <number> of the input <string>.

Positions in the string are counted starting from 0, so s[1] would output the second character in s. If the <Number> is negative, positions are counted from the end of the string: s[-1] is the last character in s.*

string extraction: <String>[<Start Number>:<Stop Number>] = <String>

  • Outputs a string that is the subsequence of the input string starting from position <Start Number> and ending just before position <Stop Number>. If <Start Number> is missing, starts from the beginning of the input string; if <Stop Number> is missing, goes to the end of the input string.

find The find method provides a way to find sub-sequences of characters in strings.

find: <Search String>.find(<Target String>) = <Number>

  • Outputs a number giving the position in <Search String> where <Target String> first appears. If there is no occurrence of <Target String> in <Search String>, outputs -1.

To find later occurrences, we can also pass in a number to find:

find after: <Search String>.find(<Target String>, <Start Number>) = <Number>

  • Outputs a number giving the position in <Search String> where <Target String> first appears that is at or after the position give by <Start Number>. If there is no occurrence of <Target String> in <Search String> at or after <Start Number>, outputs -1.

CONVERTING BETWEEN NUMBERS AND STRINGS

str: str(<Number>) = <String>

  • Outputs a string that represents the input number. For example, str(23) outputs the string '23'.

ord: ord(<One-Character String>) = <Number>

  • Outputs the number corresponding to the input string.

chr: chr(<Number>) = <One-Character String>

  • Outputs the one-character string corresponding to the number input. This function is the inverse of ord: chr(ord(a)) = a for any one-character string a.

SPLITTING STRINGS

split: <String>.split() = [<String>, <String>, ... ]

  • outputs a list of strings that are (roughly) the words contained in the input string. The words are determined by whitespace (either spaces, tabs, or newlines) in the string. (We did not cover this in class, but split can also be used with an optional input that is a list of the separator characters, and a second optional input that controls the maximum number of elements in the output list.)

LOOPING THROUGH STRINGS

A for loop provides a way to execute a block once for each character in a string (just like looping through the elements of a list):

for <Name> in <String>:
<Block>**

The loop goes through each character of the string in turn, assigning that element to the <Name> and evaluating the <Block>.

Lists

A list is a mutable collection of objects. The elements in a list can be of any type, including other lists.

Constructing a list. A list is a sequence of zero or more elements, surrounded by square brackets:

[ <Element>, <Element>, ... ]
Selecting elements: <List>[<Number>] = <Element>

  • Outputs the value of the element in <List> at position <Number>. Elements are indexed starting from 0.

Selecting sub-sequences: <List>[<Start> : <Stop>] = <List>

  • Outputs a sub-sequence of <List> starting from position <Start>, up to (but not including) position <Stop>.

Update: <List>[<Number>] = <Value>

  • Modifies the value of the element in <List> at position <Number> to be <Value>.

Length: len(<List>) = <Number>

  • Outputs the number of (top-level) elements in <List>.

Append: <List>.append(<Element>)

  • Mutates <List> by adding <Element> to the end of the list.

Concatenation: <List1> + <List2> = <List3>**

  • Outputs a new list that is the elements of <List1> followed by the elements of <List2>.

Popping: <List>.pop() = <Element>

  • Mutates <List> by removing its last element. Outputs the value of that element. If there are no elements in <List>, [].pop() produces an error.

Finding: <List>.index(<Value>) = <Number>

  • Outputs the position of the first occurrence of an element matching <Value> in <List>. If <Value> is not found in <List>, produces an error.

Membership: <Value> in <List> = <Boolean>

  • Outputs True if <Value> occurs in <List>. Otherwise, outputs False.

Non-membership: <Value> not in <List> = <Boolean>

  • Outputs False if <Value> occurs in <List>. Otherwise, outputs True.

Loops on Lists

A for loop provides a way to execute a block once for each element of a list:

for <Name> in <List>:
<Block>

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末冤竹,一起剝皮案震驚了整個(gè)濱河市默怨,隨后出現(xiàn)的幾起案子甘桑,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,542評(píng)論 6 504
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件壶栋,死亡現(xiàn)場(chǎng)離奇詭異结胀,居然都是意外死亡两残,警方通過(guò)查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,822評(píng)論 3 394
  • 文/潘曉璐 我一進(jìn)店門(mén)把跨,熙熙樓的掌柜王于貴愁眉苦臉地迎上來(lái)人弓,“玉大人,你說(shuō)我怎么就攤上這事着逐〈薅模” “怎么了?”我有些...
    開(kāi)封第一講書(shū)人閱讀 163,912評(píng)論 0 354
  • 文/不壞的土叔 我叫張陵耸别,是天一觀的道長(zhǎng)健芭。 經(jīng)常有香客問(wèn)我,道長(zhǎng)秀姐,這世上最難降的妖魔是什么慈迈? 我笑而不...
    開(kāi)封第一講書(shū)人閱讀 58,449評(píng)論 1 293
  • 正文 為了忘掉前任,我火速辦了婚禮省有,結(jié)果婚禮上痒留,老公的妹妹穿的比我還像新娘。我一直安慰自己蠢沿,他們只是感情好伸头,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,500評(píng)論 6 392
  • 文/花漫 我一把揭開(kāi)白布。 她就那樣靜靜地躺著舷蟀,像睡著了一般恤磷。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上野宜,一...
    開(kāi)封第一講書(shū)人閱讀 51,370評(píng)論 1 302
  • 那天扫步,我揣著相機(jī)與錄音,去河邊找鬼匈子。 笑死河胎,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的旬牲。 我是一名探鬼主播仿粹,決...
    沈念sama閱讀 40,193評(píng)論 3 418
  • 文/蒼蘭香墨 我猛地睜開(kāi)眼搁吓,長(zhǎng)吁一口氣:“原來(lái)是場(chǎng)噩夢(mèng)啊……” “哼原茅!你這毒婦竟也來(lái)了?” 一聲冷哼從身側(cè)響起堕仔,我...
    開(kāi)封第一講書(shū)人閱讀 39,074評(píng)論 0 276
  • 序言:老撾萬(wàn)榮一對(duì)情侶失蹤擂橘,失蹤者是張志新(化名)和其女友劉穎,沒(méi)想到半個(gè)月后摩骨,有當(dāng)?shù)厝嗽跇?shù)林里發(fā)現(xiàn)了一具尸體通贞,經(jīng)...
    沈念sama閱讀 45,505評(píng)論 1 314
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡朗若,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 37,722評(píng)論 3 335
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了昌罩。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片哭懈。...
    茶點(diǎn)故事閱讀 39,841評(píng)論 1 348
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖茎用,靈堂內(nèi)的尸體忽然破棺而出遣总,到底是詐尸還是另有隱情,我是刑警寧澤轨功,帶...
    沈念sama閱讀 35,569評(píng)論 5 345
  • 正文 年R本政府宣布旭斥,位于F島的核電站,受9級(jí)特大地震影響古涧,放射性物質(zhì)發(fā)生泄漏垂券。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,168評(píng)論 3 328
  • 文/蒙蒙 一羡滑、第九天 我趴在偏房一處隱蔽的房頂上張望菇爪。 院中可真熱鬧,春花似錦柒昏、人聲如沸娄帖。這莊子的主人今日做“春日...
    開(kāi)封第一講書(shū)人閱讀 31,783評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽(yáng)近速。三九已至,卻和暖如春堪旧,著一層夾襖步出監(jiān)牢的瞬間削葱,已是汗流浹背。 一陣腳步聲響...
    開(kāi)封第一講書(shū)人閱讀 32,918評(píng)論 1 269
  • 我被黑心中介騙來(lái)泰國(guó)打工淳梦, 沒(méi)想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留析砸,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 47,962評(píng)論 2 370
  • 正文 我出身青樓爆袍,卻偏偏與公主長(zhǎng)得像首繁,于是被迫代替她去往敵國(guó)和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子陨囊,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 44,781評(píng)論 2 354

推薦閱讀更多精彩內(nèi)容