赞
踩
练习9-13:骰子
创建一个Die类,它包含一个名为sides的属性,该属性的默认值为6。编写一个名为roll_die()的方法,它打印位于1和骰子面数之间的随机数。创建一个6面的骰子再掷10次。
- class Die:
- def __init__(self, sides=6):
- self.sides = sides
-
- def roll_die(self):
- from random import randint
- sides = randint(1, self.sides)
- print(f"这个数是{sides}")
-
- print("当面数是6时,掷10次:")
- roll1 = Die()
- roll1.roll_die()
- roll1.roll_die()
- roll1.roll_die()
- roll1.roll_die()
- roll1.roll_die()
- roll1.roll_die()
- roll1.roll_die()
- roll1.roll_die()
- roll1.roll_die()
- roll1.roll_die()
-
- print("当面数是10时,掷10次:")
- roll2 = Die(10)
- roll2.roll_die()
- roll2.roll_die()
- roll2.roll_die()
- roll2.roll_die()
- roll2.roll_die()
- roll2.roll_die()
- roll2.roll_die()
- roll2.roll_die()
- roll2.roll_die()
- roll2.roll_die()
-
- print("当面数是20时,掷10次:")
- roll3 = Die(20)
- roll3.roll_die()
- roll3.roll_die()
- roll3.roll_die()
- roll3.roll_die()
- roll3.roll_die()
- roll3.roll_die()
- roll3.roll_die()
- roll3.roll_die()
- roll3.roll_die()
- roll3.roll_die()
运行结果如图:
每个都要掷10次,我原本想要再加一个方法,调用10次函数,times的次数也是一个未知数,但调用不知道应该怎么表示,无果,最后采用了另一种方式,如下
- class Die:
- def __init__(self,sides=6):
- self.sides = sides
-
- def roll_die(self):
- from random import randint
- sides = randint(1, self.sides)
- print(f"这个数是{sides}")
-
-
- print("当面数是6时,掷10次:")
- roll1 = Die()
- current_num = 1
- while current_num <= 10:
- roll1.roll_die()
- current_num += 1
-
- print("当面数是10时,掷10次:")
- roll2 = Die(10)
- current_num = 1
- while current_num <= 10:
- roll2.roll_die()
- current_num += 1
-
- print("当面数是20时,掷10次:")
- roll3 = Die(20)
- current_num = 1
- while current_num <= 10:
- roll3.roll_die()
- current_num += 1
运行没有问题哦
- class Die:
- def __init__(self,times,sides=6):
- self.sides = sides
- self.times = times
-
- def roll_die(self):
- from random import randint
- sides = randint(1, self.sides)
- print(f"这个数是{sides}")
-
- def roll_time(self):
- current_num = 1
- times = self.times
- while current_num <= times:
- rollx = Die(self.times, self.sides)
- rollx.roll_die()
- current_num += 1
-
-
- print("当面数是6时,掷10次:")
- roll1 = Die(10)
- roll1.roll_time()
-
- print("当面数是10时,掷10次:")
- roll2 = Die(10,10)
- roll2.roll_time()
-
- print("当面数是20时,掷10次:")
- roll3 = Die(10,20)
- roll3.roll_time()
注意点:
1.第一次使用pycharm,使用过程中方便很多,比如“引号、(括号等,pycharm会自动填充,体验非常好。
2.pycharm 自查报错第一次看有很多不懂,可以完整写完后运行试试。
3.最后一个意外成功了,因为我一开始rollx还不知道怎么办,还尝试把roll1=rollx,显示rollx没有定义,我都快放弃了,没想到成功了!挺意外的
1.要举一反三,把知识用起来
2.简洁
3.循环总觉得还有更好的方法
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。