python - Python重启程序1
问题描述
如果用户从掷骰子中选择两个数字所获得的信息已经从整个列表中消失,我正在尝试重新启动该程序。它会要求他们再次滚动,刚刚发生的一切都会像他们从未点击过“e”一样返回。
roll = input("Player turn, enter 'e' to roll : ")
dice_lst = []
if roll == "e":
for e in range(num_dice):
d_lst = random.randint(1,6)
dice_lst.append(d_lst)
else:
print("Invalid ----- Please enter 'e' to roll the dice")
# Add in the invalid input error
print("")
print("You rolled", dice_lst)
dice_choose = int(input("Choose a dice : "))
dice_lst.remove(dice_choose)
print("")
print("You are left with", dice_lst)
dice_choose1 = int(input("Choose a dice : "))
dice_lst.remove(dice_choose1)
print("")
while True:
sum1 = dice_choose + dice_choose1
if sum1 in lst_player:
break
else:
print("You have made an invalid choice")
sum1 = dice_choose + dice_choose1
print(dice_choose, "+", dice_choose1, "sums to", sum1)
print(sum1, "will be removed")
print("")
lst_player.remove(sum1)
解决方案
如果您想重复代码直到满足某些条件,您可以使用while True
循环或while <condition>
循环,continue
在达到某些无效情况时使用(继续下一次迭代)“重置”:
while True:
roll = input("Player turn, enter 'e' to roll : ")
dice_lst = []
if roll == "e":
for e in range(num_dice):
d_lst = random.randint(1,6)
dice_lst.append(d_lst)
else:
print("Invalid input")
continue # Go back to asking the player to roll
print("")
print("You rolled", dice_lst)
dice_choose = int(input("Choose a dice : "))
dice_lst.remove(dice_choose)
print("")
print("You are left with", dice_lst)
dice_choose1 = int(input("Choose a dice : "))
dice_lst.remove(dice_choose1)
print("")
sum1 = dice_choose + dice_choose1
if sum1 not in lst_player:
print("You have made an invalid choice")
continue # Go back to asking the player to roll
print(dice_choose, "+", dice_choose1, "sums to", sum1)
print(sum1, "will be removed")
print("")
lst_player.remove(sum1)
break # Break out of the loop
我不完全确定这段代码是如何工作的,但你可能需要在continue
.
推荐阅读
- r - R中数组单元的平均值/总和
- laravel - Laravel Mix 和导入文件
- amazon-web-services - 启动 AWS 多节点 Ray 集群并提交简单的 python 脚本以在 conda env 中运行
- angular - Angular Reactive Forms - 重复对象
- python - pyOpenSSL 中的 PKCS#12 支持已弃用
- excel - 尝试匹配两行文本并在 excel 中返回第三行
- android - Android kotlin 日志库
- python - 从 Thread 创建的子进程中获取进程 ID
- python - 用python将XML转换为JSON,JSON中子节点后面的父属性
- c# - 将导入数据存储在变量中的最佳方法