Python初級入門精講-學習筆記

print("Hello World!")
Hello World!
print("Hello World!")
Hello World!
a = 0x0608
print(a )
1544

整數

  • 整數通常指不帶有小數部分的數字,包括自然數,0,負數等
  • 可以表示任意大的數
  • 整數的進制:
    • 十進制
    • 二進制
      • 0b
    • 八進制
      • 0o
    • 十六進制
      • 0x
# 十進制轉二進制
a = 100
b = bin(a)
print(b)
0b1100100
# 十進制轉八進制
a = 100
b = oct(a)
print(b)
#十進制轉16進制
c = hex(a)
print(c)
0o144
0x64
# 檢驗以上結果是否正確
a = 0o144
print(a)
b = 0x64
print(b)
100
100

浮點數

  • 定義:
  • 表現形式:
    • 常見小數
    • 科學計數法,小數乘以10爲底的指數,指數可以爲負數
#科學計數法
a = 3.243234e3
print(a)
3243.234

複數

  • 由實部和虛部組成,中間用‘+’號鏈接,虛部後跟‘j’表示
  • 例如 :3+4j 23,12 + 43.2j
# 複數
a = 3. + 4j
print(a)
(3+4j)

2.字符串類型

什麼是字符串

  • 表示文本信息的一種形式
  • 排列有序
  • 在非註釋中,凡是引號括起來的部分都是字符串
  • 引號類型
    • 單引號: ‘’
    • 雙引號:""
    • 三單引號:’’’’’’
    • 三雙引號: “”""""

引號的區別

  • 單雙引號沒有區別
  • 三單引號 和 三雙引號 之間沒有區別
  • 三引號常用來表示多行字符串信息,或者在程序函數內部函數體開頭表示函數說明
a = '''
王啊王
'''
print(a)
王啊王
# 字符串中出現引號
# 比如 Let's go
a = 'Let's go'
print(a)
  File "<ipython-input-18-c3cfddb251e8>", line 3
    a = 'Let's go'
             ^
SyntaxError: invalid syntax
# 字符串 中出現引號 ,需要換一種引號引起來
a = "Let's go"
print(a)
Let's go
# 字符串 中出現引號 ,需要換一種引號引起來
a = '''Let's go'''
print(a)
Let's go
# 字符串 中出現引號 ,需要換一種引號引起來
a = """Let's go"""
print(a)
Let's go

轉義字符

  • 轉義字符L字符串中一些不太好表示的符號,比如換行,製表符,連同一些需要特殊表示的符號,被如單引號,爲了表示這些符號,需要用一些特殊形式,俗稱轉義,需要轉義符號,俗稱轉義字符
    • 轉義字符::
      • 單引號:’
      • 雙引號:"
      • 響鈴: \a
      • 反斜槓: \
      • 換行:\n
      • 水平製表符:\t
      • 垂直製表符:\v
      • 倒退:\b
      • 空字符串:字符值爲0:\0
      • unicode 16位的十六進制值:\uxxxx(注意,是四個數字)
      • Unicode 32位的十六進制值:\uxxxx xxxx(注意,u後面是8位值)
      • 十六進制值:\xXX(注意:第一個x是必須有的,後邊大X表示十六進制)
      • 八進制值:\Oxx
# 字符串 中出現引號 ,需要換一種引號引起來
a = 'Let\'s go'
print(a)
Let's go

3.布爾類型

String 類型的API

  • API 應用程序接口,是第三方已經做好的繼承好的程序功能,我們需要的僅僅是使用/調用,目的是最大程度上減少使用者的開發時間,提高使用者的開發效率
  • 不重複造輪子

1.一般函數

  • startswith/endswith
    • 判斷字符串是否以特定字符串開頭或者結尾
  • count
    • 計數,計算一個字符串從某字符串出現的次數
  • find
    • 查找字符串中子字符串出現的位置
    • 能查到,返回第一個查到的位置
    • 查不到結果,返回 -1
# 判斷字符串開頭或者結尾
s = "I comes from china"
s.startswith("I")
True
# count 例子
s.count("789")
0
s.count("rom")
1
s.find("I")
0
## 查手冊:
help(str)
Help on class str in module builtins:

class str(object)
 |  str(object='') -> str
 |  str(bytes_or_buffer[, encoding[, errors]]) -> str
 |  
 |  Create a new string object from the given object. If encoding or
 |  errors is specified, then the object must expose a data buffer
 |  that will be decoded using the given encoding and error handler.
 |  Otherwise, returns the result of object.__str__() (if defined)
 |  or repr(object).
 |  encoding defaults to sys.getdefaultencoding().
 |  errors defaults to 'strict'.
 |  
 |  Methods defined here:
 |  
 |  __add__(self, value, /)
 |      Return self+value.
 |  
 |  __contains__(self, key, /)
 |      Return key in self.
 |  
 |  __eq__(self, value, /)
 |      Return self==value.
 |  
 |  __format__(self, format_spec, /)
 |      Return a formatted version of the string as described by format_spec.
 |  
 |  __ge__(self, value, /)
 |      Return self>=value.
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __getitem__(self, key, /)
 |      Return self[key].
 |  
 |  __getnewargs__(...)
 |  
 |  __gt__(self, value, /)
 |      Return self>value.
 |  
 |  __hash__(self, /)
 |      Return hash(self).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __le__(self, value, /)
 |      Return self<=value.
 |  
 |  __len__(self, /)
 |      Return len(self).
 |  
 |  __lt__(self, value, /)
 |      Return self<value.
 |  
 |  __mod__(self, value, /)
 |      Return self%value.
 |  
 |  __mul__(self, value, /)
 |      Return self*value.
 |  
 |  __ne__(self, value, /)
 |      Return self!=value.
 |  
 |  __repr__(self, /)
 |      Return repr(self).
 |  
 |  __rmod__(self, value, /)
 |      Return value%self.
 |  
 |  __rmul__(self, value, /)
 |      Return value*self.
 |  
 |  __sizeof__(self, /)
 |      Return the size of the string in memory, in bytes.
 |  
 |  __str__(self, /)
 |      Return str(self).
 |  
 |  capitalize(self, /)
 |      Return a capitalized version of the string.
 |      
 |      More specifically, make the first character have upper case and the rest lower
 |      case.
 |  
 |  casefold(self, /)
 |      Return a version of the string suitable for caseless comparisons.
 |  
 |  center(self, width, fillchar=' ', /)
 |      Return a centered string of length width.
 |      
 |      Padding is done using the specified fill character (default is a space).
 |  
 |  count(...)
 |      S.count(sub[, start[, end]]) -> int
 |      
 |      Return the number of non-overlapping occurrences of substring sub in
 |      string S[start:end].  Optional arguments start and end are
 |      interpreted as in slice notation.
 |  
 |  encode(self, /, encoding='utf-8', errors='strict')
 |      Encode the string using the codec registered for encoding.
 |      
 |      encoding
 |        The encoding in which to encode the string.
 |      errors
 |        The error handling scheme to use for encoding errors.
 |        The default is 'strict' meaning that encoding errors raise a
 |        UnicodeEncodeError.  Other possible values are 'ignore', 'replace' and
 |        'xmlcharrefreplace' as well as any other name registered with
 |        codecs.register_error that can handle UnicodeEncodeErrors.
 |  
 |  endswith(...)
 |      S.endswith(suffix[, start[, end]]) -> bool
 |      
 |      Return True if S ends with the specified suffix, False otherwise.
 |      With optional start, test S beginning at that position.
 |      With optional end, stop comparing S at that position.
 |      suffix can also be a tuple of strings to try.
 |  
 |  expandtabs(self, /, tabsize=8)
 |      Return a copy where all tab characters are expanded using spaces.
 |      
 |      If tabsize is not given, a tab size of 8 characters is assumed.
 |  
 |  find(...)
 |      S.find(sub[, start[, end]]) -> int
 |      
 |      Return the lowest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Return -1 on failure.
 |  
 |  format(...)
 |      S.format(*args, **kwargs) -> str
 |      
 |      Return a formatted version of S, using substitutions from args and kwargs.
 |      The substitutions are identified by braces ('{' and '}').
 |  
 |  format_map(...)
 |      S.format_map(mapping) -> str
 |      
 |      Return a formatted version of S, using substitutions from mapping.
 |      The substitutions are identified by braces ('{' and '}').
 |  
 |  index(...)
 |      S.index(sub[, start[, end]]) -> int
 |      
 |      Return the lowest index in S where substring sub is found, 
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Raises ValueError when the substring is not found.
 |  
 |  isalnum(self, /)
 |      Return True if the string is an alpha-numeric string, False otherwise.
 |      
 |      A string is alpha-numeric if all characters in the string are alpha-numeric and
 |      there is at least one character in the string.
 |  
 |  isalpha(self, /)
 |      Return True if the string is an alphabetic string, False otherwise.
 |      
 |      A string is alphabetic if all characters in the string are alphabetic and there
 |      is at least one character in the string.
 |  
 |  isascii(self, /)
 |      Return True if all characters in the string are ASCII, False otherwise.
 |      
 |      ASCII characters have code points in the range U+0000-U+007F.
 |      Empty string is ASCII too.
 |  
 |  isdecimal(self, /)
 |      Return True if the string is a decimal string, False otherwise.
 |      
 |      A string is a decimal string if all characters in the string are decimal and
 |      there is at least one character in the string.
 |  
 |  isdigit(self, /)
 |      Return True if the string is a digit string, False otherwise.
 |      
 |      A string is a digit string if all characters in the string are digits and there
 |      is at least one character in the string.
 |  
 |  isidentifier(self, /)
 |      Return True if the string is a valid Python identifier, False otherwise.
 |      
 |      Use keyword.iskeyword() to test for reserved identifiers such as "def" and
 |      "class".
 |  
 |  islower(self, /)
 |      Return True if the string is a lowercase string, False otherwise.
 |      
 |      A string is lowercase if all cased characters in the string are lowercase and
 |      there is at least one cased character in the string.
 |  
 |  isnumeric(self, /)
 |      Return True if the string is a numeric string, False otherwise.
 |      
 |      A string is numeric if all characters in the string are numeric and there is at
 |      least one character in the string.
 |  
 |  isprintable(self, /)
 |      Return True if the string is printable, False otherwise.
 |      
 |      A string is printable if all of its characters are considered printable in
 |      repr() or if it is empty.
 |  
 |  isspace(self, /)
 |      Return True if the string is a whitespace string, False otherwise.
 |      
 |      A string is whitespace if all characters in the string are whitespace and there
 |      is at least one character in the string.
 |  
 |  istitle(self, /)
 |      Return True if the string is a title-cased string, False otherwise.
 |      
 |      In a title-cased string, upper- and title-case characters may only
 |      follow uncased characters and lowercase characters only cased ones.
 |  
 |  isupper(self, /)
 |      Return True if the string is an uppercase string, False otherwise.
 |      
 |      A string is uppercase if all cased characters in the string are uppercase and
 |      there is at least one cased character in the string.
 |  
 |  join(self, iterable, /)
 |      Concatenate any number of strings.
 |      
 |      The string whose method is called is inserted in between each given string.
 |      The result is returned as a new string.
 |      
 |      Example: '.'.join(['ab', 'pq', 'rs']) -> 'ab.pq.rs'
 |  
 |  ljust(self, width, fillchar=' ', /)
 |      Return a left-justified string of length width.
 |      
 |      Padding is done using the specified fill character (default is a space).
 |  
 |  lower(self, /)
 |      Return a copy of the string converted to lowercase.
 |  
 |  lstrip(self, chars=None, /)
 |      Return a copy of the string with leading whitespace removed.
 |      
 |      If chars is given and not None, remove characters in chars instead.
 |  
 |  partition(self, sep, /)
 |      Partition the string into three parts using the given separator.
 |      
 |      This will search for the separator in the string.  If the separator is found,
 |      returns a 3-tuple containing the part before the separator, the separator
 |      itself, and the part after it.
 |      
 |      If the separator is not found, returns a 3-tuple containing the original string
 |      and two empty strings.
 |  
 |  replace(self, old, new, count=-1, /)
 |      Return a copy with all occurrences of substring old replaced by new.
 |      
 |        count
 |          Maximum number of occurrences to replace.
 |          -1 (the default value) means replace all occurrences.
 |      
 |      If the optional argument count is given, only the first count occurrences are
 |      replaced.
 |  
 |  rfind(...)
 |      S.rfind(sub[, start[, end]]) -> int
 |      
 |      Return the highest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Return -1 on failure.
 |  
 |  rindex(...)
 |      S.rindex(sub[, start[, end]]) -> int
 |      
 |      Return the highest index in S where substring sub is found,
 |      such that sub is contained within S[start:end].  Optional
 |      arguments start and end are interpreted as in slice notation.
 |      
 |      Raises ValueError when the substring is not found.
 |  
 |  rjust(self, width, fillchar=' ', /)
 |      Return a right-justified string of length width.
 |      
 |      Padding is done using the specified fill character (default is a space).
 |  
 |  rpartition(self, sep, /)
 |      Partition the string into three parts using the given separator.
 |      
 |      This will search for the separator in the string, starting at the end. If
 |      the separator is found, returns a 3-tuple containing the part before the
 |      separator, the separator itself, and the part after it.
 |      
 |      If the separator is not found, returns a 3-tuple containing two empty strings
 |      and the original string.
 |  
 |  rsplit(self, /, sep=None, maxsplit=-1)
 |      Return a list of the words in the string, using sep as the delimiter string.
 |      
 |        sep
 |          The delimiter according which to split the string.
 |          None (the default value) means split according to any whitespace,
 |          and discard empty strings from the result.
 |        maxsplit
 |          Maximum number of splits to do.
 |          -1 (the default value) means no limit.
 |      
 |      Splits are done starting at the end of the string and working to the front.
 |  
 |  rstrip(self, chars=None, /)
 |      Return a copy of the string with trailing whitespace removed.
 |      
 |      If chars is given and not None, remove characters in chars instead.
 |  
 |  split(self, /, sep=None, maxsplit=-1)
 |      Return a list of the words in the string, using sep as the delimiter string.
 |      
 |      sep
 |        The delimiter according which to split the string.
 |        None (the default value) means split according to any whitespace,
 |        and discard empty strings from the result.
 |      maxsplit
 |        Maximum number of splits to do.
 |        -1 (the default value) means no limit.
 |  
 |  splitlines(self, /, keepends=False)
 |      Return a list of the lines in the string, breaking at line boundaries.
 |      
 |      Line breaks are not included in the resulting list unless keepends is given and
 |      true.
 |  
 |  startswith(...)
 |      S.startswith(prefix[, start[, end]]) -> bool
 |      
 |      Return True if S starts with the specified prefix, False otherwise.
 |      With optional start, test S beginning at that position.
 |      With optional end, stop comparing S at that position.
 |      prefix can also be a tuple of strings to try.
 |  
 |  strip(self, chars=None, /)
 |      Return a copy of the string with leading and trailing whitespace remove.
 |      
 |      If chars is given and not None, remove characters in chars instead.
 |  
 |  swapcase(self, /)
 |      Convert uppercase characters to lowercase and lowercase characters to uppercase.
 |  
 |  title(self, /)
 |      Return a version of the string where each word is titlecased.
 |      
 |      More specifically, words start with uppercased characters and all remaining
 |      cased characters have lower case.
 |  
 |  translate(self, table, /)
 |      Replace each character in the string using the given translation table.
 |      
 |        table
 |          Translation table, which must be a mapping of Unicode ordinals to
 |          Unicode ordinals, strings, or None.
 |      
 |      The table must implement lookup/indexing via __getitem__, for instance a
 |      dictionary or list.  If this operation raises LookupError, the character is
 |      left untouched.  Characters mapped to None are deleted.
 |  
 |  upper(self, /)
 |      Return a copy of the string converted to uppercase.
 |  
 |  zfill(self, width, /)
 |      Pad a numeric string with zeros on the left, to fill a field of the given width.
 |      
 |      The string is never truncated.
 |  
 |  ----------------------------------------------------------------------
 |  Static methods defined here:
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  maketrans(x, y=None, z=None, /)
 |      Return a translation table usable for str.translate().
 |      
 |      If there is only one argument, it must be a dictionary mapping Unicode
 |      ordinals (integers) or characters to Unicode ordinals, strings or None.
 |      Character keys will be then converted to ordinals.
 |      If there are two arguments, they must be strings of equal length, and
 |      in the resulting dictionary, each character in x will be mapped to the
 |      character at the same position in y. If there is a third argument, it
 |      must be a string, whose characters will be mapped to None in the result.

2.判斷字符串

  • 起一定判斷功能的字符串
  • islower/isupper
    • 判斷字符串是小寫字母還是大寫字母
    • 要求全部是小寫或者大寫才返回真值
  • isdigit
    • 判斷字符串是否是全部由數字組成
  • isalpha
    • 判斷字符串是否全部由字母組成
    • alpha 是指英文字母表裏的內容
# islower/isupper
s = "My first love is wwwwww"
s.islower()
False
s.isupper()
False
s
True
# isdigit
s.isdigit()
False
sss = "234232342342"
sss.isdigit()
True
s3 = "23423 is your qq?"
s3.isdigit()
False
# isalpha 空格不是alpha
s.isalpha()
False

sss.isalpha()
False
s5 = "SDFSFSDFSFSFDFGRER"
s5.isalpha()
True

3 操作類函數

  • lower/upper
    • 把字符串轉換成大小寫
  • strip/lstrip/rstrip
    • 去掉空格
  • swapcase
    • 字符串中的字符交換大小寫

字符串格式化

  • 字符串按照一定的格式進行打印或者填充
  • 格式化的分類:
    • 使用%進行格式化
    • 使用 format函數,近年來比較流行
# 字符串格式化例子
s = "My name is wdh, my age is 20,i am 170,60kg"
print(s)
My name is wdh, my age is 20
s = "My name is %s, my age is %d,i am %.2f,%dkg" % ('wdh',21,169,59)
print(s)
My name is wdh, my age is 21,i am 169.00,59kg
利用 % 進行格式化
# %s 表示簡單字符串
s = "My age is %s" % "wdh"
print(s)
My age is wdh
# 當只有一個需要替換的時候,可以省略括號
s = "My age is %s" % ("wdh")
print(s)
My age is wdh
# %d,表示一個數字(整數)
s = "my age is %d" % 28
s
'my age is 28'
# %d 只能表示整數。如果後邊實際內容是小數,則進行取整操作
# 取整是直接取整,捨棄後面的小數
s = "my age is %d" % 28.8
s
'my age is 28'
# %f 表示浮點小數
s = "i am %fkg" % 86.11
s
'i am 86.110000kg'
# 可以對小數的格式 進行限制,在字符f前如果出現 ‘.x’,其中x表示一個整數,則此時表示浮點數小數點後出現的位數
s = "i am %.2fkg" % 66.696
s
'i am 66.70kg'
s = "i am %.8fkg" % 66.696
s
'i am 66.69600000kg'
# 如果需要格式畫的信息多於一個,則用括號把數據括起來就行了
# 在字符串中表示%怎麼辦?
s = "sdfsf%sdfsdfs"
s
'sdfsf%sdfsdfs'

佔位符的種類:

  • %s 字符串
  • %r 字符串,但是是使用repr而不是str
  • %c 整數轉換爲單個字符
  • %d 十進制整數
  • %u 無符號整型
  • %o 表示八進制
  • %x 十六進制,字母爲小寫(x爲小寫)
  • %X 十六進制,字符爲大寫(X爲大寫)
  • %e 浮點數(E爲小寫),例如:2.87e+12
  • %E 浮點數(E爲大寫),例如:2.87E+12
  • %f,%F 浮點數十進制形式
  • %g,%G 十進制形式浮點或者指浮點自動轉換
  • 格式前面出現整數表示此佔位符所佔位置的寬度
  • % 格式字符前邊出現‘-’表示左對齊
  • % 格式字符前邊出現‘+’表示右對齊
  • 0位數不足用‘0’補齊
  • width表示寬度
  • pricision精度
"i am %10dlog" % 13
'i am         13log'
"i am %20s" % "sdfsdsd"
'i am              sdfsdsd'
"i am %-20s" % "sdfsdsd"
'i am sdfsdsd             '
"i am %010d" %22
'i am 0000000022'
"i am %7.4fkg" %86.43
'i am 86.4300kg'
#對於float前面的佔位寬不起作用
"i am %07.4fkg" %86.43
'i am 86.4300kg'

布爾變量

  • 表示真假,行或者不行,是或者不是
  • True/False
  • 在編程當中,需要大量判斷真假,是非,對錯
1 > 9
False
# 字符串可以拿來直接比較
"ff" > "b"
True
if ( 3 > 8 ):
    print("yes")
else:
    print("No")
No
True
True
b = False
b
False
# 如果布爾值作爲數字參與運算,那麼所有非0的數字都爲True,但是,反之如果True作爲數字參與運算的時候,True表示1
True * 3
3
False + 8
8
if 32:
    print("true")
true

None

  • 是一個特殊的常量
  • 不表示任何類型,通常用來佔位,或者變量解除綁定,None於任何其他的類型進行比較永遠返回False
  • 作用
    • 佔位
    • 解除變量綁定
# None的例子
a = 353
print(a)
a = None
print(a)
353
None
#None 必須正確書寫
a = none
print(a)
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-78-e6a2f46dd1c7> in <module>
      1 #None 必須正確書寫
----> 2 a = none
      3 print(a)


NameError: name 'none' is not defined

1-6 運算符

  • 運算符就是爲數據提供運算鏈接的符號

1.算術運算符

    • ,-,/,%,//,*
# + - *,三個符號跟我們日常生活中的符號含義一致
# 表達式:由一個數字或者其他對象或者多個數字或者對象和運算符構成,通常是讓計算機做一些事情並返回結果
a = 4+5 # 把4和5相加得出的值賦給a
print(a)
a = 7-2
print(a)
a= 8*6
print(a)
9
5
48
# '/'代表除法
# 在python2 和python3中有些區別,此處以python3爲準
# 兩數相除,結果爲浮點數
a = 4/2
a
2.0
a = 5/2
a
2.5
a = 5.3 / 2
a
2.65
a = 4/3
a
1.3333333333333333
# '//'(floor,地板除)
# 兩數相除,得到的結果取整
# 並不意味着得到的結果一定是整數
# 如兩整數正好結果爲整數,則得到的整數,否則出現浮點數
# 一下例子,量整數相除,結果正好除盡,得到整數結果
a = 4//2
a
2
#兩數中包含小數,結果爲浮點數
a = 4.0 // 2
a
2.0
# 兩整數相除,無論是否除盡,結果都是整數
a = 25//3
a
8
a = 25//3.0
a
8.0
# ‘%’表示取餘(取模,模)
# 5除以3 商1餘2
# 5除以2 商2餘1
7%3
1
14 % 5
4
3.125% 1.5
0.125
# ‘**’表示冪指數,求一個數的多少次冪
4**2
16
3**3
27
2**8
256

算數運算符的優先級

  • 三個等級
    1. **
    2. *,/,%,//
    3. +,-
  • 如果有括號,先計算括號內表達式
#1.先計算 4**2
#2.再計算3*16 和 5//2
#3.從左向右開始計算
2 - 3*4**2+5//2
-44
#優先計算6-5
2 - 3*4**(6-5)//2
-4
### 表達式中如果出現浮點數,整數等,則計算結果爲浮點數
# 算式中包含浮點數,則結果爲浮點數
3 + 6.8
9.8

練習:

  1. 溫度轉換(華氏溫度,攝氏溫度,開氏溫度)
    • 攝氏溫度:5.0/9.0*(華氏溫度-32)
    • 開氏溫度:5.0/9.0*(華氏溫度-32)+273.15
    • 今天攝氏溫度23度,求華氏溫度和開氏溫度
    • 審題:攝氏溫度23=5.0/9.0(華氏溫度-32)》239.0/5.0=華氏溫度-32》華氏溫度=23*9.0/5.0 + 32
    • 然後把求到的華氏溫度帶入開氏溫度公式,就可以求出開氏溫度
s = 23
h = s*9.0/5.0 + 32
k = 5.0/9.0*(h-32)+273.15
print("攝氏:%d" % s )
print("華氏溫度:%f" % h)
print("開氏溫度:%f" % k)
攝氏:23
華氏溫度:73.400000
開氏溫度:296.150000

2 賦值運算符

  • 爲python變量提供賦值運算功能的符號
  • =,+=,-=,/=,%=,**=,//=
# ‘=’,爲python變量提供基本的賦值功能
# 賦值符號的作用:
# 當沒有此變量時,創建一個變量,同時把變量綁定到這個對象上
# 當變量存在時,改變此變量關聯的對象
# 用變量訪問此變量關聯的對象
a = 32 #把32賦值給變量a
# python中允許批量賦值
#左右數量必須一致
#不同變量和值用逗號隔開
a,b,c=1,2,3
print(a)
print(b)
print(c)
1
2
3
#python允許兩個變量進行交換
a = 100
b = 200
print(a)
print(b)
100
200
a,b = b,a
print(a)
print(b)
200
100
# a+=b ==> a = a + b 
a = 1
a += 4
print(a)
5
# 其他符號以此類推

練習:面積體積求值

  • 半徑爲 r = 2.5cm的圓,求周長和麪積
  • 如果是球,求其體積
  • 分析:
    • 周長公式: l = 2* pi* r
    • 面積:m = pi x r^2
    • 體積: v = 4 x pi x r^3/3
# 作業練習
# 1.我們需要pi的值,最好用一個變量來表示
pi = 3.1415
r = 2.5
l = 2 * pi * r
m = pi * r ** 2
v = 4 * pi * r ** 3 / 3
print("周長:%f" % 1)
print("面積:%f" % m)
print("體積:%f" % v)
周長:1.000000
面積:19.634375
體積:65.447917

例子,求當前時間

  • 從今天00:00:00 起,已經過去了28762秒,求現在是幾時幾分幾秒
  • 分析:
    • 一個小時是3600秒
    • 一分鐘是60s
    • 如果我們知道總秒數,對小時的秒數求整就應該是小時,求餘就是剩下的分秒對應的秒數,"//"
    • 對剩下的秒數用60求整,就會的到分鐘數
    • 剩下的就是秒數
s_sum = 28762
clock_sec = 3600
minu_sec = 60
clock = s_sum // clock_sec
s_sum = s_sum % clock_sec
minu = s_sum // minu_sec
s_sum = s_sum % minu_sec
print("現在是 %d時 %d分 %d秒" % (clock,minu,s_sum))
現在是 7時 59分 22秒

3.比較運算符

  • 爲我們提供比較功能的運算符
  • 特點是:最後的結果是真或者假,即布爾值
    <,>,<=,>=,==,!=
  • 這些符號和C語言中的含義相同
# == 檢查操作是否等於
b = 4 == 6 # 先計算表達式,即對4==6進行判斷,然後判斷結果賦值給b
b
False

4 邏輯運算符

  • 邏輯運算就是 對布爾值進行運算
  • and,or,not
  • 邏輯運算的短路問題:
    • 在邏輯運算過程中,-旦結果已經確定,則不進行剩下的計算而是直接返回結果
# and 邏輯與
# 如果不能理解,可以把True看成數字1,False看做數字0,and就是乘號
True and False
False
True and True #可以理解爲左右布爾值相乘
True
a = 7
b = 2
c = 8
a < b and b > c
False
# or 邏輯或
# 可以把True看做數字1,False看做數字0,則or就應該被看做 + 號
False or True # 0 + 1
True
True or True #可以理解爲左右布爾值相加
True
# not 邏輯非
# True看做1,False看做0,則not看做取反
not True
False
### 特殊運算符
- is
- is not
- del
# is判斷兩個變量,對象是否是同一個
# 下面的例子,兩個變量具有同一個值,但是否指向/綁定同一個對象呢?
# 兩個對象/變量是否是is的依據是,id值是否一樣
a = 7897 #用的時候臨時創建
b = 7897
a is b # is 操作符返回布爾值
False
id(a) # 查看a綁定的對象的編號
140107648900080
id(b)
140107648900176
a = b
a is b
True
print(id(a))
print(id(b))
140107648900400
140107648900400
# Python 對一些初級的,常用的對象,放入內存中,供大家使用
a = 2 #一直在內存中,直接使用
b = 2 #一直在內存中,直接使用
a is b
True
print(id(a))
print(id(b))
94359883973696
94359883973696
# is not 跟is操作符正好相反
a is not b
False
# del 用於刪除變量,同事解除與對象的關聯,如果可能則釋放對象
print(b)
2
# 因爲已經把b刪除掉了(釋放內存),所以再次使用b的時候,出現name error
del b
print(b)
# 如果 有多個變量使用同一個id則 del操作不會真正刪除掉id
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-143-9a0533abae4f> in <module>
      1 # 因爲已經把b刪除掉了(釋放內存),所以再次使用b的時候,出現name error
----> 2 del b
      3 print(b)
      4 # 如果 有多個變量使用同一個id則 del操作不會真正刪除掉id


NameError: name 'b' is not defined
a = b = 4
print(a)
print(id(a))
print(b)
print(id(b))
del b
print(a)
print(id(a))
print(b)
print(id(b))
4
94359883973760
4
94359883973760
4
94359883973760



---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-144-9e6261ff1f70> in <module>
      7 print(a)
      8 print(id(a))
----> 9 print(b)
     10 print(id(b))


NameError: name 'b' is not defined
# 基本輸入輸出
- input
- print
# input: 從標準設備讀取一個字符串,在python裏末尾的換行符會被自動刪除
# 標準輸入設備:一般指鍵盤
# 標準輸出設備:屏幕
input("請輸入您的年齡,按回車鍵結束:")
請輸入您的年齡,按回車鍵結束:20





'20'
age = input("請輸入您的年齡,按回車鍵結束:") # 輸入的內容賦給age,這裏輸入的內容是被作爲字符串處理的,所以age是個字符串
print("您的年齡是 %s" % age)
請輸入您的年齡,按回車鍵結束:20
您的年齡是 20
print("您的年齡是 %d" % age)
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-147-346aa7de2c39> in <module>
----> 1 print("您的年齡是 %d" % age)


TypeError: %d format: a number is required, not str
# print 輸出/打印信息到標準輸出設備
print("my name is wdh")
my name is wdh
print("My age is: ",28)
My age is:  28
print("My age is: ",28,'sdfssfgdf')
My age is:  28 sdfssfgdf

分支語句

  • 程序可以由種結構組成全部:程序結構 = 順序 + 分支 + 循環
  • 順序:程序從上到下一行一行執行,一行執行完之後纔會繼續下一個行
  • 分支:通過一個判斷條件,不同的結果對應不同的處理程序段
  • 循環:多次重複執行相同的或者相似的代碼

if 語句

  • 判斷一個條件,當條件成立,則執行相應的程序代碼段
  • 語法如下:
    if (條件表達式) :
    程序處理模塊
  • python 用縮進來表示程序結構或者代碼的層級關係
    • 可以使用tab鍵或者空格
    • 一個tab鍵表示幾個空格可以設置
    • python2中,只要空格數相等就可以,tab和空格可以混用
    • python3中,不能混用,要麼用空格,要麼用tab,一般推薦使用tab
# 例子,假如 3< 56,則打印出字符串“True”
if( 3<56 ):
    print("True")
True
if( 3>56 ):
    print("True")
# pass語句,佔位符號,不執行任何語句,不起任何實際作用
if (3<9):
    pass
# if 語句案例
# 老師對大家的考試的程序進行評定,採用ABCDE五級進行評定,A是最好成績
# 如果90分(包括此分數)以上,則輸出A
# 如果80分(包括此分數)以上,則輸出B
# 如果70分(包括此分數)以上,則輸出C
# 如果60分(包括此分數)以上,則輸出D
# 其餘,則輸出E
# 考試程序,由自己給出,存入變量
#以下代碼 不符合題目要求
score = 87
if (score>=90):
    print("A")
if (score>=80):
    print("B")
if (score>=70):
    print("C")
if (score>=60):
    print("D")
if (score<60):
    print("E")
B
C
D
# 以下代碼滿足要求
score = 87
if (score>=90):
    print("A")
if (score>=80 and score<90):
    print("B")
if (score>=70 and score<80):
    print("C")
if (score>=60 and score<70):
    print("D")
if (score<60):
    print("E")
B

if…else…

  • 假如條件滿足,則執行if後面的語句,否則,執行else後面的語句
# 判斷一個學生多成績,如果大於60分,則學生成績及格,否則,重考
score = input("請輸入您的成績:") 
#此處輸入內容被作爲字符串處理了,所以使用score時需要轉換
#score = int(score)
if(score>=60):
    print("您已經及格!")
else:
    print("對不起,您需要重考!")
請輸入您的成績:20



---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-3-7ab17da7d300> in <module>
      3 #此處輸入內容被作爲字符串處理了,所以使用score時需要轉換
      4 #score = int(score)
----> 5 if(score>=60):
      6     print("您已經及格!")
      7 else:


TypeError: '>=' not supported between instances of 'str' and 'int'
#重新寫:
score = input("請輸入您的成績:") 
#此處輸入內容被作爲字符串處理了,所以使用score時需要通過int對象把字符串轉換成整數數字
score = int(score)
if(score>=60):
    print("您已經及格!")
else:
    print("對不起,您需要重考!")
請輸入您的成績:20
對不起,您需要重考!
# 輸入學生成績,大於等於90則輸出A,否則判斷是否大於60,如果大於60則輸出及格,否則輸出不及格
score = input("請輸入您的成績:") 
#此處輸入內容被作爲字符串處理了,所以使用score時需要通過int對象把字符串轉換成整數數字
score = int(score)
if(score>=90) :
    print("A")
    print("Your are the best!")
    print("Thank you!")
else :
    if(score>=60):
        print("成績及格")
    else:
        print("成績不及格")
請輸入您的成績:20
成績不及格
### else 跟誰配對?
score = 87
if ( score > 90 ):
    if(score>95):
        print("Your are the best")
else:
    print("just soso")
just soso

練習:if語句後者if…else語句,模擬上海出租車收費系統

  1. 3公里以內,收費基本起步費用 13元
  2. 超出3公里,則2.3元/km
  3. 空駛費,超出15公里,每公里加收單價的50%空駛費,即 3.45元/km
  4. 要求:輸入駕駛里程後計算費用
#1. 要求用戶輸入總里程等於3km,則輸出13元
#3. 如果大於3km並且小於等於15km,則收取13 + (里程數-3)*2.3
#4. 如果大於15公里,則13 + 12*2.3 + (里程數-15)*3.45
#5. 輸出費用
km = input("請輸入行駛里程數:")
km = int(km)
if(km<=3):
    cost = 13
    print("費用:%0.2f" % cost)
else:
    if(km<=15):
        cost = 13+(km-3)*2.3
        print("費用:%0.2f" % cost)
    else:
        cost = 13+12*2.3+(km-15)*3.45
        print("費用:%0.2f" % cost)
請輸入行駛里程數:20
費用:57.85

三元操作符

  • 元:操作數的意思,所謂三元,就是一個操作符帶動三個操作數一起運算
  • 原本沒有python沒有三元運算符
  • 語法: x if 條件 ele y
# 三元運算符示例
a = 34 if 3<5 else 1
a
34
a = 34 if 3>5 else 1
a
1

作業:三元運算符

  1. a,b兩數由用戶輸入
  2. 比較大小,把最大值存入變量c
# 分析:
# 1.用戶輸入可以用input函數,然後用int轉換
# 2. 比較兩個數,把最大值存入c
a = input("請輸入數字A:")
a = int(a)
b = int(input("請輸入數字B:"))
c = a if a>b else b
c
請輸入數字A:35
請輸入數字B:22





35
### 要求用三元運算符求最大值
- 要求:
1. a,b,c由用戶輸入是哪個
2. 比較大小,最大值輸出
a = int(input("請輸入A:"))
b = int(input("請輸入B:"))
c = int(input("請輸入C:"))
e = (a if a>b else b)
d = (e if e>c else c)
d
請輸入A:12
請輸入B:45
請輸入C:6





45

前提只是

list

  • 列表:用來盛放/表示一串性質相同或者相似的數據,這些數據組成有序的一種排序方式
  • 一個列表可以盛放:數字,字符串,列表,或者其他複雜的結構
# 列表定義
# 直接表示列表,需要用中括號括起來,中間數據用逗號隔開
L1 = [1,2,3,4,5]
L1
[1, 2, 3, 4, 5]
L2 = [5,1,"你好!",6.8,[3,6,8]]
L2
[5, 1, '你好!', 6.8, [3, 6, 8]]

range

  • 一個函數
  • 產生一個有規律的由數字組成的列表
  • 使用包含三個參數: range(start,end,step)
  • start: 開始數字,以後生成列表裏,包含這個數字作爲第一個數字,默認爲0
  • end: 結束數字,這個數字不包含在range生成的列表裏,例如range(1,5) 就是生成[1,2,3,4],不包含end
  • step: 步長,即每次增加多少,默認爲1
  • python2: range生成結果就是列表,同時有xrange函數,功能類似
  • python3:沒有xrange,生成的結果就是迭代器,不是列表,教學上爲了易於理解,初步認爲是生成的列表
a = range(1,6)
# a==[1,2,3,4,5]
a = range(2,12,3)
# a==[2,5,8,11]

For循環

  • 程序三個結構:順序,分支,循環
  • 循環:重複做一些性質相同或者相似的事情
  • Python循環:for,while
  • for:用關鍵字for來表示
  • for循環特點:有一個清晰的循環次數,或者清晰的循環結束標誌等
  • 語法:
    for i in xxx:
    循環語句模塊
L1 = [1,2,3,4,5]
# 對於在L1中每一個元素,我們給這個元素臨時用變量idx表示,執行打印操作
for idx in L1:
    print(idx)
1
2
3
4
5
#列表由range函數生成
L2 = range(1,6) # 這裏不包含6
for idx in L2:
    print(idx)
1
2
3
4
5

作業: 1-50的數求和

  1. 1-50的數字增長有規律,次數明確
  2. 是個for循環
  3. 列表適合用range生成
# 生成存放結果的變量
mySum = 0
for idx in range(1,51):
    mySum += idx
print(mySum)
1275

while循環

  • 當滿足一定條件的時候才循環,具體循環多少次數沒有具體規定或者規劃
  • 語法:
    while(循環條件):
    循環體

示例:銀行利息

  • 10000本金
  • 每年利息收入7%
  • 多少年後本金會超過12000
  • 分析:
    • 循環問題
    • 沒有明確循環次數
    • 循環條件確定:本金不超過13000
    • while
# 讓我們求年限,我們用一個變量來存儲答案並初始化
year = 0
money = 10000
while(money<=13000):
    money *= (1 + 0.07 )
    year += 1
print("Year is %d" % year)
Year is 4

示例:累加求和

  • 1_50 累加求和
  • while 循環必須用
  • 分析:
    • 用計數來表示數字,從1開始,每次增長1,只要小於51,就把數字和總和相加
    • 循環條件:n 小於51
    • 每次n都要增加1
    • 每次n都要跟綜合相加
# 存放綜合
mySum = 0
# 計數器
n = 1
while n < 51 :
    mySum += n
    n+= 1
print("Summary is %d" % mySum)
Summary is 1275

break語句

  • 英文原意就是中斷循環的意思,在python中,保持了英文的原意
  • 無條件終止循環並跳出循環體

示例:

  • 在50_100之間查找第一個可以被9整除的數
  • 對於此類業務,優先選用for
  • 要求找到第一個==>找到第一個就行該退出
  • 退出==>break
for idx in range(50,101):
    # 被9整除如何表示?
    # 如果用9取餘等於0,則表示能被整除
    print(idx)
    if(idx % 9)==0:
        print(idx)
        break
50
51
52
53
54
54

對於嵌套多重訓話你,break語句值退出跟他最近的一次循環

練習: 輸出9*9乘法表

  • 如果相乘的積大於36,則不需要顯示
  • 乘法表是一個典型的雙重for循環結構
  • 如果乘積大於36,我們結束本輪循環
  • 結束用break
# 不能使用print語句,因爲print語句默認輸出後悔換行
# 在sys模塊中有write可以使用
import sys
# 負責乘法表的行數
for i in range(1,10):
    #負責乘法表列數的循環
    for j in range(1,10):
        if(i*j>36):
            break;
        sys.stdout.write(str(i*j))
        sys.stdout.write("\t")
    sys.stdout.write("\n")#此處用print打印空格也可以起到換行效果,print(" ")
1	2	3	4	5	6	7	8	9	
2	4	6	8	10	12	14	16	18	
3	6	9	12	15	18	21	24	27	
4	8	12	16	20	24	28	32	36	
5	10	15	20	25	30	35	
6	12	18	24	30	36	
7	14	21	28	35	
8	16	24	32	
9	18	27	36	

continue語句

  • continue 含義:繼續循環
  • 使用環境:當我們已經確定不需要繼續本輪循環的時候使用

案例:累加求和

  • 1_100累加求和
  • 只有當數字爲奇數的時候才累加
  • 分析:
    • 累加求和==>for循環
    • 奇數==>n%2!=0
    • 奇數就累加,偶數就進行下一輪循環
mySum = 0
for idx in range(1,100):
    if idx % 2 ==0 :
        # continue繼續的含義就是繼續下一輪循環
        continue
    mySum += idx
print(mySum)
2500
# 要求:乘法表中所有乘積小於12的數字打印出來
for i in range(1,10):
    for j in range(1,10):
        n = i*j
        if n > 12:
            continue
        sys.stdout.write(str(n))
        sys.stdout.write("\t")
    sys.stdout.write("\n")
1	2	3	4	5	6	7	8	9	
2	4	6	8	10	12	
3	6	9	12	
4	8	12	
5	10	
6	12	
7	
8	
9	

函數

  • 能完成一定邏輯業務功能的程序塊(一堆程序代碼),是程序模塊的一個單位
  • 作用:
    • 代碼組織
    • 代碼複用
  • 幾個函數:
    • 函數名/函數定義
    • 參數
    • 返回值
# 函數定義
def funcName():
    print("這是我的第一個函數")
# 函數的調用
# 調用直接用函數的名稱,有參數的輸入參數,沒有用空括號
funcName()
這是我的第一個函數
def funcOne():
    for idx in range(1,6):
        print(idx)
funcOne()
1
2
3
4
5

函數返回值 return 語句

  • 表示無條件結束函數並返回結果
  • 約定,任一函數應該都有return 語句表示結束,可以說 return None
# return 例子
# 定義函數,表示兩個數相加,則返回相加的和
def getSum(one,two):
    return one + two

summ = getSum(33,66)
summ
99

參數

  • 在函數中,用來佔位具有一定表示意義的變量名
  • 分類:
    • 形參:形式參數簡稱
    • 實參:實際參數的簡稱
# 函數參數舉例
# 在函數定義的時候,參數沒有具體的值,他的主要作用是佔據位置
# 我們稱之爲形參
def func01(name):
    print("My name is %s" % name)

func01("wdh")
My name is wdh

關鍵字參數

  • 對參數進行別名設置,同時使參數具有了默認值
  • 可以忽略參數的順序
def func02(name,food):
    print(name+" likes eat "+ food)
func02("wdh","apple")
wdh likes eat apple
func02("apple","wdh")
apple likes eat wdh
func02(food="cake",name="wdh")
wdh likes eat cake
### 默認參數
- 參數在定義的時候帶默認值
func02("wdh")
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-78-dd81ebb8ac58> in <module>
----> 1 func02("wdh")


TypeError: func02() missing 1 required positional argument: 'food'
# 默認參數的定義
# 默認參數需要使用關鍵字參數,語法格式爲arg=xxx
# 默認參數必須放在參數列表後邊,且默認參數後不得再有普通參數

# 定義一個函數,函數功能爲:顯示誰取的了多少成績
def func03(name,score=60):
    if(score>=60):
        print("恭喜 %s 考了%d" % (name,score) )
    else:
        print("遺憾 %s 考了%d" % (name,score) )
func03("wdh")
恭喜 wdh 考了60
func03("wdh",99)
恭喜 wdh 考了99
func03("wdh",12)
遺憾 wdh 考了12
#以下寫法錯誤,一旦用了非default參數不能跟在default參數後面
def func05(arg0=0,arg1=1,arg2=2,arg3):
    print(arg0,arg1,arg2,arg3)
  File "<ipython-input-87-4e1747f81251>", line 2
    def func05(arg0=0,arg1=1,arg2=2,arg3):
              ^
SyntaxError: non-default argument follows default argument

序列參數,字典參數

  • 列表參數:所有參數作爲一個列表傳入
  • 字典參數:參數作爲一個字典傳入
def myFunc01(a,b,c):
    print("This is a example for para")
    print("Value of a is %s" % a)
    print("Value of a is %s" % b)
    print("Value of a is %s" % c)
    
myFunc01("one","two","three")
This is a example for para
Value of a is one
Value of a is two
Value of a is three
# 把實參作爲列表傳入
p1 = ["one","two","three"]
# 如果把列表直接傳入,則解釋器認爲你只傳入了一個參數
myFunc01(p1)
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-123-b74647d45fd8> in <module>
      2 p1 = ["one","two","three"]
      3 # 如果把列表直接傳入,則解釋器認爲你只傳入了一個參數
----> 4 myFunc01(p1)


TypeError: myFunc01() missing 2 required positional arguments: 'b' and 'c'
# 如果所有的參數都放入一個列表中,則需要特殊表示出來
# 序列的長度必須與形參個數相同
# 序列位置信息對應相應的參數信息
myFunc01(*p1)
This is a example for para
Value of a is one
Value of a is two
Value of a is three
# 嘗試把所有的參數都放入字典中傳入
# 字典的長度必須與形參的個數相同
# 字典的鍵必須對應函數的形參,鍵作爲字符串類型(字典的鍵和形參的名稱必須相同,而排列順序可以不同)
# 字典的值傳遞給鍵對應的參數
d = {"a":"one","b":"two","c":"three"}
myFunc01(**d)
This is a example for para
Value of a is one
Value of a is two
Value of a is three
d1 = {"b":"two","a":"one","c":"three"}
myFunc01(**d1)
This is a example for para
Value of a is one
Value of a is two
Value of a is three

星號元組形參,只需要定義一個*元組形參,則可以傳入的參數個數不限制

  • 星號元組參數
  • 語法:
    def 函數名(*元組形參):
    語句塊
# 定義星號元組參數函數
def func(*arg):
    print("進入星號元組函數")
    print(arg)
# 如果不輸入實參,則函數認爲你給了一個空列表
# 如果輸入實參,函數自動把實參打包放入列表,然後傳入
func()
進入星號元組函數
()
func("wdh")
進入星號元組函數
('wdh',)
func("wdh","wdddd")
進入星號元組函數
('wdh', 'wdddd')

雙星號字典參數

  • 把傳入參數打包成字典傳入
  • 語法:
    def 函數名(**字典形參)
    函數體
# 定義一個雙星號字典參數函數例子
def func1(**args):
    print("進入雙星號字典函數參數")
    print(args)
func1()
進入雙星號字典函數參數
{}
# 雙星號字典參數對應的是關鍵字參數
func1("one","two")
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-117-d9b5e354d530> in <module>
      1 # 雙星號字典參數對應的是關鍵字參數
----> 2 func1("one","two")


TypeError: func1() takes 0 positional arguments but 2 were given
func1(a="one",b="two")
進入雙星號字典函數參數
{'a': 'one', 'b': 'two'}

不定長參數說明:

  • 位置形參,星號列表形參,雙星號字典形參可以混用
  • 如果混合使用,則順序必須爲位置形參,星號列表形參,雙星號字典形參

函數返回值

  • 返回值一般會有,用return語句返回值
  • 函數的類型,一般就是返回值的類型
  • 不返回數據可以沒有return,不建議去掉
  • 如果不返回值,則默認返回None
  • 函數可以返回複雜類型,也可以一次返回多個值
# 如果沒有return 則也返回None
def func1(one):
    print("The first func")
    return
func1(999)
The first func
rst = func1(0)
print(rst)
The first func
None
def func2(two):
    print("The second func")
rst = func2(33)
print(rst)
The second func
None
def func3(one,two):
    three = one + two
    print(three)
    return three
rst = func3(33,66)
print(rst)
99
99
# 返回多個值的函數
# 多個返回值直接用逗號隔開
def func4(one,two):
    one += 100
    two += 100
    three = one + two
    return one,two,three
# 對返回多個值得函數調用
# 如果返回值放入一個變量中,則默認此變量爲tuple類型,即多個返回值自動打包成tuple
rst = func4(23,32)
print(rst)
type(rst)
(123, 132, 255)





tuple
o,t,h = func4(23,88)
print(o,t,h)
type(t)
123 188 311





int
# 多個返回值函數接收只能是一個tuple類型或者相同數量的變量列表
one,two = func4(23,88)
print(one,two)
---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

<ipython-input-146-41ea7bf604e7> in <module>
      1 # 多個返回值函數接收只能是一個tuple類型或者相同數量的變量列表
----> 2 one,two = func4(23,88)
      3 print(one,two)


ValueError: too many values to unpack (expected 2)

函數文檔

  • 函數文檔在函數開頭起一定說明性的一段文字
# 函數文檔的例子
def func5(one):
    '''這是一個函數文檔的例子
    勝多負少發是電風扇
    勝多負少是gfgdf
    '''
    print("The first func")
    return one
func5(1)
The first func





1
# 通過查看__doc__屬性可以查看函數定義的doc內容
func5.__doc__ # doc前後都是兩個下劃線
'這是一個函數文檔的例子\n    勝多負少發是電風扇\n    勝多負少是gfgdf\n    '
# 函數定義的文檔會出現在help函數結果中,供用戶查看
help(func5)
Help on function func5 in module __main__:

func5(one)
    這是一個函數文檔的例子
    勝多負少發是電風扇
    勝多負少是gfgdf

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章