我正在尝试使用while循环创建一个骰子游戏,如果是的话。我已经成功完成了这个,但是我想弄清楚如何对游戏进行编程,这样如果没有输入数字4,6或12,它将表示无效选择并将再次询问diceChoice。 有人可以帮忙吗?
到目前为止,我有......
rollAgain = "Yes" or "yes" or "y"
while rollAgain == "Yes" or "yes" or "y":
diceChoice = input ("Which dice would you like to roll; 4 sided, 6, sided or 12 sided?")
if diceChoice == "4":
import random
print("You rolled a ", random.randint(1,4))
if diceChoice == "6":
import random
print("You rolled a ", random.randint(1,6))
if diceChoice == "12":
import random
print("You rolled a ", random.randint(1,12))
rollAgain = input ("Roll Again?")
print ("Thank you for playing")
答案 0 :(得分:3)
固定While循环,整理所有重复。将导入语句移至顶部。结构化允许rollAgain和diceChoice的更多选项。
import random
rollAgain = "Yes"
while rollAgain in ["Yes" , "yes", "y"]:
diceChoice = input ("Which dice would you like to roll; 4 sided, 6, sided or 12 sided?")
if diceChoice in ["4","6","12"]:
print("You rolled a ",random.randint(1,int(diceChoice)))
else:
print "Please input 4,6, or 12."
rollAgain = input ("Roll Again?")
print ("Thank you for playing")
执行此类任务:
rollAgain = "Yes" or "yes" or "y"
是不必要的 - 只输入第一个值。为此变量选择一个;你只需要一个用于它的目的。
这种作业在这里也不起作用:
while rollAgain == "Yes" or "yes" or "y":
它将再次仅检查第一个值。您要么像其他海报一样将其拆分,要么使用不同的数据结构,将它们全部合并为上面代码中的列表。
答案 1 :(得分:1)
你应该只在顶部随机导入一次
import random #put this as the first line
您的rollAgain声明只应将其设置为一个值
rollAgain = "yes" # the or statements were not necessary
您忘记在后续条件中执行rollAgain ==
,这是一种更简单的方式
while rollAgain.lower().startswith("y"): #makes sure it starts with y or Y
要执行无效输入语句,您可以使用elif:
和else:
语句来保持简单
if diceChoice == "4":
print("You rolled a ", random.randint(1,4))
elif diceChoice == "6":
print("You rolled a ", random.randint(1,6))
elif diceChoice == "12":
print("You rolled a ", random.randint(1,12))
else:
print("Invalid Input, please enter either 4, 6, or 12")
你旧的while循环永远不会退出,因为你基本上是这样说的
while rollAgain == "Yes" or True or True #because non-empty strings are treated as True
编辑,因为您询问了in
语句,这是一个简短的例子
>>>5 in [1,2,3,4]
False
>>>5 in [1,2,3,4,5]
True
in
语句与其他语言中的contains()
类似,它检查变量是否在列表中
由于5
不在列表[1,2,3,4]
中,因此返回False
但是,5
位于列表[1,2,3,4,5]
中,因此返回True
您可以在代码中使用这几个位置,特别是如果您想确保变量位于一组选项中。我不建议你为它保持简单。
答案 2 :(得分:0)
diceChoice = None
while diceChoice not in ["4","12","6"]:
diceChoice = input("enter choice of dice(4,6,12)")
print "You picked %d"%diceChoice
答案 3 :(得分:0)
我接受它:
# If you are only using one function from random
# then it seems cleaner to just import that name
from random import randint
while True:
choice = int(input("Which dice would you like to roll; 4 sided, 6, sided or 12 sided?\n:"))
# Using sets for 'in' comparisons is faster
if choice in {4, 6, 12}:
print("You rolled a", randint(1, choice))
else:
print("Please input 4, 6, or 12.")
# Make the input lowercase so that it will accept anything that can be
# interpreted as "yes".
if input("Roll Again?\n:").lower() not in {"yes", "y"}:
# End the game by breaking the loop
break
# You should use an input at the end to keep the window open to see the results
input("Thank you for playing!")