一、石头剪刀布游戏
# -*- coding = utf-8 -*-
# @Time : 2021-07-06 17:46
# @Author : xs
# @File : demo1.py
# @Software : PyCharm
import random
'''
print("请输入剪刀(0)、石头(1)、布(2):")
while True:
a = int(input())
if a==0 or a==1 or a==2:
break
else:
print("你的输入不符合规范!请重新输入:")
continue
'''
a = input("请输入剪刀(0)、石头(1)、布(2):")
while a!=str(0) and a!=str(1) and a!=str(2):
a=input("你的输入不符合规范!请重新输入:")
b = random.randint(0, 2)
print("你的输入为:", a)
print("随机生成数字为", b)
a = int(a)
if (a == 0 and b == 1) or (a == 1 and b == 2) or (a == 2 and b == 0):
print("你输了")
else:
print("你赢了")
二、1-100求和
sum = 0
for i in range(1,101):
sum += i
print(sum)
三、九九乘法表
for循环:
for i in range(1,10):
for j in range(1,i+1):
print(i,"*",j,"=",i*j,sep="",end=" ")
if i == j:
print("")
while循环
i = 1
while i<10:
j = 1
while j <=i:
print(i,"*",j,"=",i*j,sep="",end=" ")
j += 1
if i<j:
print("")
i+=1
结果:
四、将8个老师随机分配到三个办公室
# 将8个老师随机分配到三个办公室
import random
office = [[], [], []]
teachers = ["A", "B", "C", "D", "E", "F", "G", "H"]
for i in teachers:
index = random.randint(0, 2)
office[index].append(i)
j = 0
for i in office:
j += 1
print("办公室%d"%j, "人数是%d "%(len(i)), end="")
for n in i:
print(n,end=" ")
print("")
结果:
五、列表打印输出
products = [["iphone", 6888], ["MacPro", 14800], ["小米6", 2499], ["Coffee", 31], ["Book", 60], ["Nike", 699]]
print("-"*6, " 商品列表 ", "-"*6)
for i, product in enumerate(products):
print("%d\t%s\t%d" % (i, product[0], product[1]))
六、文件复制
def readtxt():
try:
f1 = open("gushi.txt", "r")
content = f1.readlines()
print(content)
return content
except Exception:
print("出现异常")
finally:
f1.close()
print("f1文件已关闭")
def writetxt(content):
try:
f2 = open("copy.txt", "w")
f2.write(content)
except Exception as result:
print("出现异常,异常是:",result)
finally:
f2.close()
print("f2文件已关闭")
content =readtxt()
writetxt(content[0])