都是根据课程进度,学习过程中编写的代码,有任何问题都可以沟通。
石头剪刀布小游戏
?
import random
while(1):
user=int(input("请输入:剪刀(0)、石头(1)、布(2):"))
if user==0:
print("你的输入为:剪刀(0)")
elif user==1:
print("你的输入为:石头(1)")
elif user==2:
print("你的输入为:布(2)")
if user==0 or user==1 or user==2 :
break;
else:
print("用户输入格式不对,请重新输入!")
computer = random.randint(0,2)
print("随机生成数字:%s"%computer)
if (user==0 and computer==1) or(user==1 and computer==2)\
or (user==2 and computer==0):
print("哈哈,你输了")
elif (user==0 and computer==2) or(user==2 and computer==1)\
or (user==1 and computer==0):
print("哈哈,你赢了")
elif (user==0 and computer==0) or(user==1 and computer==1)\
or (user==2 and computer==2):
print("哈哈,打平了")
打印九九乘法表?
while循环实现
i=1
while i<=9:
j = 1
while j<=i:
print("%d*%d=%d"%(j,i,i*j),end="\t")
j+=1
print("\t")
i+=1
for循环实现
for i in range(1,10):
for j in range(1,i+1):
print("%d*%d=%d"%(j,i,i*j),end="\t")
print("\t")
实现购物车功能
products = [["iphone", 6888], ["MacPro", 14800], ["小米6", 2499],
["Coffee", 31], ["Book", 60], ["Nike", 699]]
print("-"*6+"商品列表"+"-"*6)
i = 0
for product in products:#实现输出商品列表
print("%d" % i, end="")
for name in product:
print(" %s " % name, end="\t")
i += 1
print("\t")
shopping = []
while 1:#购物者想买的编号
a = input("你想要买什么 请选择编号:")
if a == "q":
break
shopping.append(products[int(a)])
print("购物车内有以下商品:")
for shop in shopping:
for product in shop:
print("%s" % product, end="\t")
print("\t")
?古诗写入文件中
f=open("gushi.txt","w",encoding="utf-8")
f.write(''' 《惠崇春江晓景》
苏轼
竹外桃花三两枝,春江水暖鸭先知。
蒌蒿满地芦芽短,正是洒豚欲上时。
''')
f.close()
try:
f=open("gushi.txt",encoding="utf-8")#编码格式不要忘记
f1=open("copy.txt","w",encoding="utf-8")
try:
def copy1(f, f1):#复制到copy.txt
content = f.readlines()
for i in content:
f1.write(i)
print("复制完毕")
def read1 (f): # 读文件
i = 1
content = f.readlines()
for temp in content:
print("%d:%s" % (i, temp),end="")
i += 1
def write1(f,f0):#写文件
content = f.readlines()
for i in content:
f1.write(i)
copy1(f, f1)
f = open("gushi.txt", encoding="utf-8")
read1(f)
except Exception as result:
print("产生异常")
print(result)
finally:
f.close()
f1.close()
except:
print("有异常!")
|