python - 我怎样才能把它放在一个循环中,在开始时尝试使用一个while循环,但我会得到错误的输出
问题描述
程序模拟两个六面骰子的掷骰,如果两个骰子的得分相同(例如:(6,6))等于双倍。
我希望用户在掷骰子并显示双打数量后能够再次去。
提前致谢。
import random
user_input= int(input("How many times would you like to roll the dice?"))
Dice_1 = [random.randint(1,6) for x in range(user_input)]
Dice_2 = [random.randint(1,6) for x in range(user_input)]
count = 0
for a,b in zip(Dice_1,Dice_2):
if((a)) == ((b)):
print("double")
count += 1
else:
print((a,b))
print(f'\nYou have scored {count} doubles! out of {user_input}')
解决方案
所以我不确定你的第一次尝试,但我想说即使失败了,看看你尝试了什么也会很棒:)
使用 while 循环是最简单、最方便的方法。例如
import random
while user_input := int(input("How many times would you like to roll the dice?")) :
Dice_1 = ...
... # roll dice, blah blah
会做你想做的。输入 0 将中断 while 循环(因为0
在 python 中被认为是假的,即while 0
->while False
并且任何其他整数都被认为是真)。请注意,它使用海象运算符:=
而不是=
没有海象运算符,上面与下面类似:
user_input = int(input("How many times would you like to roll the dice?"))
while user_input != 0:
... # roll dice, blah blah
#then ask again if they want to roll again
user_input = int(input("How many times would you like to roll the dice?")
:=
海象运算符只是使其更具可读性的一种方法(它计算结果值并将:= int(input("How many times would you like to roll the dice?"))
其分配给user_input
)。
推荐阅读
- javascript - 如何使用 AVA 框架根据某些条件(比如说环境变量)跳过测试执行
- amazon-web-services - 关闭 ssh 会话后,我想在 aws ec2 中运行一个进程
- xamarin - 是否有另一种方法可以在不使用 Convert 的情况下转换用户在条目中输入的值?....(Convert.ToDouble 或 Convert.ToInt)
- firebase - 是音乐流媒体应用程序的理想之选。(扑)
- android - android:fontFamily 在 styles.xml 中不起作用
- timestamp - 四舍五入到最接近的十分钟 - Snowflake/SQL
- ios - Apple Developer Enterprise Program 应用程序没有图标
- python - 如何将一长串图像保存到特定目录?
- odoo - 在odoo中获取带有html格式的电子邮件正文
- java - 在 Sub-Fragment 中,当 webview 无法返回时,如何重定向到 Main-Fragment 或 Home-Fragment