Python基本概念

  • 2020 年 1 月 13 日
  • 筆記

一 基本概念

1 字面意義上的常量,如2、『This is ok'這樣的字元串

>>> print('a,2,3')

a,2,3

2 字元串

  • 單引號(『) 使用單引號指示字元串,類似shell中的強引用,所有的空格、製表符照原樣保留。

>>> print('This is ok')

This is ok

print 'I'd mouch you 'not'.' 也可以這樣表示: print "I'd mouch you 'not'."

print 'I "said" do not touch this.'

備註:注意單引號和雙引號的混合使用

  • 雙引號(「) 在雙引號中的字元串與單引號中的字元串使用完全相同

>>> print("This is ok")

This is ok

  • 三引號(''') 利用三引號,可以指示一個多行的字元串,可以在三引號中自由的使用單引號和雙引號。

>>> '''This is am string.This is the first line.

... This is the second line.

... "What's your name?" Lasked.

... He said "Bond,JamesBond."'''

'This is am string.This is the first line.nThis is the second line.n"What's your name?" Lasked.nHe said "Bond,JamesBond."'

  • 轉義符

>>> 'what 's your name'            #在單引號中實現單引號的使用

"what 's your name"

或使用雙引號

>>> "what'your name"

"what'your name"

>>> "This is "ok","               #雙引號中實現雙引號的引用

'This is "ok",'

備註:行尾單獨反斜杠,表示字元串在下一行繼續,如:

>>> 'This is ok

... ,hello'

'This is ok,hello'

  • 自然字元串 如果不需要轉義符那樣特別處理的字元串,那麼可以給字元串加上前綴r或R來指定一個自然字元串

>>> r'New line are by n'

'New line are by \n'

3 對象:python在程式中把用到的任何東西都稱為對象。

4 變數:

>>> i=100;print(i);

100

5 縮進:每個縮進層次使用2個或4個空格或單個製表符,使用其中的一種風格並且一值使用它。

二 表達式:Python大多數語句都包含表達式,如2+3,一個表達式可以分解為運算符和操作數。在上面的例子中,+為運算符,2和3為操作數。

示例:

>>> 2+3

5

>>> 3+3*2

9

三 控制流:

1 if語句

#!/bin/env python

number=23

guess=int(raw_input('Enter an integer: '))

if guess==number:

  print 'Congratulations,you guessed it.'

  print "(but you do not win any prizes!)"

elif guess<number:

  print 'No,it is a little highers than that'

else:

  print 'No,it is a little lower than that'

print 'Done'

2 for語句:

#!/bin/env python

for i in range(1,5):

  print i

else:

  print 'The for loop is over'

3 while語句

#!/bin/env python

number=23

running=True

while running:

  guess=int(raw_input('Enter an integer:'))

  if guess==number:

    print 'Congratulations,you guessedit.'

    running=False

  elif guess<number:

    print 'No,it is a little higher than that'

  else:

    print 'No,it is a little lower than that'

else:

  print 'The while loop is over.'

print 'Done'

四 函數:函數是重複使用的程式段,並且可以在你的程式的任何地方使用,這被稱為調用函數。在Python中有許多的內建函數,如len()。

函數通過def定義,示例如下:

#!/bin/env python

def abc():

  print'This is abc'

abc()

五 關於編碼:通常情況下,在Python程式中,不應有中文,如果要有的話,需要添加以下參數:

#!/bin/env python

#-- coding:utf-8 --

#chickents:

print "I will now count my chickents:"

#計算數值:

print "Hens", 25 + 30 /6

print "Roosters", 100 - 25 * 3 % 4

Tags: