PYTHON BASIC

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:

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:

test.py
test2.py

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>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,383评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,522评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,852评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,621评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,741评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,929评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,076评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,803评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,265评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,582评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,716评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,395评论 4 333
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,039评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,798评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,027评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,488评论 2 361
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,612评论 2 350

推荐阅读更多精彩内容