卡技巧程序

我一直在试图创建一个程序,将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()

回答:

当你到达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()

回答:

你有递归调用。 split()调用choice(),然后再调用split(),它可以调用main(),它再次调用split()。

回答:

我已经找到了解决办法:

这仅仅是一个的ident的事,

代替:

elif count == 4: 

end()

break

我把break语句上与elif相同的行:

elif count == 4: 

end()

break

这似乎解决了它

以上是 卡技巧程序 的全部内容, 来源链接: utcz.com/qa/258452.html

回到顶部