0

I am asked to produce a random string using a previously defined value.

THREE_CHOICES = 'ABC'
FOUR_CHOICES = 'ABCD'
FIVE_CHOICES = 'ABCDE'

import random

def generate_answers(n: int) -> str:
    '''Generates random answers from number inputted '''
    for i in range(0,n):
        return random.choice(FOUR_CHOICES)
        continue

What I am trying to get happening here is, if I were to plug in 7 into the function I'd get something like "ABDCBBA"

A random 7 character string from the specified letters. However, this code is returning only one random character no matter what number I put in (has to be non-zero).

I don't know what to do here, can someone point me in the right direction?

1
  • return is the end of your function. Always. So accumulate in some manner, and then return the accumulated value. Commented Dec 5, 2013 at 3:58

2 Answers 2

1

you could just return a list like this:

def generate_answers(n):
    '''Generates random answers from number inputted '''
    randoms = [random.choice(FOUR_CHOICES) for _ in range(0,n)]
    return randoms
    #return ''.join(randoms) to get string

print generate_answers(7)  

this would print a list like this: ['D', 'D', 'D', 'B', 'A', 'A', 'C']

you could join the list if you want a string

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

1 Comment

@EricCuevas No problem! good luck with the rest of the project :)!
0

not tested, but should work.

THREE_CHOICES = 'ABC'
FOUR_CHOICES = 'ABCD'
FIVE_CHOICES = 'ABCDE'

import random

def generate_answers(n):
    '''Generates random answers from number inputted '''
    answerList = ""
    for i in range(0,n):
        answerList += random.choice(FOUR_CHOICES)
    return answerList

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.