欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python簡明入門教程

 更新時間:2015年08月04日 12:11:15   作者:Cobra  
這篇文章主要介紹了Python簡明入門教程,較為詳細的分析了Python的基本概念及語法基礎(chǔ),有助于Python初學者更好的掌握Python的基本語法與使用技巧,需要的朋友可以參考下

本文實例講述了Python簡明入門教程。分享給大家供大家參考。具體如下:

一、基本概念

1、數(shù)

在Python中有4種類型的數(shù)——整數(shù)、長整數(shù)、浮點數(shù)和復數(shù)。
(1)2是一個整數(shù)的例子。
(2)長整數(shù)不過是大一些的整數(shù)。
(2)3.23和52.3E-4是浮點數(shù)的例子。E標記表示10的冪。在這里,52.3E-4表示52.3 * 10-4。
(4)(-5+4j)和(2.3-4.6j)是復數(shù)的例子。

2、字符串

(1)使用單引號(')
(2)使用雙引號(")
(3)使用三引號('''或""")
利用三引號,你可以指示一個多行的字符串。你可以在三引號中自由的使用單引號和雙引號。例如:

'''This is a multi-line string. This is the first line.
This is the second line.
"What's your name?," I asked.
He said "Bond, James Bond."
'''

(4)轉(zhuǎn)義符
(5)自然字符串
自然字符串通過給字符串加上前綴r或R來指定。例如r"Newlines are indicated by \n"。

3、邏輯行與物理行
一個物理行中使用多于一個邏輯行,需要使用分號(;)來特別地標明這種用法。一個物理行只有一個邏輯行可不用分號

二、控制流

1、if

塊中不用大括號,條件后用分號,對應(yīng)elif和else

if guess == number:
  print 'Congratulations, you guessed it.' # New block starts here
elif guess < number:
  print 'No, it is a little higher than that' # Another block
else:
  print 'No, it is a little lower than that'

2、while

用分號,可搭配else

while running:
  guess = int(raw_input('Enter an integer : '))
  if guess == number:
    print 'Congratulations, you guessed it.'
    running = False # this causes the while loop to stop
  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.'
  # Do anything else you want to do here

3、for
用分號,搭配else

for i in range(1, 5):
  print i
else:
  print 'The for loop is over'

4、break和continue
同C語言

三、函數(shù)

1、定義與調(diào)用

def sayHello():
  print 'Hello World!' # block belonging to the function
sayHello() # call the function

2、函數(shù)形參
類C語言

def printMax(a, b):
  if a > b:
    print a, 'is maximum'
  else:
    print b, 'is maximum'

3、局部變量
加global可申明為全局變量

4、默認參數(shù)值

def say(message, times = 1):
  print message * times

5、關(guān)鍵參數(shù)
如果某個函數(shù)有許多參數(shù),而只想指定其中的一部分,那么可以通過命名來為這些參數(shù)賦值——這被稱作 關(guān)鍵參數(shù) ——使用名字(關(guān)鍵字)而不是位置來給函數(shù)指定實參。這樣做有兩個 優(yōu)勢 ——一,由于不必擔心參數(shù)的順序,使用函數(shù)變得更加簡單了。二、假設(shè)其他參數(shù)都有默認值,可以只給我們想要的那些參數(shù)賦值。

def func(a, b=5, c=10):
  print 'a is', a, 'and b is', b, 'and c is', c
func(3, 7)
func(25, c=24)
func(c=50, a=100)

6、return

四、模塊

1、使用模塊

import sys
print 'The command line arguments are:'
for i in sys.argv:
  print i

如果想要直接輸入argv變量到程序中(避免在每次使用它時打sys.),可以使用from sys import argv語句

2、dir()函數(shù)
可以使用內(nèi)建的dir函數(shù)來列出模塊定義的標識符。標識符有函數(shù)、類和變量。

五、數(shù)據(jù)結(jié)構(gòu)

1、列表

shoplist = ['apple', 'mango', 'carrot', 'banana']
print 'I have', len(shoplist),'items to purchase.'
print 'These items are:', # Notice the comma at end of the line
for item in shoplist:
  print item,
print '\nI also have to buy rice.'
shoplist.append('rice')
print 'My shopping list is now', shoplist
print 'I will sort my list now'
shoplist.sort()
print 'Sorted shopping list is', shoplist
print 'The first item I will buy is', shoplist[0]
olditem = shoplist[0]
del shoplist[0]
print 'I bought the', olditem
print 'My shopping list is now', shoplist

2、元組
元組和列表十分類似,只不過元組和字符串一樣是不可變的即你不能修改元組。

zoo = ('wolf', 'elephant', 'penguin')
print 'Number of animals in the zoo is', len(zoo)
new_zoo = ('monkey', 'dolphin', zoo)
print 'Number of animals in the new zoo is', len(new_zoo)
print 'All animals in new zoo are', new_zoo
print 'Animals brought from old zoo are', new_zoo[2]
print 'Last animal brought from old zoo is', new_zoo[2][2]

像一棵樹

元組與打印

age = 22
name = 'Swaroop'
print '%s is %d years old' % (name, age)
print 'Why is %s playing with that python?' % name

3、字典

類似哈希

ab = {    'Swaroop'  : 'swaroopch@byteofpython.info',
       'Larry'   : 'larry@wall.org',
       'Matsumoto' : 'matz@ruby-lang.org',
       'Spammer'  : 'spammer@hotmail.com'
   }
print "Swaroop's address is %s" % ab['Swaroop']
# Adding a key/value pair
ab['Guido'] = 'guido@python.org'
# Deleting a key/value pair
del ab['Spammer']
print '\nThere are %d contacts in the address-book\n' % len(ab)
for name, address in ab.items():
  print 'Contact %s at %s' % (name, address)
if 'Guido' in ab: # OR ab.has_key('Guido')
  print "\nGuido's address is %s" % ab['Guido']

4、序列

列表、元組和字符串都是序列。序列的兩個主要特點是索引操作符和切片操作符。

shoplist = ['apple', 'mango', 'carrot', 'banana']
# Indexing or 'Subscription' operation
print 'Item 0 is', shoplist[0]
print 'Item 1 is', shoplist[1]
print 'Item -1 is', shoplist[-1]
print 'Item -2 is', shoplist[-2]
# Slicing on a list
print 'Item 1 to 3 is', shoplist[1:3]
print 'Item 2 to end is', shoplist[2:]
print 'Item 1 to -1 is', shoplist[1:-1]
print 'Item start to end is', shoplist[:]
# Slicing on a string
name = 'swaroop'
print 'characters 1 to 3 is', name[1:3]
print 'characters 2 to end is', name[2:]
print 'characters 1 to -1 is', name[1:-1]
print 'characters start to end is', name[:]

5、參考

當你創(chuàng)建一個對象并給它賦一個變量的時候,這個變量僅僅參考那個對象,而不是表示這個對象本身!也就是說,變量名指向你計算機中存儲那個對象的內(nèi)存。這被稱作名稱到對象的綁定。

print 'Simple Assignment'
shoplist = ['apple', 'mango', 'carrot', 'banana']
mylist = shoplist # mylist is just another name pointing to the same object!
del shoplist[0]
print 'shoplist is', shoplist
print 'mylist is', mylist
# notice that both shoplist and mylist both print the same list without
# the 'apple' confirming that they point to the same object
print 'Copy by making a full slice'
mylist = shoplist[:] # make a copy by doing a full slice
del mylist[0] # remove first item
print 'shoplist is', shoplist
print 'mylist is', mylist
# notice that now the two lists are different

6、字符串

name = 'Swaroop' # This is a string object
if name.startswith('Swa'):
  print 'Yes, the string starts with "Swa"'
if 'a' in name:
  print 'Yes, it contains the string "a"'
if name.find('war') != -1:
  print 'Yes, it contains the string "war"'
delimiter = '_*_'
mylist = ['Brazil', 'Russia', 'India', 'China']
print delimiter.join(mylist)  //用delimiter來連接mylist的字符

六、面向?qū)ο蟮木幊?/strong>

1、self

Python中的self等價于C++中的self指針和Java、C#中的this參考

2、創(chuàng)建類

class Person:
  pass # An empty block
p = Person()
print p

3、對象的方法

class Person:
  def sayHi(self):
    print 'Hello, how are you?'
p = Person()
p.sayHi()

4、初始化

class Person:
  def __init__(self, name):
    self.name = name
  def sayHi(self):
    print 'Hello, my name is', self.name
p = Person('Swaroop')
p.sayHi()

5、類與對象的方法

類的變量 由一個類的所有對象(實例)共享使用。只有一個類變量的拷貝,所以當某個對象對類的變量做了改動的時候,這個改動會反映到所有其他的實例上。
對象的變量 由類的每個對象/實例擁有。因此每個對象有自己對這個域的一份拷貝,即它們不是共享的,在同一個類的不同實例中,雖然對象的變量有相同的名稱,但是是互不相關(guān)的。

class Person:
  '''Represents a person.'''
  population = 0
  def __init__(self, name):
    '''Initializes the person's data.'''
    self.name = name
    print '(Initializing %s)' % self.name
    # When this person is created, he/she
    # adds to the population
    Person.population += 1

population屬于Person類,因此是一個類的變量。name變量屬于對象(它使用self賦值)因此是對象的變量。

6、繼承

class SchoolMember:
  '''Represents any school member.'''
  def __init__(self, name, age):
    self.name = name
class Teacher(SchoolMember):
  '''Represents a teacher.'''
  def __init__(self, name, age, salary):
    SchoolMember.__init__(self, name, age)
    self.salary = salary

七、輸入輸出

1、文件

f = file('poem.txt', 'w') # open for 'w'riting
f.write(poem) # write text to file
f.close() # close the file
f = file('poem.txt')
# if no mode is specified, 'r'ead mode is assumed by default
while True:
  line = f.readline()
  if len(line) == 0: # Zero length indicates EOF
    break
  print line,
  # Notice comma to avoid automatic newline added by Python
f.close() # close the file

2、存儲器

持久性

import cPickle as p
#import pickle as p
shoplistfile = 'shoplist.data'
# the name of the file where we will store the object
shoplist = ['apple', 'mango', 'carrot']
# Write to the file
f = file(shoplistfile, 'w')
p.dump(shoplist, f) # dump the object to a file
f.close()
del shoplist # remove the shoplist
# Read back from the storage
f = file(shoplistfile)
storedlist = p.load(f)
print storedlist

3、控制臺輸入

輸入字符串 nID = raw_input("Input your id plz")
輸入整數(shù) nAge = int(raw_input("input your age plz:\n"))
輸入浮點型 fWeight = float(raw_input("input your weight\n"))
輸入16進制數(shù)據(jù) nHex = int(raw_input('input hex value(like 0x20):\n'),16)
輸入8進制數(shù)據(jù) nOct = int(raw_input('input oct value(like 020):\n'),8)

八、異常

1、try..except

import sys
try:
  s = raw_input('Enter something --> ')
except EOFError:
  print '\nWhy did you do an EOF on me?'
  sys.exit() # exit the program
except:
  print '\nSome error/exception occurred.'
  # here, we are not exiting the program
print 'Done'

2、引發(fā)異常

使用raise語句引發(fā)異常。你還得指明錯誤/異常的名稱和伴隨異常 觸發(fā)的 異常對象。你可以引發(fā)的錯誤或異常應(yīng)該分別是一個Error或Exception類的直接或間接導出類。

class ShortInputException(Exception):
  '''A user-defined exception class.'''
  def __init__(self, length, atleast):
    Exception.__init__(self)
    self.length = length
    self.atleast = atleast
raise ShortInputException(len(s), 3)

3、try..finnally

import time
try:
  f = file('poem.txt')
  while True: # our usual file-reading idiom
    line = f.readline()
    if len(line) == 0:
      break
    time.sleep(2)
    print line,
finally:
  f.close()
  print 'Cleaning up...closed the file'

九、Python標準庫

1、sys庫

sys模塊包含系統(tǒng)對應(yīng)的功能。sys.argv列表,它包含命令行參數(shù)。

2、os庫

os.name字符串指示你正在使用的平臺。比如對于Windows,它是'nt',而對于Linux/Unix用戶,它是'posix'。
os.getcwd()函數(shù)得到當前工作目錄,即當前Python腳本工作的目錄路徑。
os.getenv()和os.putenv()函數(shù)分別用來讀取和設(shè)置環(huán)境變量。
os.listdir()返回指定目錄下的所有文件和目錄名。
os.remove()函數(shù)用來刪除一個文件。
os.system()函數(shù)用來運行shell命令。
os.linesep字符串給出當前平臺使用的行終止符。例如,Windows使用'\r\n',Linux使用'\n'而Mac使用'\r'。
os.path.split()函數(shù)返回一個路徑的目錄名和文件名。
>>> os.path.split('/home/swaroop/byte/code/poem.txt')
('/home/swaroop/byte/code', 'poem.txt')
os.path.isfile()和os.path.isdir()函數(shù)分別檢驗給出的路徑是一個文件還是目錄。類似地,os.path.existe()函數(shù)用來檢驗給出的路徑是否真地存在。

希望本文所述對大家的Python程序設(shè)計有所幫助。

相關(guān)文章

  • Python使用xlrd模塊操作Excel數(shù)據(jù)導入的方法

    Python使用xlrd模塊操作Excel數(shù)據(jù)導入的方法

    這篇文章主要介紹了Python使用xlrd模塊操作Excel數(shù)據(jù)導入的方法,涉及Python操作xlrd模塊的技巧,需要的朋友可以參考下
    2015-05-05
  • pytorch動態(tài)網(wǎng)絡(luò)以及權(quán)重共享實例

    pytorch動態(tài)網(wǎng)絡(luò)以及權(quán)重共享實例

    今天小編就為大家分享一篇pytorch動態(tài)網(wǎng)絡(luò)以及權(quán)重共享實例,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • pytorch如何使用Imagenet預(yù)訓練模型訓練

    pytorch如何使用Imagenet預(yù)訓練模型訓練

    這篇文章主要介紹了pytorch如何使用Imagenet預(yù)訓練模型訓練問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • Python中的functools partial詳解

    Python中的functools partial詳解

    這篇文章主要介紹了Python中functools partial詳解,本文通過示例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2023-01-01
  • Python 列表與鏈表的區(qū)別詳解

    Python 列表與鏈表的區(qū)別詳解

    這篇文章主要介紹了Python 列表與鏈表的區(qū)別詳解,本篇文章通過簡要的案例,講解了該項技術(shù)的了解與使用,以下就是詳細內(nèi)容,需要的朋友可以參考下
    2021-09-09
  • numpy 產(chǎn)生隨機數(shù)的幾種方法

    numpy 產(chǎn)生隨機數(shù)的幾種方法

    本文主要介紹了numpy 產(chǎn)生隨機數(shù)的幾種方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2023-02-02
  • 關(guān)于PyCharm安裝后修改路徑名稱使其可重新打開的問題

    關(guān)于PyCharm安裝后修改路徑名稱使其可重新打開的問題

    這篇文章主要介紹了關(guān)于PyCharm安裝后修改路徑名稱使其可重新打開的問題,本文通過圖文實例相結(jié)合給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下
    2020-10-10
  • Python接口測試環(huán)境搭建過程詳解

    Python接口測試環(huán)境搭建過程詳解

    這篇文章主要介紹了Python接口測試環(huán)境搭建過程詳解,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-06-06
  • Python的f-string使用技巧

    Python的f-string使用技巧

    Python很早就引入了一種稱為 f-string 的字符串格式化方法,它代表格式化字符串字面值,本文主要介紹了Python的f-string使用技巧,具有一定的參考價值,感興趣的可以了解一下
    2024-01-01
  • python global的創(chuàng)建和修改實例講解

    python global的創(chuàng)建和修改實例講解

    在本篇文章里小編給大家整理了一篇關(guān)于python global的創(chuàng)建和修改實例講解內(nèi)容,有興趣的朋友們可以學習下。
    2021-09-09

最新評論