最近在codecademy上学习Python, 这是一个非常注意实践的操作平台,每讲解一点内容就让人做一些练习,讲解点也设计得非常适合Python零基础的人学习。讲到了变量,list, dictionary, for/while loop, class, file I/O 等内容。
Python的特点
functional programming: you're allowed to pass functions around just as if they were variables or values. Sometimes we take this for granted, but not all languages allow this!
注意要用空格表示缩进
#用四个空格表示缩进,如果没有缩进,是语法错误 def spam(): eggs =12 return eggs print spam()
不换行标示符\
注意\可以用来表示此处不换行
变量小结1
Variables, which store values for later use
Data types, such as numbers and booleans
Whitespace, which separates statements
Comments, which make your code easier to read, # 表示单行注释 ’'’表示多行注释
Arithmetic , +, -, *, /, **, and %
变量小结2
变量不需要定义类型。变量的类型由赋值时候等号右边的数的类型去决定
my_bool=true #错误。改为 my_bool=True 正确
my_bool=True #正确
count_to = 2137483647+2137483648 #没有发生溢出,运行正常
变量小结3
To divide two integers and end up with a float, you must first usefloat() to convert one of the integers to a float.
15.0/100 =0.15 #
15/100=0 #注意运算精度的问题,当期待的计算结果为float型时,等号左边至少有一个float
print 10//3.0 #3
print 10/3.0 #3.33333
print 10/3 #3
注意1 在python中转化为整数的语法是 int(x),而不是(int) x
python中的时间
#打印时间 from datetime import datetime now = datetime.now() print '%s/%s/%s %s:%s:%s' % (now.month, now.day, now.year, now.hour, now.minute, now.second)
'Alpha' "Bravo" str(3)
c = “cats”[1] #则c="a”, 注意变量c也是字符型
parrot="Norwegian Blue” print len(parrot) parrot = "Norwegian Blue" print parrot.lower() print parrot.upper() pi=3.14 print str(pi) #规律: 上面的内建函数中Methods that use dot notation only work with strings. On the other hand, len() and str() can work on other data types.
String Concatenation “a” + “b” + ”c”
string_1 = "Camelot" string_2 = "place" print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2) #The % operator after a string is used to combine a string with variables. The % operator will replace a %s in the string with the string variable that comes after it
hours =3 ones =hour %10 tens= hour //10 print tens, ones, “:00” #输出 0 3 :00 print str(tens), str(ones), “:00” #输出 0 3 :00 print str(tens)+str(ones)+“:00” #输出 03:00
import math #这种是generic import print math.sqrt(25) from math import sort #这种是function import from math import * #这种是universal import,可能会带来命名空间污染,不推荐使用 # 不需要import 任何module就可以直接使用的function是min(), max(), abs(), type()
pyg = 'ay' original = raw_input('Enter a word:') if len(original) > 0 and original.isalpha(): word = original.lower() first=word[0] new_word=word+first+pyg new_word=new_word[1:len(new_word)] print new_word else: print 'empty'
#定义函数 def hello(): print "Hello, world!” #调用函数 h=hello() print h #none #上面print h之后的显示结果为none,说明函数hello()其实隐形地返回了none,如下 def hello(): print "Hello, world!” return none
suitcase = [] suitcase.append("sunglasses") suitcase.append("tshirt") suitcase.append("dress") suitcase.append("belt") list_length = len(suitcase) # Set this to the length of suitcase print "There are %d items in the suitcase." % (list_length) print suitcase #list类型的变量suitcase是可以打印的
n = [1, 3, 5] #1.n.pop(index) will remove the item at index from the list and return it to you: n.pop(1) # Returns 3 (the item at index 1) print n # prints [1, 5] #2.n.remove(item) will remove the actual item if it finds it: n.remove(1) # Removes 1 from the list, NOT the item at index 1 print n # prints [3, 5] #3.del(n[1]) #del is like .pop in that it will remove the item at the given index, but it won't return it: del(n[1]) # Doesn't return anything print n # prints [1, 5]
#Method 1 - for item in list: for item in list: print item #Method 2 - iterate through indexes: for i in range(len(list)): print list[i]
for letter in "Codecademy": print letter print print word = "Programming is fun!" for letter in word: # Only print out the letter i if letter == "i": print letter
doubles_by_3 = [x*2 for x in range(1,6) if (x*2) % 3 == 0] even_squares = [x**2 for x in range(1,11) if x%2 ==0] print even_squares
#0 格式为list[start:end:stride] #1 步长: stride>0则从左往右前进,stride<0则从右往左前进 #2 默认: start_index=0, end_index=len(list), stride=1 #3 方括号: list和list slicing都使用方括号 #list slicing example1 l = [i ** 2 for i in range(1, 11)] # Should be [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] print l[2:9:2] #list slicing example2 my_list = range(1, 11) # should be [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] backwards=my_list[::-1]
#例1 在内建filter( )中结合使用lambda syntax进行过滤 my_list = range(16) print filter(lambda x: x % 3 == 0, my_list) #例2 在内建filter( )中结合使用lambda syntax进行过滤 languages = ["HTML", "JavaScript", "Python", "Ruby"] print filter(lambda x: x=='Python',languages )
#创建时,用{ } ,如 dict_a={ key_a:value_a, key_b:value_b, key_c:value_c, }, #注意1 创建之后 # 如果要删除用[ ],如del dict_a[key_b] # 如果要插入用[ ],如dic_a[key_a]=value_a #注意2 每次遍历dictionary,可能得到的遍历顺序不一样
#Python中的循环表示法,WHILE ELSE语法 import random print "Lucky Numbers! 3 numbers will be generated." print "If one of them is a '5', you lose!" count = 0 while count < 3: num = random.randint(1, 6) print num if num == 5: print "Sorry, you lose!" break count += 1 else: print "You win!”
hobbies = [] for i in range(3): hobby=raw_input("what is your hobby") hobbies.append(hobby)
thing = "spam!" for c in thing: print c word = "eggs!" for c in word: print c
phrase = "A bird in the hand..." for char in phrase: if char=='A' or char=='a': print 'X', else: print char, print
numbers = [7, 9, 12, 54, 99] print "This list contains: " for num in numbers: print num for num in numbers: print num**2
d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'} for key in d: print key+" "+d[key]
choices = ['pizza', 'pasta', 'salad', 'nachos'] print 'Your choices are:' for index, item in enumerate(choices): print index+1, item
list_a = [3, 9, 17, 15, 19] list_b = [2, 4, 8, 10, 30, 40, 50, 60, 70, 80, 90] for a, b in zip(list_a, list_b): if a>=b: print a else: print b
for循环搭配使用 zip语句,zip语句可以扩展到有N个list的情况,相当于对list求了横截面,生成N个list的横截面pair , 直到遇到最短的list为止。
list_a=[1,3,5,7,9,10] list_b=[2,4,6,8] list_c=[-6,-3,0,3,6,9,12,15,18,21] for a,b,c in zip(list_a,list_b,list_c): if a>=b: if a>=c: print a else: print c else: if b>=c: print b else: print c
fruits = ['banana', 'apple', 'orange', 'tomato', 'pear', 'grape'] print 'You have...' for f in fruits: print 'these are the fruits:', else: print 'A fine selection of fruits!'
for A in B 语法
#1 my_dict ={"Book" : "Idealism", "Rate" : 4.8, "Year" : 2013 } for each in my_dict: print each, my_dict[each] #2 for num in range(5): print num, #3 for letter in ‘Eric’ print letter,
def remove_duplicates(list_in): list_out=[] for item in list_in: if item not in list_out: list_out.append(item) return list_out