10.3 Case Study: Lotto Numbers
LISTING 10.2 LottoNumbers.py
isCovered = 99 * [False] # 初始化一个列表
endOfInput = True #设定一个跳出loop的判定值
while endOfInput:
s = input("Enter a line of numbers separated by space:\n") #用户输入数字并以“空格”隔开
item = s.split()
lst = [eval(x) for x in item] # 注意这种语法格式convert every string in item to number
for number in lst:
if number == 0:
endOfInput = False
else:
isCovered[number -1] = True #将与之对应的位置标记成"True"
allCovered = True #初始化一个值,假设所有值都覆盖了
for i in range(99):
if isCovered[i] == False: #如果有数没有覆盖,初始值设为F
allCovered = False
break
if allCovered:
print("The tickets cover all numbers")
else:
print("The tickets don't cover all numbers")
----------------------------小节分割线-----------------------------
10.4 Case Study: Deck of Cards
从52张扑克牌中任意抽取4张。
deck = [x for x in range(52)]
初始化deck列表,并赋值0~51,代表52张牌。注意每个数字代表特定的扑克牌,后面会有解释为什么。(利用[ ]和for语句初始化列表),或
deck = list(range(52))
使用list()函数和range()函数初始化列表
数字 0~12 spades 黑桃,
数字 13~25 hearts 红心,
数字 26~38 diamands 方块,
数字 39~51 clubs 草花,
52张牌的号码对应52张扑克,例如: 牌号为 3 ,3 // 3 是 0 代表 Spades(黑桃),3 % 13 是 3 代表4,所以牌号3代表黑桃4
LISTING 10.3 DeckOfCards.py
deck = [x for x in range(52)]
suits = ["Spades", "Hearts", "Diamonds", "Clubs"]
ranks = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"]
import random
random.shuffle(deck) #洗牌
for i in range(4):
suit = suits[deck[i] // 13]
rank = ranks[deck[i] % 13]
print("Card number", deck[i], "is the", rank, "of", suit)
-------------------------------小节分割线----------------------------------------------
10.5 Deck of Cards GUI
跳过
----------------------------------小节分割线-------------------------------------------
10.6 Copying Lists
list2 = list1
并不是把list1的值拷贝给list2,原因看下图