Python/基礎

維基教科書,自由的教學讀本

首先,使用Python要先從Python網站下載。此教程使用2.5版本。下載網址:

http://python.org/download/

Python在英文中是蟒蛇的意思。Python的創始人為荷蘭的Guido van Rossum。他在1989年為了打發聖誕節的無趣,決定開發一個新的腳本解釋程序,名稱以他愛看的一個電視喜劇的名字來命名。(在維基百科詳細了解

在IDLE裡輸入print "Hello World"來顯示第一個腳本。

>>> print "hello world"
hello world

字符串[編輯]

字符串的引號有以下幾種寫:

  1. '」或「"」,可以指示這裡的字符是字符串
  2. """」或「 ''' 」——三個引號,引用多行字符串
  3. \n」——轉義符,表示換行
  4. 在「'」或「"」的行末輸入「\」轉行
>>> abc='def'
>>> abc="def"
>>> abc='''d
ef'''
>>> abc="d\
ef"

語句間的間隔[編輯]

有兩種方式間隔:

  1. 換行
  2. ;」——分號
>>> abc="def"
>>> wmr="great wikipedian"

>>> abc="def";wmr="great wikipedian"

控制語句[編輯]

  • if:如果,(wmr could be admin on wikipedia)
    1. elif:另一個如果,(wmr could be bureaucrat on wikipedia)
    2. else:如果兩個都不,(wmr could be nothing on wikipedia)
>>> wmr=250
>>> if wmr==500:
	print "wmr could be admin on wikipedia."
elif wmr==1000:
	print "wmr could be bureaucrat on wikipedia."
else:
	print "wmr could be nothing on wikipedia."

	
wmr could be nothing on wikipedia.
  • while:與此同時..
>>> while running=True
>>> while running:
	wmr=250
	if wmr==500:
		print "wmr could be admin on wikipedia."
	elif wmr==1000:
		print "wmr could be bureaucrat on wikipedia."
	else:
		print "wmr could be nothing on wikipedia."
	running = False

一定要寫running = False !否則就會一直print "wmr could be nothing on wikipedia."

  • for:循環
for i in range(1, 5):
    print i
else:
    print 'The for loop is over'
  • break:終止循環
>>> while running=True
>>> while running:
	wmr=250
	if wmr==500:
		print "wmr could be admin on wikipedia."
	elif wmr==1000:
		print "wmr could be bureaucrat on wikipedia."
	else:
		print "wmr could be nothing on wikipedia."
	break