python 小游戏
1、石头、剪刀、布
import random player = int(input("石头1,剪刀2,布3,玩家请出拳:")) # randint 返回 1<= ran <=3 computer = random.randint(1,3) # if 语句太长时可以将条件用括号括起来,然后换行 if ((player==1 and computer ==2) or (player == 2 and computer == 3) or (player == 3 and computer == 1)): # 多个格式化输出变量要用括号括起来,中间加逗号 print("玩家出拳是: %d , 电脑出拳是: %d" % (player ,computer)) print("你赢了,你很厉害") elif player == computer: print("平局,加油!") else: print("你输了!") print("玩家出拳是: %d , 电脑出拳是: %d" % (player ,computer))
2、循环比赛多次
import random loop = int(input("请输入比赛次数:")) i = 0 player_win = 0 computer_win =0 while i < loop: player = int(input("石头1,剪刀2,布3,玩家请出拳:")) # randint 返回 1<= ran <=3 computer = random.randint(1,3) # if 语句太长时可以将条件用括号括起来,然后换行 if ((player==1 and computer ==2) or (player == 2 and computer == 3) or (player == 3 and computer == 1)): # 多个格式化输出变量要用括号括起来,中间加逗号 print("玩家出拳是: %d , 电脑出拳是: %d" % (player ,computer)) print("你赢了,你很厉害") player_win = player_win +1 elif player == computer: print("平局,加油!") else: print("你输了!") print("玩家出拳是: %d , 电脑出拳是: %d" % (player ,computer)) computer_win = computer_win +1 i = i +1 print("玩家获胜次数:%d ,电脑获胜次数:%d " % (player_win,computer_win))
3、输出三角形
i = 0 while i < 10: print("*" * i) i += 1

4、使用嵌套语句输出三角形
i = 1 while i <= 9: j = 1 while j <= i: print("*",end ="") #print("第%d行第%d列" % (i,j)) j += 1 #此句作用是输出一行后,输出下一行前进行换行,注意缩进要在内循环之外 print("") #print("第%d行" % i) i += 1
5、九九乘法表
i = 1 while i <= 9: j = 1 while j <= i: # end 中加个空格 print("%d * %d = %d" % (j,i,i*j),end =" ") j += 1 print("") i += 1

6、\t制表符作用是保证在垂直方向对其
i = 1 while i <= 9: j = 1 while j <= i: # end 中加个\t制表符,保证垂直方向对其 print("%d * %d = %d" % (j,i,i*j),end ="\t") j += 1 print("") i += 1


浙公网安备 33010602011771号