程式碼5要素
變數
type這個function,可以取得變數的資料型態
#Numbers
counter = 100 # An integer assignment
miles = 1000.0 # A floating point
name = "John" # A string
type(name)
#String
str = 'Hello World!'
print str # Prints complete string
print str[0] # Prints first character of the string
print str[2:5] # Prints characters starting from 3rd to 5th
print str[2:] # Prints string starting from 3rd character
print str * 2 # Prints string two times
print str + "TEST" # Prints concatenated string
#List
list = [ 'abcd', 786 , 2.23, 'john', 70.2 ]
tinylist = [123, 'john']
print list # Prints complete list
print list[0] # Prints first element of the list
print list[1:3] # Prints elements starting from 2nd till 3rd
print list[2:] # Prints elements starting from 3rd element
print tinylist * 2 # Prints list two times
print list + tinylist # Prints concatenated lists
#Tuples
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 )
#Dictionary
tinydict = {'name': 'john','code':6734, 'dept': 'sales'}
tinydict['mynewkey'] = 'mynewvalue'
print (tinydict['name']) # Prints value for 'one' key
print (tinydict['code']) # Prints value for 2 key
print (tinydict) # Prints complete dictionary
print (tinydict.keys()) # Prints all the keys
print (tinydict.values()) # Prints all the values
Dictionary
dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}
print ("dict['Name']: ", dict['Name'])
print ("dict['Age']: ", dict['Age'])
del dict['Name'] # 删除键是'Name'的条目
dict.clear() # 清空词典所有条目
del dict # 删除词典
Creating an empty dictionary
data = {}
# OR
data = dict()
Creating a dictionary with initial values
data = {'a':1,'b':2,'c':3}
# OR
data = dict(a=1, b=2, c=3)
# OR
data = {k: v for k, v in (('a', 1),('b',2),('c',3))}
Inserting/Updating a single value
data['a']=1 # Updates if 'a' exists, else adds 'a'
# OR
data.update({'a':1})
# OR
data.update(dict(a=1))
# OR
data.update(a=1)
Inserting/Updating multiple values
Python 字典(Dictionary) update()方法
data.update({'c':3,'d':4}) # Updates 'c' and adds 'd'
Creating a merged dictionary without modifying originals
data3 = {}
data3.update(data) # Modifies data3, not data
data3.update(data2) # Modifies data3, not data2
##Deleting items in dictionary
```py
del data[key] # Removes specific element in a dictionary
data.pop(key) # Removes the key & returns the value
data.clear() # Clears entire dictionary
Check if a key is already in dictionary
key in data
Iterate through pairs in a dictionary
for key in data: # Iterates just through the keys, ignoring the values
for key, value in d.items(): # Iterates through the pairs
for key in d.keys(): # Iterates just through key, ignoring the values
for value in d.values(): # Iterates just through value, ignoring the keys
x = {'a' : 1, 'b' : 2}
if 'a' in x.keys():
print(x['a'])
Create a dictionary from 2 lists
data = dict(zip(list_with_keys, list_with_values))
敘述
print("Art: %5d, Price per Unit: %8.2f" % (453, 59.058))
print("Art: {a:5d}, Price: {p:8.2f}".format(a=453, p=59.058))
判斷
a=1
if a>0:
print("Value of a is positive")
else:
print("Value of a is negative")
if a==0:
print("Value of a is zero")
elif a>0:
print("Value of a is positive")
else:
print("Value of a is negative")
b=100
while b > 1:
print ("The number is:%3d" % (b))
b = b / 3
迴圈
for x in range(0, 3):
print ("It's %d" % (x))
my_list = [1,2,3]
for ndx, member in enumerate(my_list):
my_list[ndx] += 42
print my_list
函式
def max(a, b):
if a > b:
return a
else:
return b
def max(a, b):
return a if a > b else b
def gcd(m, n):
if n == 0:
return m
else:
return gcd(n, m % n)
print(gcd(45, 30)) #15
print(type(gcd)) #<class 'function'>
def sum(a, b):
return a + b
def sum(a, b, c):
return a + b + c
#預設引數
def sum(a, b, c = 0):
return a + b + c
匯入模組import 、 import as 與 from import
import math
print(math.pi)
print(math.e)
print(math.sqrt(2))
print(math.sin(math.radians(90))) # sin 90 度
from math import pi, sqrt, sin
print(pi)
print(sqrt(2))
print(sin(math.radians(90))) # sin 90 度
import matplotlib.pyplot as plt
輸入/輸出
str = input("Enter your a number: ")
print "Received bumber is : ", int(str)
# file-wrt.py
a=100
f = open('test.txt','w')
f.write(a)
f.close()
# file-rd.py
f = open('test.txt','r')
str = f.readline()
print(int(str))
f.close()
with open('filename.txt') as fp:
for line in fp:
print(line)
csvfileIn = folder+"\\"+csvfile
csvfileOut = path2+"\\"+name+".vcf"
print(csvfileOut)
# file-rd.py
fin = open(csvfileIn,'r')
fout = open(csvfileOut,'w')
for line in fin:
chr = line[:4]
if chr != "chr3":
continue
if chr == "chr4":
break
fout.write(line)
fin.close()
fout.close()