Python入門簡短實例摘錄

Python入門簡短實例摘錄


這十個小題目是任何一門語言最基本的入門,爲方便後續瀏覽而摘錄下來。大部分實例摘自網站:http://askpython.com,英文原版短文。有想讀英文原版的朋友可以瀏覽此站點。


1. Hello world:

#!/usr/bin/env python3

print('hello world')

2. 變量【可以不用聲明,自動識別變量類型】

#!/usr/bin/python
 
x = 3              # a whole number                   
f = 3.1415926      # a floating point number              
name = "Python"    # a string
 
print(x)
print(f)
print(name)

combination = name + " " + name
print(combination)

sum = f + f
print(sum)

3. 鍵盤輸入【Python2x可以接收字符串或者數字,但是Python3x只接收數字時需要強制轉換】

#!/usr/bin/env python3

name = input('What is your name? ')
print('Hello ' + name)

num = input('Give me a number? ')
print('You said: ' + str(num))

4. 條件語句

!/usr/bin/env python3

age = int(input("Age of your cat? "))
if age < 5:
    print("Your cat is young.")
elif age > 10:
    print("Your cat is old.")
else:
    print("Your cat is adult.")

5. for循環

#!/usr/bin/env python3

city = ['Tokyo','New York','Toronto','Hong Kong']
for x in city:
    print(x)

#!/usr/bin/env python3

num = [1,2,3,4,5,6,7,8,9]
for x in num:
    y = x * x
    print(y)

5.  while循環

#!/usr/bin/python
 
x = 3                              
while x < 10:
    print(x)
    x = x + 1

#!/usr/bin/python

while True:
    if condition:
        break

6. 函數

#!/usr/bin/env python3

def f(x,y):
    print(x*y)

f(3,4)

#!/usr/bin/env python3

def sum(list):
    sum = 0
    for l in list:
        sum = sum + l
    return sum

mylist = [1,2,3,4,5]
print(sum(mylist))

7. 元組 【下標起始0,-1指示最後一個元素】

list = [1,3,4,6,4,7,8,2,3]

print(sum(list))
print(min(list))
print(max(list))
print(list[0])
print(list[-1])

8. 字典【無序存儲結構】

注:使用Python3x運行如下腳本,着重注意print必須帶有括號,如print(words["BMP"]),這是與Python2x中print的區別。

#!/usr/bin/python

words = {}
words["BMP"] = "Bitmap"
words["BTW"] = "By The Way"
words["BRB"] = "Be Right Back"

print words["BMP"]
print words["BRB"]


9.  讀取文件:

按行讀取:

#!/usr/bin/env python

filename = "file.py"

with open(filename) as f:
    content = f.readlines()

print(content)
讀取文件內容到一個字符串:

#!/usr/bin/env python

filename = "file.py"

infile = open(filename, 'r')
data = infile.read()
infile.close()

print(data)

10. 寫文件:

創建一個文件:

#!/usr/bin/env python

# create and open file
f = open("test.txt","w")

# write data to file 
f.write("Hello World, \n")
f.write("This data will be written to the file.")

# close file
f.close()
添加內容到文件末尾:

#!/usr/bin/env python

# create and open file
f = open("test.txt","a")

# write data to file 
f.write("Don't delete existing data \n")
f.write("Add this to the existing file.")

# close file
f.close(





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