代码
# Fibonacci series: 斐波纳契数列
# 两个元素的总和确定了下一个数
a,b=0,1
while b <10:
#print(b)
#横屏输出
print(b,end=",")
#先计算右边的等值,后赋值给a,b
a,b = b, a+b
print()
#if else计算狗年龄
age = int(input("请输入你家狗的年龄"))
if age <= 0:
print("tmd是在逗我吧!")
elif age == 1:
print("相当于14岁的人!")
elif age == 2:
print('相当于22岁的人!')
else:
human = 22 + (age-2)*5
print("相当于"+str(human)+"岁的人!")
#猜数字游戏
num = -1
guess = 7
while num != guess:
try:
num = int(input("please guess num: "))
except:
continue
if num > guess:
print("Guess little big")
elif num < guess:
print("Guess little small")
print("Brilliant! Guess right!")
#计算1-100和
n = 100
i = 1
sum = 0
while i <= n:
sum += i
i += 1
print("1到%d间的和为:%d"%(n,sum))
#for in
sites = ["Baidu", "Google","Running","Taobao"]
for site in sites:
if site == "Running":
print("跑步教程!")
break
print("循环数据 " + site)
else:
print("没有循环数据!")
print("完成循环!")
for i in range(5):
print(i)
for i in range(6,9):
print(i)
for i in range(1,10,3):
print(i)
#迭代器iter() next()
list = [1,2,3,4]
it = iter(list)
for x in it:
print(x,end=" ")
print("")
'''
it2 = iter(list)
import sys
while True:
try:
print(next(it2),end=" ")
except:
sys.exit()
'''
#迭代
class MyNumbers:
def __iter__(self):
self.a = 0
return self
def __next__(self):
self.a+= 1
return self.a
myClass = MyNumbers()
it3 = iter(myClass)
print(next(it3))
print(next(it3))
print(next(it3))
print(next(it3))
#生成器yield
def myYield_1():
a, i = 'yield', 0
while True:
print('before #%d' % i, end=", ")
yield a, i
print('after #%d' % i, end=", ")
i += 1
it1 = iter(myYield_1())
for i in range(10):
print("next #%d" % i, end=": ")
print(next(it1))
print('\n')
#调用函数时,如果没有传递参数,则会使用默认参数
def testcase( name,age=30):
print("age = ", age)
print("name = ", name)
return
testcase('cat',18)
testcase( "dog")
#不定长参数 元组
def rollcall(name1,*name):
print("点名:")
print(name1)
print(name)
for sname in name:
print(sname)
return
rollcall("zhangsan","lisi","wanger","mazi")
#字典
def rollcallagain(name1, **name):
print("再点名:")
print(name1)
print(name)
rollcallagain("xiaoli",xiaowang="wangzi",xiaowangba="pet")
#匿名函数 lambda
sum = lambda arg1,arg2:arg1+arg2
print("sum = ",sum(1,1))
#堆栈
stack = [1,2,3]
stack.append(4)
print(stack)
stack.pop()
print(stack)
#deque 双端队列
from collections import deque
dequetest = deque(["zsan","lsi","wer"])
dequetest.append("mzi")
dequetest.popleft()
print(dequetest)
#列表推导式
vec1 = [1,3,5]
vec2 = [2,4,6]
vec3 = [x*y for x in vec1 for y in vec2]
print(vec3)
matrix = [[1, 2, 3, 4],[5, 6, 7, 8],[9, 10, 11, 12],]
print([row[i] for row in matrix for i in range(2)])
#del
a = [-1, 1, 66.25, 333, 333, 1234.5]
del a[2:4]
print(a)
#元组和序列
t = 12345, 54321, 'hello!'
u = t, (1, 2, 3, 4, 5)
print(t)
print(u)
#集合 无序不重复元素的集,基本功能包括关系测试和消除重复元素
basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'}
print(basket)
#字典
tel = {'jack': 4098, 'sape': 4139}
tel['guido'] = 4127
print(tel)
#构造函数 dict() 直接从键值对元组列表中构建字典
dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
{x: x**2 for x in (2, 4, 6)}
dict(sape=4139, guido=4127, jack=4098)
#遍历技巧
#在字典中遍历时,关键字和对应的值可以使用 items() 方法同时解读出来
knights = {'gallahad': 'the pure', 'robin': 'the brave'}
for k, v in knights.items():
print(k, v)
#在序列中遍历时,索引位置和对应值可以使用 enumerate() 函数同时得到
for i, v in enumerate(['tic', 'tac', 'toe']):
print(i, v)
#同时遍历两个或更多的序列,可以使用 zip() 组合
questions = ['name', 'quest', 'favorite color']
answers = ['lancelot', 'the holy grail', 'blue']
for q, a in zip(questions, answers):
print('What is your {0}? It is {1}.'.format(q, a))
#反向遍历一个序列,首先指定这个序列,然后调用 reversed() 函数:
for i in reversed(range(1, 10, 2)):
print(i)
#要按顺序遍历一个序列,使用 sorted() 函数返回一个已排序的序列,并不修改原值
basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
for f in sorted(set(basket)):
print(f)
运行结果
1,1,2,3,5,8,
请输入你家狗的年龄7
相当于47岁的人!
please guess num: 7
Brilliant! Guess right!
1到100间的和为:5050
循环数据 Baidu
循环数据 Google
跑步教程!
完成循环!
0
1
2
3
4
6
7
8
1
4
7
1 2 3 4
1
2
3
4
next #0: before #0, ('yield', 0)
next #1: after #0, before #1, ('yield', 1)
next #2: after #1, before #2, ('yield', 2)
next #3: after #2, before #3, ('yield', 3)
next #4: after #3, before #4, ('yield', 4)
next #5: after #4, before #5, ('yield', 5)
next #6: after #5, before #6, ('yield', 6)
next #7: after #6, before #7, ('yield', 7)
next #8: after #7, before #8, ('yield', 8)
next #9: after #8, before #9, ('yield', 9)
age = 18
name = cat
age = 30
name = dog
点名:
zhangsan
('lisi', 'wanger', 'mazi')
lisi
wanger
mazi
再点名:
xiaoli
{'xiaowang': 'wangzi', 'xiaowangba': 'pet'}
sum = 2
[1, 2, 3, 4]
[1, 2, 3]
deque(['lsi', 'wer', 'mzi'])
[2, 4, 6, 6, 12, 18, 10, 20, 30]
[1, 2, 5, 6, 9, 10]
[-1, 1, 333, 1234.5]
(12345, 54321, 'hello!')
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
{'pear', 'banana', 'apple', 'orange'}
{'jack': 4098, 'sape': 4139, 'guido': 4127}
gallahad the pure
robin the brave
0 tic
1 tac
2 toe
What is your name? It is lancelot.
What is your quest? It is the holy grail.
What is your favorite color? It is blue.
9
7
5
3
1
apple
banana
orange
pear