[关闭]
@ExcitedSpider 2018-01-30T10:01:13.000000Z 字数 4317 阅读 1253

Learning Python(1)

The Zen of Python

The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than right now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Variation

  1. #Wrong! Python intepreter don't know 18 is a int or two char
  2. #TypeError: can only concatenate str (not "int") to str
  3. print("Happy "+18+" years old")
  4. #Yes!Using str()
  5. print("Happy "+str(18)+" years old")

List

  1. moto=['yamaha','suzuki']
  2. #add to rear
  3. moto.append('honda')
  4. #delete
  5. del moto[0]
  6. moto.pop()
  7. moto.remove('yamaha')
  8. print(moto)
  9. ['yamaha', 'suzuki', 'honda']

handle list

  1. motos=['yamaha','suzuki','suzuki']
  2. for moto in motos:
  3. print(moto)
  1. #equals for(int i;i<5;i++) in c++
  2. for value in range(1,5):
  3. print(value)
  4. #1 2 3 4
  1. numbers=list(range(2,11,2))
  2. print(numbers)
  3. #[2, 4, 6, 8, 10]
  1. >>>digits=[1,2,3,4,5,6]
  2. >>>min(digits)
  3. 0
  4. >>>max(digits)
  5. 6
  6. >>>sum(digits)
  7. 21
  1. #It's so amazing!
  2. squares = [value**2 for value in range(1,11)]
  3. print(squares)
  1. numlists=[1,2,3,4,5,6,7,8,9,10]
  2. print(numlists[0:3])
  3. print(numlists[:3])
  4. print(numlists[3:])
  5. print(numlists[-3:])
  6. #[1, 2, 3]
  7. #[1, 2, 3]
  8. #[4, 5, 6, 7, 8, 9, 10]
  9. #[8, 9, 10]
  1. numlists=[1,2,3,4,5,6,7,8,9,10]
  2. numlists2=numlists[:]
  3. #numlist2=numlists Wrong! This expression will copy reference
  4. numlists2.append(11)
  5. print(numlists)
  6. print(numlists2)
  7. #[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
  8. #[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
  1. tupleints=(10,20,30)

Control Flow

  1. and <=> && in cpp
  2. or <=> || in cpp
  1. >>>cars = ['audi','bmw','subaru','toyota']
  2. >>>print('bmw' in cars)
  3. True
  4. >>>print('byd' in cars)
  5. False
  1. cars = []
  2. if cars:
  3. print("I have cars!")
  4. else:
  5. print("I don't have a car!")
  1. #also can be write in one line
  2. aliens={
  3. 'color':'green',
  4. 'points':5
  5. }
  6. print(aliens['color'])
  7. print(aliens['points'])
  8. aliens['name']='holo' #add a key-value pair
  9. print(aliens)
  10. del aliens['color']
  1. #also can be write in one line
  2. aliens={
  3. 'color':'green',
  4. 'points':5
  5. }
  6. for key,value in aliens.items():
  7. print("the alien's "+key+" is value")
  8. for item in aliens.items():
  9. print(item)
  10. for key in aliens.keys():
  11. print(key)
  12. for value in sorted(aliens.values()):
  13. print(value)
  1. message=input("tell me something:")
  2. print("You say "+message)
  3. tell me something:hello
  4. You say hello
  1. message=input("How old are you:")
  2. #input is a string
  3. #using type cast to get int
  4. if int(message)>18:
  5. print('You are an adult!Welcome')

function

  1. def greet_user(Username='Noname'):
  2. """Hello"""
  3. print(Username+", Hello!")
  4. greet_user(Username='David')
  1. def change(value):
  2. value=10
  3. val=5
  4. change(val)
  5. print(val)
  6. #5
  1. def change(values):
  2. for i in range(0,len(values)):
  3. values[i]=10
  4. vals=[5]
  5. change(vals)
  6. print(vals)
  7. #[10]
  1. def change(values):
  2. for value in values:
  3. value=10
  4. vals=[5]
  5. change(vals[:]) //safe mode, cost time
  6. print(vals)
  7. #[5]
  1. def make_pizza(size,*toppings):
  2. #notice the order of args,*means toppings is a tuple.
  3. """make pizza with variable ingredients"""
  4. for top in toppings:
  5. print(top+" add!")
  6. print("This is a "+str(size)+"-inch pizza")
  7. make_pizza("mushroom",'peppers','cheese')
  8. #mushroom add!
  9. #peppers add!
  10. #cheese add!
  1. def build_profile(first,last,**userinfo):
  2. #key-value pair as varargs,use two '*'
  3. """创建用户信息"""
  4. profile={}
  5. profile['first_name']=first
  6. profile['last_name']=last
  7. for key,value in userinfo.items():
  8. profile[key]=value
  9. return profile
  10. first='albert'
  11. last='einstein'
  12. profile=build_profile(first.title(),last.title(),
  13. major='physics',
  14. local='princeton')
  15. print(profile)
  16. #{'first_name': 'Albert', 'last_name': 'Einstein', 'major': 'physics', 'local': 'princeton'}

import modules

  1. import mod as p
  2. #别名
  3. p.fun()
  1. from mod import *
  2. fun() #fun is a function in mod
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注