>>> x = input('Please input x:')Please input x:
>>>print("x="+x)
>>> the_world_is_flat = 1 #注释>>> if the_world_is_flat:print("Be careful not to fall off!")Be careful not to fall off!
>>> x = y = z = 8 #赋值 数字可以运算>>> x+y+z24
>>> x = y = z = 'a' #赋值 字符可以相连>>> x+y+z'aaa'
>>> tax = 12.5 / 100>>> price = 100.50>>> price * tax12.5625>>> price + _113.0625>>> round(_, 2)113.06
字符串>>> 'spam eggs''spam eggs'>>> 'doesn\'t'"doesn't">>> "doesn't""doesn't">>> '"Yes," he said.''"Yes," he said.'>>> "\"Yes,\" he said."'"Yes," he said.'>>> '"Isn\'t," she said.''"Isn\'t," she said.'
>>> hello = '这是一个相当长的字符串包含\n\ #换行几行文本, 就像你在 C 里做的一样.\n\ 注意开通的空白是\ 有意义的.'>>> print(hello)这是一个相当长的字符串包含几行文本, 就像你在 C 里做的一样. 注意开通的空白是 有意义的.
字符串可以使用 + 操作符来连接 (粘在一起), 使用 * 操作符重复:>>> word = 'Help' + 'A'>>> word'HelpA'>>> '<' + word*5 + '>''<HelpAHelpAHelpAHelpAHelpA>'
spider
>>> import urllib.request>>> response = urllib.request.urlopen('http://www.baidu.com/')>>> html = response.read()>>> print (html)
即
>>> import urllib.request>>> print (urllib.request.urlopen('http://www.baidu.com/').read())
字符串可以使用下标选择某个元素 或者切片选择之前之后的所有元素
>>> word='strip'
>>> word'strip'
>>>word[1:3]'tr'
>>> word[:1]'s'>>> word[1:]'trip'>>>
索引可以是负数, 那样就会从右边开始算起。
>>> word[-1]'p'
内建函数 len() 返回字符串的长度:
>>> len(word)5
>>> a = ['spam', 'eggs', 100, 1234]>>> a['spam', 'eggs', 100, 1234]>>> a[1]'eggs'>>> a[1:]['eggs', 100, 1234]
>>> # 可以替代一些项:>>> a[0:2] = [1, 12]>>> a[1, 12, 123, 1234]>>> a[0:2] = ['A', 12]>>> a['A', 12, 123, 1234]>>> a['A', 12, 123, 1234]>>> a[:0] = a>>> a['A', 12, 123, 1234, 'A', 12, 123, 1234]
>>> q = [2, 3]>>> p = [1, q, 4]>>> len(p)3>>> p[1][2, 3]>>> p[1][0]2
>>> p[1, [2, 3], 4]>>> p[1].append('xtra')>>> p[1, [2, 3, 'xtra'], 4]>>> q[2, 3, 'xtra']
>>> a, b = 0, 1>>> while b<100:print('a=',a)print('b=',b)print(" ")c=aa=bb=b+c
>>> a, b = 0, 1>>> while b < 10:print('a =',a,end=',') print('b =',b,end=' ')a,b=b,a+b
if elif 语句 elif必须要顶格 整数要做类型转换
>>> x=int(input("please enter an interger:")) please enter an interger:88>>> if x<0:print('negative change to zero')elif x==0:print('0')else:print('more')
数组元素改变 错误写法
words = ['cat', 'window', 'defenestrate']
>>> for w in words: # Loop over a slice copy of the entire list. ... if len(w) > 6: ... words.insert(0, w) ... >>> words ['defenestrate', 'cat', 'window', 'defenestrate']正确写法
words = ['cat', 'window', 'defenestrate']
>>> for w in words[:]: # Loop over a slice copy of the entire list. ... if len(w) > 6: ... words.insert(0, w) ... >>> words ['defenestrate', 'cat', 'window', 'defenestrate']
等差数列
>>> f=list(range(1, 11))>>> f
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
质数
for n in range(2,100):
for x in range(2,n):
if n%x==0:break
else:print(n,end=',')
缩进是语法
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print('*')
print("Found a number", num)
for num in range(2, 10):
if num % 2 == 0:
print("Found an even number", num)
continue
print('*')
print("Found a number", num)