Output:
<pre>
print(3)
print("Hello World")
</br>
A = 123
B = 'ABC'
C = 456
D = 'DEF'
print(A, B, C, D)
</pre>
Calculation:
1 + 1
4 - 2
12 / 3
2 * 3
5 % 2
2 ** 3
Variable:
cash =100
apple =10
remain = cash – apple
print(remain)
x = 1;
x = x + 1
print(x)
Type:
<pre>
1---Integer
"1"--- String
True---Boolean
[1, 2, 3]---List
(1, 2, 3)--- Tuple
["name": "Linda"]---Dictionary
two different type cannot operate together
</pre>
String:
<pre>
print("Hello World")
print("This is "+"BCIS") #concatenate
print("Over hill, over dale,\n"+"Thorough bush,thoroughbrier")
print(1 + 2)
print(1 + "ss") #wrong
print("1" + "ss")
print(str(1) + "ss")
print("This year is %d"%2016)
print("I am %d years old I have %d brothers"% (12,3))
print("PI is %6.3f"%3.14159)
</pre>
Input:
<pre>
print("How old are you?")
age = input()
print("How tall are you?")
height = input()
print("How much do you weigh?")
weight = input()
print("So, you're %s old, %s tall and %s heavy." % (age, height, weight))
</br>
name = input("What is your name?")
print("so your name is " + name)
</br>
Mad Lib Game
print("MAD LIB GAME")
print("Enter answers to the following prompts\n")
guy = input("Name of a famous man: ")
girl = input("Name of a famous woman: ")
food = input("Your favorite food (plural): ")
ship = input("Name of a space ship: ")
job = input("Name of a profession (plural): ")
planet = input("Name of a planet: ")
drink = input("Your favorite drink: ")
number = input("A number from 1 to 10: ")
story = "\nA famous married couple, GUY and GIRL, went on\n" +
"vacation to the planet PLANET. It took NUMBER\n" +
"weeks to get there travelling by SHIP. They\n" +
"enjoyed a luxurious candlelight dinner over-\n" +
"looking a DRINK ocean while eating FOOD. But,\n" +
"since they were both JOB, they had to cut their\n" +
"vacation short."
story = story.replace("GUY", guy)
story = story.replace("GIRL", girl)
story = story.replace("FOOD", food)
story = story.replace("SHIP", ship)
story = story.replace("JOB", job)
story = story.replace("PLANET", planet)
story = story.replace("DRINK", drink)
story = story.replace("NUMBER", number)
print(story)
</pre>
List:
lists can contain any sort ofobject: numbers, strings, and even other lists.
<pre>classmates = ['Michael','Bob','Tracy','Tony','Cargo']
len(classmates)
classmates[0]
classmates.append('Jason')
classmates.insert(2,'Pony')
classmates.pop()
classmates.remove('Bob')
classmates.pop(2)
classmates.reverse()
classmates.sort()
classmates[2] ="Mike"
classmates[1:3]
classmates[:3]
classmates[-1]
classmates[-3:-1]
classmates[:5:2]
classmates[::-1]
classmates.count('Bob')
L = [
['Apple','Google','Microsoft'],
['Java','Python','Ruby','PHP'],
['Adam','Bart','Lisa']
]
L[0][1]
[1, 2, 3] + [4, 5, 6]
['Ni!'] * 4
3 in [1, 2, 3]
</pre>
Dictionary:
<pre>
dict= {'Michael':95,'Bob':75,'Tracy':85}
dict['Michael']
dict['Jack'] =90
dict['Jack']
dict['Jack'] =87
dict['Jack']
dict.get('Jack')
dict.pop('Michael')
</pre>
Set:
<pre>
s=set([1,1,2,2,3,3])# it will delete same number
s.add(4)
s.add(4)
print(s)# {1, 2, 3, 4}
s.remove(2)
s1 = {1,3,4}
s2 = {1,2,5}
s1 & s2
s1 | s2
</pre>
Logic:
<pre>
True and False
True or False
not True
1!=2
1==1
3>=1
3<=6
</pre>
If:
<pre>
age = 3
if age >= 18:
print('adult')
elif age >= 6:
print('teenager')
else:
print('kid')</pre>
Loop:
<pre>names = ['Michael', 'Bob', 'Tracy']
for name in names:
print(name)
</pre>
缩进
<pre>
!/usr/bin/python
-- coding: UTF-8 --
文件名:test.py
if True:
print "Answer"
print "True"
else:
print "Answer"
# 没有严格缩进,在执行时会报错
print "False"
</pre>
<pre>sum = 0
for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
sum = sum + x
print(sum)
</pre>
<pre>sum = 0
for x in range(10):
sum = sum + x
print(sum)
</pre>
Functions:
<pre>
def my_abs(x):
if x >= 0:
return x
else:
return -x
def power(x, n):
s = 1
while n > 0:
n -= 1
s = s * x
return s
def power(x, n=2):
s = 1
while n > 0:
n = n - 1
s = s * x
return s
def calc(*numbers):
sum = 0
for n in numbers:
sum = sum + n * n
return sum
calc(1, 2)
nums = [1, 2, 3]
calc(*nums)
</pre>
Recursion:
<pre>
def fact(n):
if n==1:
return 1
return n * fact(n - 1)
</pre>
Iteration:
<pre>
d = {'a': 1, 'b': 2, 'c': 3}
for key in d:
print("key:" + key + "value:" + str(d[key]) + "\n")
for character in "ABCDEFG":
print(character)</pre>
Generator:
<pre>g = (x * x for x in range(10))
next(g)
next(g)
f = (x * x for x in range(10))
for n in f:
print(n)
</pre>
<pre>def fib(max):
n, a, b = 0, 0, 1
while n < max:
yield b
a, b = b, a + b
n = n + 1
return 'done'
g = fib(10)
for i in g:
print(i)
</pre>
High Order Function:
<pre>def add(a, b):
return a + b
f = add
print(f(1, 2))
</pre>
Build-in Function:
map:
<pre>
def f(x):
return x * x
r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(list(r))
</pre>
reduce:
<pre>from functools import reduce
def f(a, b):
return a + b
r = reduce(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
print(r)
</pre>
filter:
<pre>def is_odd(n):
return n % 2 == 1
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
</pre>
sort:
<pre>
sorted([36, 5, -12, 9, -21])
sorted([36, 5, -12, 9, -21], key=abs)
sorted(['bob', 'about', 'Zoo', 'Credit'], key=str.lower, reverse=True)
</pre>
Exception:
<pre>
s = input("Enter a number:")
try:
number = float(s)
except:
number = 0
answer = number * number
print(answer)
</pre>
Module:
OOP:
<pre>
class Student(object):
def init(self, name, score):
self.name = name
self.score = score
def print_score(self):
print('%s: %s' % (self.name, self.score))
bart = Student('Bart Simpson', 59)
lisa = Student('Lisa Simpson', 87)
bart.print_score()
lisa.print_score()</pre>
Inheritance:<pre>
class Animal(object):
def run(self):
print('Animal is running...')
class Dog(Animal):
pass
class Cat(Animal):
pass
dog = Dog()
dog.run()
cat = Cat()
cat.run()
</pre>
<pre>
class Dog(Animal):
def run(self):
print('Dog is running...')
def eat(self):
print('Eating meat...')
dog = Dog()
dog.run()
</pre>
<pre>a = list()
b = Animal()
c = Dog()
print(isinstance(a,list))
print(isinstance(b, Animal))
print(isinstance(c, Dog))
print(isinstance(c, Dog))
</pre>