Validating generated Captcha with User's input

Viewed 51

I've made a captcha from a random selection within the text file 'captcha.txt'. I have converted these recalled characters to a variable which i can then validate the user's input with.

import random 
import os
def captchasub():

    thisfolder = os.path.dirname(os.path.abspath(file))
    captchatxt = os.path.join(thisfolder, 'captcha.txt')

    with open(captchatxt) as text_file: 
        captcha = text_file.read()
        validation = print("".join(random.choices(captcha, k=6,)))
        x = input('Please Rewrite the Captcha Above:')
        if x != validation:
            print ('Stupid Robot')
            return captchasub()
        if x == validation:
            print ('Welcome')

captchasub()

I'm however not recieving the 'welcome' print im expecting when successfully completing a captcha.

I believe that everything is fine up until x != validation and onwards (maybe even at x = input).

EDIT: Solved!

validation = print("".join(random.choices(captcha, k=6,)))

Simple change to

validation = "".join(random.choices(captcha, k=6,))
print(validation)

and Bobs your uncle. Thanks boys! :)

2 Answers

Your validation variable is None, you'll first need to assign it the value and then print it, like so :)

validation = "".join(
    random.choices(
        captcha,
        k=6,
    ),
)

print(validation)

if x == validation:
    print('Welcome')
else:
    print('Stupid Robot')
    return captchasub()

The problem is with this statement. The print command returns None.

validation = print("".join(random.choices(captcha, k=6,)))

Try this:

validation = "".join(random.choices(captcha, k=6,))
print(validation)
Related