Home > Blockchain >  how to make a loop that adds up items to a list in a given condtion and giving back the sum in pytho
how to make a loop that adds up items to a list in a given condtion and giving back the sum in pytho

Time:07-05

I use this:

import random
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
computer = []

def another_card_computer():
    for i in range(1):
        computer.append(random.choice(cards))

computer_score = sum(computer)
while computer_score < 17:
    another_card_computer()
computer_score = sum(computer)
print(computer_score)

for some reason, it just goes into an infinite loop. I'm new to programming, python, and stack overflow so let me know if there's any more info you need here.

thanks!

CodePudding user response:

This should work from what I can understand from the question

import random
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
computer = []
computer_score = 0
end = True #looping condition

while end:
    computer.append(random.choice(cards))
    computer_score = sum(computer)
    if computer_score >= 17:
        end = False
    else:
        print(computer_score)

if you want it as a function:

import random

def another_card_computer(card):
    computer = []
    computer_score = 0
    end = True #looping condition
    while end:
        computer.append(random.choice(cards))
        computer_score = sum(computer)
        if computer_score >= 17:
            end = False
        else:
            print(computer_score)
        
cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
another_card_computer(cards)

CodePudding user response:

Maybe this helps you to get started:

cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]

def fun(cards, n):
    computer = []
    while True:
        value = np.random.choice(cards, replace=False)
        cards.remove(value)
        if sum(computer)   value < n:
            computer.append(value)
        else:
            break
    return computer

fun(cards, 17)
  • Related