Python
Interpreted (√) VS. compile
Operation
+ - * /
>>>‘a‘*3
‘aaa‘
>>>3/5
0
>>>3**3
27
Variables
>>> a = 3
>>> print a
3
Operators and operands
>>> ‘ab‘ + ‘c‘
‘abc‘
>>> 3 + ‘c‘
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for +: ‘int‘ and ‘str‘
>>> str(3) + ‘c‘
‘3c‘
>>> ‘a‘ < 3
False
>>> 4 + ‘3‘
True
>>> 9/5
1
>>> 9%5
4
>>> 3+4*5
23
type of Variables--get from value
Dynamic types 动态类型
x = ‘abc’
don’t change types arbitrarily 不要反复无常的改变变量类型
Variables used any place it’s legal to use value
statements
branching 分支
冒号: start
carriage 回车 is end
x = 15
if(x/2)* 2 == x:
print ‘Even‘
else: print ‘Odd‘
conditionals 条件
# if语句可嵌套
if <some test> :
Block of instructions.
else:
Block of instructions.
iteration 迭代 or loops 循环
# y = x的平方
y = 0
x = 3
itersLeft = x
while(itersLeft>0) :
y = y + x
itersLeft = itersLeft -1
print y
iterative programs
flow chart 流程图
# x开方
# find the square root of a perfect square
x = 16
ans = 0
while ans*ans <= x:
ans = ans + 1
print ans
x = 15
if(x/2)* 2 == x:
print ‘Even‘
else: print ‘Odd‘
Simulate 模拟
ans | x | ans*ans |
---|---|---|
0 | 16 | 0 |
1 | 16 | 1 |
2 | 16 | 4 |
3 | 16 | 9 |
4 | 16 | 16 |
5 | 16 | 25 |
Defensive programming
# x开方进化版
# find the square root of a perfect square
# x = 1515361
ans = 0
if x > 0:
while ans*ans < x:
ans = ans + 1
#print ‘ans =‘, ans
if ans*ans != x:
print x, ‘is not a perfect square‘
else: print ans
else: print x, ‘is a negative number‘
Exhaustive enumeration 穷尽/枚举
# find x‘s divisor
# x = 10
# i = 1
while i < x:
if x%i == 0:
print ‘divisor‘, i
i = i+1
# find x‘s divisor
x = 10
for i in range(1, x):
if x%i == 0:
print ‘divisor‘, i
Tuple 元组
w3school Python元组
- ordered sequence of elements 有序的元素序列(immutable 不可变的)
>>> foo = (1, 2, 3)
>>>> foo
(1, 2, 3)
>>> foo[0]
1
>>> foo[1]
2
>>> foo[10]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: tuple index out of range
>>> foo[-1]
3
>>> foo[-2]
2
>>> foo[1:3]
(2, 3)
>>> foo[1:2]
(2,)
>>> foo[:2]
(1, 2)
>>> foo[1:]
(2, 3)
# find x‘s divisor
x = 100
divisors = ()
for i in range(1, x):
if x%i == 0:
divisors = divisors + (i,)
print divisors
String
w3school Python字符串
- support selection, slicing, and a set of other parameters, other properties
sumDigits = 100
for c in str(1952):
sumDigits += int(c)
print sumDigits
MIT麻省理工学院公开课:计算机科学及编程导论 Python 笔记1-3
原文地址:http://blog.csdn.net/muzilanlan/article/details/45749823