我一直在努力创建一个程序,将21张卡分成3堆。然后要求用户考虑卡并告诉程序哪个堆是他们的卡。此步骤重复4次,直到卡片正好位于21张卡片的中间。该程序应该转到用于打印用户卡的end()
函数,问题是,一切正常,但它会在end()
函数中打印语句5次。我知道它可能是非常愚蠢的东西,但我想不出解决方案。提前谢谢。
import random
cards = []
count = 0
def end():
print("Your card is: ", cards[10])
def split():
def choice():
global count
while True:
if count >=0 and count <= 3:
global cards
user = input("Think of a card. Now to which pile does your card belong to?: ")
count = count + 1
if user == "1":
del cards[:]
cards = (pile_2 + pile_1 + pile_3)
print(cards)
split()
elif user == "2":
del cards[:]
cards = (pile_1 + pile_2 + pile_3)
print(cards)
split()
elif user == "3":
del cards[:]
cards = (pile_1 + pile_3 + pile_2)
print(cards)
split()
else:
print("Invalid input")
main()
elif count == 4:
end()
break
pile_1 = []
pile_2 = []
pile_3 = []
counter = 0
sub_counter = 0
while True:
if sub_counter >= 0 and sub_counter <= 20:
for item in cards:
if counter == 0:
pile_1.append(item)
counter = counter + 1
elif counter == 1:
pile_2.append(item)
counter = counter + 1
elif counter == 2:
pile_3.append(item)
counter = 0
sub_counter = sub_counter + 1
elif sub_counter == 21:
False
break
print()
print("first pile: ", pile_1)
print("second pile: ", pile_2)
print("third pile: ", pile_3)
choice()
def main():
file = open('cards.txt.', 'r')
for line in file:
cards.append(line)
file.close
random.shuffle(cards)
print(cards)
split()
main()
答案 0 :(得分:2)
你有递归电话。 split()调用choose()然后再次调用split(),这可以调用main()再调用split()。
答案 1 :(得分:1)
当你到达elif count == 4行时,count总是为4.这就是原因。如果你改变顺序,我可以预感它可以工作:
...
if count == 4:
end()
break
elif count >= 0 and count <=3:
...
但是,如果你可以在没有全局变量的情况下编写它,那就更好了。您可以使用本地变量而不是全局变量作为参数传递给下一个函数。像这样:
import random
def end(cards):
print("Your card is: ", cards[10])
def choice(count,pile_1,pile_2,pile_3):
while True:
user = input("Think of a card. Now to which pile does your card belong to?: ")
if user == "1":
cards = (pile_2 + pile_1 + pile_3)
print(cards)
split(count+1, cards)
break
elif user == "2":
cards = (pile_1 + pile_2 + pile_3)
print(cards)
split(count+1, cards)
break
elif user == "3":
cards = (pile_1 + pile_3 + pile_2)
print(cards)
split(count+1, cards)
break
else:
print("Invalid input")
def split(count,cards):
if count == 4:
end(cards)
return
pile_1 = []
pile_2 = []
pile_3 = []
for i in range(0,21,3):
pile_1.append(cards[i])
pile_2.append(cards[i+1])
pile_3.append(cards[i+2])
print()
print("first pile: ", pile_1)
print("second pile: ", pile_2)
print("third pile: ", pile_3)
choice(count,pile_1,pile_2,pile_3)
def main():
cards = []
file = open('cards.txt.', 'r')
for line in file:
cards.append(line.strip())
file.close
random.shuffle(cards)
print(cards)
split(0, cards)
main()
答案 2 :(得分:0)
我找到了一个解决方案:
这只是一个身份问题,
而不是:
elif count == 4:
end()
break
我把break语句放在与elif相同的行上:
elif count == 4:
end()
break
似乎解决了它