python的学习笔记1

Codeacadem专注于step by step的编程教学,包括APIs, Ruby, Python, JavaScript, jQuery, PHP,Web等语言的学习,是免费学习编程的不错的工具。

http://www.codecademy.com点击打开链接


在学习python的过程中,记录的知识点如下:

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 operations, including +, -,*, /, **(平方)and %(模,取余)

    转义字符 :/

    # :单行注释

     一套三重引号 “””   “””:多行注释

# example
monty = True
python = 1.234
monty_python = python ** 2

# 账单的例子。 meal成本,tax是税率6.75%,tip是小费15%
meal = 44.50
tax = 0.0675
tip = 0.15
meal = meal + meal * tax
total = meal + meal * tip
print("%.2f" % total)

2.  数据类型

Python主要有三种数据类型:字典、列表、元组。其分别由花括号,中括号,小括号表示。

如:

字典:dic={'a':12,'b':34}

列表:list=[1,2,3,4]

元组:tup=(1,2,3,4)

3. 字符串函数

    len():长度                   str():将非字符串转化为字符串格式   
    lower():转化为小写    upper():转化为大写      

    parrot = "Norwegian Blue"
  print len(parrot)       # 14
  print parrot.lower()    # norwegian blue
  print parrot.upper()    # NORWEGIAN BLUE
  pi = 3.14 
  print str(pi)           # 3.14
4. 输出函数 print 和 输入
  print "Spam and eggs"
  print "Spam " + "and " +"eggs"       # 注意 + 的使用
  print "The value of pi is around " + str(3.14)
  
  string_1 = "Camelot"
  string_2 = "place"
  print "Let's not go to %s. 'Tis a silly %s." % (string_1, string_2)  # 注意% 和 ()

  name = raw_input("What is your name?")
  quest = raw_input("What is your quest?")
  color = raw_input("What is your favorite color?")
  print "Ah, so your name is %s, your quest is %s, " \
  "and your favorite color is %s." % (name, quest, color)

5. Datetime

    #导入
    from datetime import datetime
  #获取当前时间,年月日 
  now = datetime.now()
  current_month = now.month
  current_day = now.day
  current_year = now.year
  print now            #2014-01-14 03:23:19.092424
  print current_month
  print current_day
  print current_year
  print str(current_month)+"/"+str(current_day)+"/"+str( current_year)  # mm/dd/yyyy 
  #获取小时,分,秒  打印格式 hh:mm:ss
  now = datetime.now()
  current_hour = now.hour
  current_minute = now.minute
  current_second = now.second
  print str(current_hour)+":"+str(current_minute)+":"+str( current_second)

6. 比较和控制流 Conditionals & Control Flow

# 例子
  def clinic():
      print "You've just entered the clinic!"
      print "Do you take the door on the left or the right?"
      answer = raw_input("Type left or right and hit 'Enter'.").lower()
      if answer == "left" or answer == "l":
          print "This is the Verbal Abuse Room, you heap of parrot droppings!"
      elif answer == "right" or answer == "r":
          print "Of course this is the Argument Room, I've told you that already!"
      else:
          print "You didn't pick left or right! Try again."
          clinic()
  clinic()

  # 比较 >/>=/</<=/==/!=
  bool_one = 20 + -10 * 2 > 10 % 3 % 2
  bool_two = (10 + 17)**2 == 3**6
  bool_three = 1**2**3 <= -(-(-1))
  bool_four = 40 / 20 * 4 >= -4**2
  bool_five = 100**0.5 != 6 + 4
  
  # bool比较 and/or/not
  
  #例子,注意冒号 (if, else, and elif)
  def greater_less_equal_5(answer):
      if answer > 5:
          return 1
      elif answer < 5:         
          return -1
      else:
          return 0       
  print greater_less_equal_5(4)
  print greater_less_equal_5(5)
  print greater_less_equal_5(6) 

7. PygLatin

# 判断输入的字符串是否为空
  print "Welcome to the English to Pig Latin translator!"
  original = raw_input("Please input a string:")
  if original != "":
      print original
  else:
      print "empty" 

 original.isalpha():判断字符串是否全是字母

 word[i:j]:取字符串i到j的字符串。

#例子,实现变换
  pyg = 'ay'
  original = raw_input('Enter a word:')
  word = original.lower()
  first = word[0]
  if len(original) > 0 and original.isalpha():
  #元音字母的处理,apple->appleay
      if first == 'a' or first == 'e' or first == 'i' or first == 'o' or first == 'u':
          new_word = original + pyg
          print new_word
  # 辅音字母的处理,deep->eepday
      else: 
          new_word = word[1:len(original)] + first + pyg
          print new_word
  else: print 'empty'
 
#输出结果
Enter a word: apply
applyay
Enter a word: deep
eepday

8. 函数  Functions

类型转化函数

int(x [,base ])         将x转换为一个整数    
long(x [,base ])        将x转换为一个长整数    
float(x )               将x转换到一个浮点数    
complex(real [,imag ])  创建一个复数    
str(x )                 将对象 x 转换为字符串    
repr(x )                将对象 x 转换为表达式字符串    
eval(str )              用来计算在字符串中的有效Python表达式,并返回一个对象    
tuple(s )               将序列 s 转换为一个元组    
list(s )                将序列 s 转换为一个列表    
chr(x )                 将一个整数转换为一个字符    
unichr(x )              将一个整数转换为Unicode字符    
ord(x )                 将一个字符转换为它的整数值    
hex(x )                 将一个整数转换为一个十六进制字符串    
oct(x )                 将一个整数转换为一个八进制字符串  

#例子   注意 冒号:的使用
def tax(bill):
    """Adds 8% tax to a restaurant bill."""
    bill *= 1.08
    print "With tax: %f" % bill
    return bill
def tip(bill):
    """Adds 15% tip to a restaurant bill."""
    bill *= 1.15
    print "With tip: %f" % bill
    return bill 
meal_cost = 100
meal_with_tax = tax(meal_cost)
meal_with_tip = tip(meal_with_tax)

# 例子 *的使用
def favorite_actors(*name):
    """Prints out your favorite actorS (plural!)"""
    print "Your favorite actors are:" , name
favorite_actors("Michael Palin", "John Cleese", "Graham Chapman")

# 函数嵌套
def one_good_turn(n):
    return n + 1   
def deserves_another(n):
  return one_good_turn(n) + 2
  
# 例子2 嵌套  
def cube(n):
    sum = n ** 3
    return sum
def by_three(m):
    if m % 3 == 0: return cube(m)
  else: return False

导入 import

import math
print math.sqrt(25)

特定函数导入 用法:from module import function

from math import sqrt

所有函数的导入 用法:from module import *   import everything from the module

from math import *    
import math            # Imports the math module
everything = dir(math)   # Sets everything to a list of things from math
print everything         # Prints 'em all!

函数 max() / min() / abs() / type()

the type() function returns the type of the data :

print type(42)
print type(4.2)
print type('spam')
#输出结果:
<type 'int'>
<type 'float'>
<type 'unicode'>

#若参数m是int或者float型,则返回其绝对值。
def distance_from_zero(m):
    if type(m) == int or type(m) == float:
        return abs(m)
  else: return "Not an integer or float!"
9.  Python 列表 Lists and 字典 Dictionaries

列表:list_name = [item_1, item_2, item_3,...]

空列表:empty_list = []

取值 list_name[index]index0开始编号

取列表的部分值 list_name[a:b]  a开始,在b之前结束

list_name[:b] 从头开始,在b之前结束;list_name[a:]  a开始,到列表尾部。

列表长度:len(list_name)

所涉及的函数

追加: list_name.append(item)

查找dog的位置:my_list.index("dog")

插入cat : my_list.insert(4,"cat")

duck_index = animals.index("duck")   # Use index() to find "duck"

animals.insert(duck_index,"cobra")   # 插入

排序:square_list.sort()

For循环   variable是变量,表示列表list_name内的值

for variable in list_name:

# 例子
start_list = [5, 3, 1, 2, 4]
square_list = []
for x in start_list:
    square_list.append(x ** 2)
    square_list.sort()
print square_list

字典d = {'key1' : 1, 'key2' : 2, 'key3' : 3}

索引 的作用—— 字符串 和 数字的对应

d = {'key1' : 1, 'key2' : 2, 'key3' : 3}
print d['key1']   #输出1
print d['key2']   #输出2
print d['key3']   #输出3

dict_name[new_key] = new_value

# 例子
menu = {} # Empty dictionary
menu['Chicken Alfredo'] = 14.50 # Adding new key-value pair
print menu['Chicken Alfredo']
menu['pig'] = 20.40
menu['tomato'] = 2.00
menu['potata'] = 5.50
print "There are " + str(len(menu)) + " items on the menu."
print menu
# 输出
14.5
There are 4 items on the menu.
{'tomato': 2.0, 'Chicken Alfredo': 14.5, 'potata': 5.5, 'pig': 20.4}

del dict_name[key_name]

dict_name[key] = new_value

# key - animal_name : value - location 
zoo_animals = { 'Unicorn' : 'Cotton Candy House',
'Sloth' : 'Rainforest Exhibit',
'Bengal Tiger' : 'Jungle House',
'Atlantic Puffin' : 'Arctic Exhibit',
'Rockhopper Penguin' : 'Arctic Exhibit'}
# A dictionary (or list) declaration may break across multiple lines
# Removing the 'Unicorn' entry. (Unicorns are incredibly expensive.)
del zoo_animals['Unicorn']
# Your code here!
del zoo_animals['Sloth']
del zoo_animals['Bengal Tiger']
#zoo_animals['Arctic Exhibit']='Rockhopper Penguin'
zoo_animals['Rockhopper Penguin']='aa'
print zoo_animals
# 输出  {'Atlantic Puffin': 'Arctic Exhibit', 'Rockhopper Penguin': 'aa'}

dict_name['list_key'].list_function()

Dict_name[‘list_key’].remove(VALUE)  将列表的值VALUEDict_name[‘list_key’]中移除

# 例子
inventory = {'gold' : 500,
'pouch' : ['flint', 'twine', 'gemstone'], # Assigned a new list to 'pouch' key
'backpack' : ['xylophone','dagger', 'bedroll','bread loaf']}
print inventory
# Adding a key 'burlap bag' and assigning a list to it
inventory['burlap bag'] = ['apple', 'small ruby', 'three-toed sloth']
# Sorting the list found under the key 'pouch'
inventory['pouch'].sort() 
# Here the dictionary access expression takes the place of a list name 
print inventory
# Your code here
inventory['pouch'] = ['seashell', 'strange berry', 'lint']
#inventory['backpack'] = ['xylophone','dagger', 'bedroll','bread loaf']
inventory['pouch'].sort()
inventory['backpack'].remove('dagger')
inventory['gold'] = 50
print inventory
# 输出结果
{'backpack': ['xylophone', 'dagger', 'bedroll', 'bread loaf'], 'pouch': ['flint', 'twine', 'gemstone'], 'gold': 500}
{'backpack': ['xylophone', 'dagger', 'bedroll', 'bread loaf'], 'pouch': ['flint', 'gemstone', 'twine'], 'burlap bag': ['apple', 'small ruby', 'three-toed sloth'], 'gold': 500}
{'backpack': ['xylophone', 'bedroll', 'bread loaf'], 'pouch': ['lint', 'seashell', 'strange berry'], 'burlap bag': ['apple', 'small ruby', 'three-toed sloth'], 'gold': 50}

10.  A Day at the Supermarket  超市的例子

for 循环的应用

# List的例子
a = ["List of some sort”]
for x in a: 
    # Do something for every x
# A simple dictionary  字典的例子
d = {"foo" : "bar"}
for key in d: 
  print d[key]  # prints "bar" 
  
# 运用if/else的for循环
for item in numbers: 
    if condition: 
        # Do something
# 例子:统计"fizz"字符串的个数
def fizz_count(list):
    sum = 0
    for x in list:
        if x == "fizz":
            sum = sum + 1
    return sum
print fizz_count(["fizz","buzz","fizz"])
#输出 2
超市的例子
#例子:按照 “item   price: x  stock: x”的形式输出
prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3}
stock = {"banana": 6,"apple": 0,"orange": 32,"pear": 15}
for x in prices :
   print x
   print "price: "+str(prices[x])
   print "stock: "+str(stock[x])
#输出结果
orange
price: 1.5
stock: 32
pear
price: 3
stock: 15
banana
price: 4
stock: 6
apple
price: 2
stock: 0

#例子:求卖出所有商品的总收入
prices = {"banana": 4,"apple": 2,"orange": 1.5,"pear": 3}
stock = {"banana": 6,"apple": 0,"orange": 32,"pear": 15}
for x in prices :
   print x
   print "price: "+str(prices[x])
   print "stock: "+str(stock[x])
sum = 0 
for x in prices :
    sum = sum + prices[x] * stock[x]
print sum
#输出 117.0

# 超市购物的例子
# stock为库存,prices为单价,只有在有库存的情况,才能出售。每售出一商品,库存减一。
shopping_list = ["banana", "orange", "apple"]
stock = { "banana": 6, "apple": 0, "orange": 32, "pear": 15 }
prices = { "banana": 4, "apple": 2, "orange": 1.5, "pear": 3 }
#统计价格
def compute_bill(food):
    total = 0
    for x in food:
        if stock[x] > 0:
            total += prices[x]
            stock[x] -=1
    return total
#test
print compute_bill(["banana"])
print compute_bill(["apple","orange"])
print compute_bill(prices)
#输出
4
1.5
8.5

11. Student Becomes the Teacher

实例:记录学生成绩等信息

#学生名单
students = [lloyd, alice, tyler]
#学生信息
lloyd = {
    "name": "Lloyd",
    "homework": [90.0, 97.0, 75.0, 92.0],
    "quizzes": [88.0, 40.0, 94.0],
    "tests": [75.0, 90.0]
}
alice = {
    "name": "Alice",
    "homework": [100.0, 92.0, 98.0, 100.0],
    "quizzes": [82.0, 83.0, 91.0],
    "tests": [89.0, 97.0]
}
tyler = {
    "name": "Tyler",
    "homework": [0.0, 87.0, 75.0, 22.0],
    "quizzes": [0.0, 75.0, 78.0],
    "tests": [100.0, 100.0]
}

#求平均值
def average(lst):
    sum = 0
    n = 0
    for i in lst:
        sum += i
        n += 1.0
    return sum/n

#加权平均数
def get_average(student):
    sum = 0
    for key in student:
        if key == "homework":
            sum += average(student["homework"]) * 0.1
        if key == "quizzes":
            sum += average(student["quizzes"]) * 0.3
        if key == "tests":
            sum += average(student["tests"]) * 0.6
    return sum

#成绩与等级的映射
def get_letter_grade(score):
    if score >= 90 :
        return "A"
    if score >= 80 and score < 90 :
        return "B"
    if score >= 70 and score < 80 :
        return "C"
    if score >= 60 and score < 70 :
        return "D"
    if score < 60 :
        return "F"
#test
print get_letter_grade(get_average(lloyd))

#班级的平均数
def get_class_average(class_list):
    grade = 0
    n = 0
    for student in class_list:
        grade += get_average(student)
        n += 1
    return grade/n
#test    
print  get_class_average(students)
输出:B

83.8666666667


版权声明:本文为u010241906原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。