获取变量类型:
print type(42)print type(4.2)print type('spam')if(type(1) == type(2.0)): print "equal"else: print "not equal"
list:
start_list = [5, 888, 1, 2, 4]square_list = [] print len(start_list) # number of items start_list.remove(888) # remove an item by value
del start_list[0] # remove an item by index
for num in start_list: square_list.append(num*num) # append to tailsquare_list.sort() # alphabetic orderprint square_list
dictionary:
zoo_animals = { 'Unicorn' : 'Cotton Candy House','Sloth' : 'Rainforest Exhibit','Bengal Tiger' : 'Jungle House','Atlantic Puffin' : 'Arctic Exhibit','Rockhopper Penguin' : 'Arctic Exhibit'}idel zoo_animals['Unicorn'] # remove an itemzoo_animals['Rockhopper Penguin'] = 'anything' # change an itemprint zoo_animalsfor one_key in zoo_animals: print zoo_animals[one_key]
# dictionary can hold many different types of valuesinventory = { 'gold' : 500, 'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key 'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']}# add a key called 'packet', and set the value of this key to be a listinventory['pocket'] = ['seashell', 'strange berry', 'lint']# sort the listinventory['backpack'].sort()# remove an item from the list stored under the 'backpack' keyinventory['backpack'].remove('dagger')# add 50 to the number stored under the 'gold' keyinventory['gold'] = inventory['gold']+50
引入模块:
(1) import math // recommended wayprint math.sqrt(4)(2) from math import sqrt // recommended wayprint sqrt(4)(3) from math import * // NOT recommended wayprint sqrt(4)
函数定义和调用:
def cube(number): return number**3def by_three(number): if(number%3 == 0): return cube(number) else: return Falseprint by_three(3)