Reputation: 49
Here is my code
def gen_code(codeLength):
symbols = ('ABCDEF')
code = random.sample(symbols, k=codeLength)
return str(code)
def print_code(code):
i = 0
while i < len(code):
print(code[i])
i += 1
code = gen_code(codeLength)
print("The code is " + code)
convCode = code[0] + code[1] + code[2] + code[3]
print(convCode)
So I basically want to generate a random string from the letters I have provided and then check if the user guesses a correct entry in that string (I'm trying to make mastermind). The issue I have is checking to see if the user's guess is in the code which is generated.
Why is my convCode
variable printing ['E' and not EAFB?
Upvotes: 0
Views: 54
Reputation: 8273
code
is a list use slicing to get the required result which will give you flexibility as you need not write hardcoded list indices each time.
import random
def gen_code(codeLength):
symbols = ('ABCDEF')
code = random.sample(symbols, k=codeLength)
return code
def print_code(code):
i = 0
while i < len(code):
print(code[i])
i += 1
code = gen_code(5)
print("The code is " + str(code))
convCode =code[:4]
print(convCode)
Upvotes: 0
Reputation: 3462
If the code is returned as a list
instead of a string
, you can access the individual letters of the code in the manner you want to.
import random
codeLength=4
def gen_code(codeLength):
symbols = ('ABCDEF')
code = random.sample(symbols, k=codeLength)
return code
def print_code(code):
i = 0
while i < len(code):
print(code[i])
i += 1
code = gen_code(codeLength)
print("The code is " + str(code))
convCode = code[0] + code[1] + code[2] + code[3]
print(convCode)
Upvotes: 1
Reputation: 813
In your gen_code
function you convert the list to a string before you return it:
def gen_code(codeLength):
symbols = ('ABCDEF')
code = random.sample(symbols, k=codeLength)
# This converts it to a string, rather than leaving it as a list
# which is presumably what you want.
return str(code)
So later in your code:
convCode = code[0] + code[1] + code[2] + code[3]
Gives you the first four characters of that string which are exactly ['E'
Try changing gen_code
to this:
def gen_code(codeLength):
symbols = ('ABCDEF')
code = random.sample(symbols, k=codeLength)
return code
Upvotes: 0