0

I want to get two words but I only get one. What should I change? Here's the code:

import random

puntos = ['Norte' , 'Sur' ,'Este' , 'Oeste']

res = random.choice(puntos) #choice returns without [''], choices returns with ['']

print(res)
5
  • 4
    Use random.choices() and specify the number of words to choose. Commented Aug 3, 2022 at 21:52
  • 1
    res = random.choices(puntos, k=2). If you want the choices to be unique, res = random.sample(puntos, 2). Commented Aug 3, 2022 at 21:52
  • and how do I get them without brackets and quotes? Commented Aug 3, 2022 at 21:56
  • They return lists of k-length, so you could destructure like a, b = random.sample(puntos, 2), whereas printing res just prints out the entire list (or what Python defaults to be the string representation of a list). Commented Aug 3, 2022 at 21:58
  • 1
    Nothing is returning "brackets and quotes". You are getting a list, and you are welcome to directly references items in that list if you want. Commented Aug 3, 2022 at 21:58

1 Answer 1

1

Ways of printing 2 values without '[' like you want

Example 1:

import random

puntos = ['Norte' , 'Sur' ,'Este , Oeste'] 
res1 = random.choice(puntos)
res2 = random.choice(puntos)

print(res1, res2)

Example 2:

import random

puntos = ['Norte' , 'Sur' ,'Este , Oeste'] 
res1, res2 = random.choices(puntos, k=2)

print(res1, res2)

Example 3:

import random

puntos = ['Norte' , 'Sur' ,'Este , Oeste'] 
res = random.choices(puntos, k=2)

print(res[0], res[1])

Example 4: Concatenating two words into one string

import random

puntos = ['Norte' , 'Sur' ,'Este , Oeste'] 
res = random.choice(puntos) + ' ' + random.choice(puntos)

print(res)

If this does not answer your question then I need a clearer question.

Always remember to check the documentation: https://docs.python.org/3/library/random.html#random.choice

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.