assert 3 > 7
# AssertionError
count = 0
while count < 3:
temp = input("猜一猜小姐姐想的是哪个数字?")
guess = int(temp)
if guess > 8:
print("大了,大了")
else:
if guess == 8:
print("你太了解小姐姐的心思了!")
print("哼,猜对也没有奖励!")
count = 3
else:
print("小了,小了")
count = count + 1
print("游戏结束,不玩儿啦!")
string = 'abcd'
while string:
print(string)
string = string[1:]
# abcd
# bcd
# cd
# d
x = 5
while x >= 0:
x -= 1
if x < 3:
break
print(x)
else: print('x小于5')
#4
#3
例(无break):会一直执行到else
x = 5
while x >= 0:
x -= 1
print(x)
else: print('x小于5')
#4
#3
#2
#1
#0
#-1
x小于5
member = ['张三', '李四', '刘德华', '刘六', '周润发']
for each in member:
print(each)
# 张三
# 李四
# 刘德华
# 刘六
# 周润发
for i in range(len(member)):
print(member[i])
# 张三
# 李四
# 刘德华
# 刘六
# 周润发
dic = {
'a': 1, 'b': 2, 'c': 3, 'd': 4}
for key, value in dic.items(): #items返回tuple(元组)
print(key, value, sep=':', end=' ')
# a:1 b:2 c:3 d:4
遍历所有keys
dic = {
'a': 1, 'b': 2, 'c': 3, 'd': 4
for key in dic.keys():
print(key, end=' ')
# a b c d
dic = {
'a': 1, 'b': 2, 'c': 3, 'd': 4}
for value in dic.values():
print(value, end=' ')
# 1 2 3 4
list = [1, 2, 3, 4, 5]
for x in list:
if x > 4:
break
print(x)
else:
print('list没有完成遍历')
#1
#2
#3
#4
list = [1, 2, 3, 4, 5]
for x in list:
print(x)
else:
print('list完成遍历')
#1
#2
#3
#4
#5
list完成遍历
for i in range(1, 10, 2):
print(i)
# 1
# 3
# 5
# 7
# 9
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
lst = list(enumerate(seasons))
print(lst)
# [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
lst = list(enumerate(seasons, start=1)) # 下标从 1 开始
print(lst)
# [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
例2
for i, language in enumerate(languages, 2):
print(i, 'I love', language)
print('Done!')
# 2 I love Python
# 3 I love R
# 4 I love Matlab
# 5 I love C++
# Done!
x = [-4, -2, 0, 2, 4]
y = [a * 2 for a in x]
print(y)
# [-8, -4, 0, 4, 8]
例2
x = [i for i in range(100) if (i % 2) != 0 and (i % 3) == 0]
print(x)
# [3, 9, 15, 21, 27, 33, 39, 45, 51, 57, 63, 69, 75, 81, 87, 93, 99]
例3
a = [(i, j) for i in range(0, 3) if i < 1 for j in range(0, 3) if j > 1]
print(a)
# [(0, 2)]
a = (x for x in range(10))
print(a)
# at 0x0000025BE511CC48>
print(tuple(a))
# (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
b = {
i: i % 2 == 0 for i in range(10) if i % 3 == 0}
print(b)
# {0: True, 3: False, 6: True, 9: False}
c = {
i for i in [1, 2, 3, 4, 5, 5, 6, 4, 3, 2, 1]}
print(c)
# {1, 2, 3, 4, 5, 6}
e = (i for i in range(3))
while True:
print(next(e, '-1')) #如e没有对应的值,一直返回-1
s = sum([i for i in range(101)])
print(s) # 5050