内容正文:
少儿编程课
1
扑克游戏之比拼
2
字符串
h = '黑桃 红桃 方片 梅花'
s= '2 3 4 5 6 7 8 9 10 J Q K A'
运行结果:
梅花
K A
填写代码处
3
字符串操作指令
split():通过指定分隔符对字符串进行切片
分隔符:默认为所有的空字符,包括空格、换行、制表符
h = '黑桃 红桃 方片 梅花'.split()
s= '2 3 4 5 6 7 8 9 10 J Q K A'.split()
print(h)
print(s)
4
双重for循环
for x in 列表名称:
#需要重复执行的代码
#需要重复执行的代码
for y in 列表名称:
#需要重复执行的代码
循环中的代码需要缩进4个空格
l=[1,2,3,4]
for i in l:
print(i)
此处的i是遍历列表中的元素值
生成纸牌
h = '黑桃 红桃 方片 梅花'.split()
s= '2 3 4 5 6 7 8 9 10 J Q K A'.split()
p = []
for i in h:
for j in s:
temp = i +' '+ j
p.append(temp)
随机获取指令
sample(列表,n):从列表中随机抽取n个元素,并以列表的形式返回
import random
li=['a','b','c','d','e']
temp=random.sample(li,2)
print(temp)
注意:结果是随机的,每一次都不确定
指令应用
从所有纸牌中随机抽取2张纸牌
…
result = random.sample(p,2)
you = result[0]
me = result[1]
print('小朋友的牌:',you,'老师的牌:',me)
…
查找指令
index(str):检测字符串中是否包含子字符串str
s="abcdefg"
a=s.index("abc")
print(a)
运行结果:
0
s="abcdefg"
a=s.index("fg")
print(a)
运行结果:
5
指令应用
比较大小的结果为:True或False
import random
s="2345678"
result=random.sample(s,2)
print(result)
your=s.index(result[0])
my=s.index(result[1])
print(your>my)
10
通过位置比较
…
your = s.index(you.split()[1])
my = s.index(me.split()[1])
…
找到数字纸牌所在列表中的位置
11
比较大小
if your > my:
print('小朋友赢了!')
elif your == my:
print('不分伯仲')
else:
print('老师赢了!')
12
$$