我目前正在研究用Python 3.5编写的Yahtzee游戏。我已经定义了一个函数,要求用户输入将要播放的人的姓名,然后再检查这是否正确。
def get_player_names():
while True:
print("Who are playing today? ")
players = [str(x) for x in input().split()]
n = len(players)
if n == 1:
for p in players:
print("So", p, "is playing alone today.")
choice = input("Is this correct?(y/n)\n")
if choice == "y" or "Y":
break
elif choice == "n" or "N":
continue
else:
print("You should enter either y/Y or n/N")
continue
elif n > 1:
print("So today, ", n, " people are playing, and their names are: ")
for p in players:
print(p)
choice = input("Is this correct?(y/n)\n")
if choice == "y" or "Y":
break
elif choice == "n" or "N":
continue
else:
print("You should enter either y/Y or n/N")
continue
else:
print("Sorry, but at least one person has to participate")
continue
placeholder()
def placeholder():
print("KTITENS")
get_player_names()
程序创建没有问题的玩家列表,以及当用户确认玩家的名字是正确的时,此时循环中断并调用下一个函数。 (目前这只是打印KITTENS的功能。问题是,如果用户输入" n" /" N"或其他什么,我希望循环重复,但它而是打破了。
希望有人可以帮助我!如果这个问题重复,请道歉,但我找不到有关Python 3的类似问题。
答案 0 :(得分:4)
问题是这些问题:
if choice == "y" or "Y":
break
elif choice == "n" or "N":
# Some stuff
应该是:
if choice == "y" or choice == "Y":
break
elif choice == "n" or choice == "N":
# Some stuff
实际上,or "Y"
始终为真,因此始终会调用break
。
您可以在python控制台中输入以下内容来检查:
>>> if 'randomstring': print('Yup, this is True')
Yup, this is True
答案 1 :(得分:2)
更改
if choice == "y" or "Y":
break
elif choice == "n" or "N":
continue
到
if choice == "y" or choice =="Y":
break
elif choice == "n" or choice =="N":
continue
'Y'
是非空字符串,因此bool('Y')
始终为True
您可以在此处阅读Truth Value Testing