Python学习笔记(1)变量、循环

最近在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

包含文件或者库或者包(分类为generic import 和function import)
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 



list的用法 - 使用append()进行插入
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是可以打印的

list的用法- remove方法
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]


list的用法 - 遍历
#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]

 
list的用法 - 小例子1 -  string也是一种list
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

如何创建符合条件的list之一  - 使用List Comprehension
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

如何创建符合条件的list之二 - 使用Slicing - 例子1
#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]


如何创建符合条件的list之二 - 使用Functional Programming中的Lambda Syntax - 例子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 )


Dictionary的用法
#创建时,用{ } ,如
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,可能得到的遍历顺序不一样

打印Dictionary
用 values() 函数打印values,同样没有顺序
用 keys() 函数打印keys,同样没有顺序

tuples
You can think of a tuple as an immutable (that is, unchangeable) list (though this is an oversimplification); tuples are surrounded by ()s and can contain any data type.

循环的用法1 while else
the else block will execute anytime the loop condition is evaluated toFalse. This means that it will execute if the loop is never entered or if the loop exits normally. If the loop exits as the result of a break, the else will not be executed.
注意常见BUG是 while else中一定要明确地对循环变量增加或者减少,否则就无限循环了

#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!”


循环的用法2 for + range()
hobbies = []
for i in range(3):
    hobby=raw_input("what is your hobby")
    hobbies.append(hobby)



循环的用法2 for _ string
对字符串变量使用for循环语句, 打印字符串变量。 print c 表示每次打印一行,print c, 表示将正常状态下的行分隔符换位去掉,这样所有的打印结果将在同一行了
thing = "spam!"

for c in thing:
    print c

word = "eggs!"

for c in word:
    print c


循环的用法2 for + string
对字符串变量使用for循环语句, 替换指定的字符。
phrase = "A bird in the hand..."
for char in phrase:
    if char=='A'  or char=='a':
        print 'X',
    else:
        print char,
print


循环的用法2 for + list
对list使用for语句,逐个操作list中的元素
numbers  = [7, 9, 12, 54, 99]
print "This list contains: "
for num in numbers:
    print num
for num in numbers:
    print num**2


循环的用法2 for + dictionary
对dictionary使用for语句,逐个操作dictionary中的key和value
d = {'a': 'apple', 'b': 'berry', 'c': 'cherry'}
for key in d:
    print key+" "+d[key]

循环的用法2 for + enumerate + list
对list使用for语句和enumerate语句的结合体,获取元素及元素的下标
choices = ['pizza', 'pasta', 'salad', 'nachos']
print 'Your choices are:'
for index, item in enumerate(choices):
    print index+1, item


循环的用法2 for + zip + list
for循环搭配使用 zip语句,zip语句生成2个list的pair,直到遇到较短的list为止。
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
    

循环的用法2 for + zip + list

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



循环的用法3 for  else
注意和WHILE ELSE的执行条件不一样
Just like with while, for loops may have an else associated with them. In this case, the else statement is executed after the for, but only if the for ends normally—that is, not with a break. This code will break when it hits 'tomato', so the else block won't be executed.
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,


for A not in B 语法
滤重过程中的语法 if a not in b
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
     
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值