-1

How can I add all the numbers in a list? For instance, take the code below.

import random

cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
user_cards = random.sample(cards, 2)
user_score = user_cards[0 + 1]
print(f"Your cards: {user_cards}, your score: {user_score}")

The user randomly picks two cards from the list "cards", but the line

user_score = user_cards[0 + 1]

is not adding numbers together; it's just printing the second number. What am I doing wrong? I'm a confused beginner.

niamulbengali
  • 292
  • 1
  • 3
  • 16
mgksmv
  • 5
  • 1
  • 4
  • 2
    user_cards[0]+user_cards[1] – Berdan Akyürek Dec 06 '20 at 15:06
  • 1
    Are you familiar with the built-in [`sum()`](https://docs.python.org/3/library/functions.html#sum) function? In this specific case, of just 2 numbers, why not just do `user_cards[0] + user_cards[1]`? Does this answer your question? [Summing elements in a list](https://stackoverflow.com/questions/11344827/summing-elements-in-a-list) – Tomerikoo Dec 06 '20 at 15:09
  • 1
    FYI, what you are doing is trying to treat list indexing as a [homomorphism](https://en.wikipedia.org/wiki/Homomorphism) (i.e, assuming that `a[x] + a[y] == a[x + y]`). – chepner Dec 06 '20 at 15:09

3 Answers3

0

user_cards[0 + 1] this will always five you the user_cards[1]

You can do: user_score = user_cards[0] + user_cards[1] or use sum

import random

cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
user_cards = random.sample(cards, 2)
user_score = sum(user_cards) # or user_score = user_cards[0] + user_cards[1]
print(f"Your cards: {user_cards}, your score: {user_score}")
Kuldeep Singh Sidhu
  • 3,748
  • 2
  • 12
  • 22
0
 user_score = user_cards[0 + 1] 

This code call the second element only since 1+0 = 1 and user_cards[0 + 1] = user_cards[ 1]

you should write like below

 import random

cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
user_cards = random.sample(cards, 2)
user_score = user_cards[0] + user_cards[1]
print(f"Your cards: {user_cards}, your score: {user_score}")
0
import random

cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10, 10, 10]
draw = random.sample(cards, 2)
score = sum(draw)
print("Your cards: {}\nYour score: {}".format(draw, score))

Alternatively, you could use score = draw[0] + draw [1] for the fifth line. There is nothing wrong in using f"..." to indicate a formatted string, but I prefer "...".format().

niamulbengali
  • 292
  • 1
  • 3
  • 16