0

I want to create a while-loop that loops until a random string has been created that starts with "A" and ends with "Z".

import string
from random import choice

def random_string():
    """ Generates a 5 letter random string. """
    rs = ''.join(choice(string.ascii_uppercase) for _ in range(5))
    print(rs)
    
    

while random_string()[-1] != "Z" and random_string()[0]) != "A":
    print("keep going")
return random_string
      

So far I have this and I am running into trouble with the while loop checking for the first and last letter. Is there a simpler (and correct) way to test this?

Thanks in advance.

3
  • 2
    You are calling the function twice, so you are checking two different strings. You could try calling the function once, storing the result in a variable and then checking the variable in the while condition. Commented Jan 20, 2021 at 1:34
  • 1
    The parenthesis around the while condition were wrong, and the operator to check logical AND in Python is and, not & Commented Jan 20, 2021 at 1:43
  • If the indentation in your code is the same as the indentation in your question, you hit return rs before you ever enter the loop. Commented Jan 20, 2021 at 1:44

2 Answers 2

1

If you want to have the first and last letters in your string to be the same, why not just randomize the middle 3 characters.

You would have a successful result every run.

pre = 'A'
suf = 'Z'
n = 3

result = pre + ''.join(random.choice(string.ascii_uppercase) for i in range(n)) + suf

#'ACUUZ'

Id you want to achieve this with the while loop, you need to ensure your return is outside of your loop, and that your loop runs whilst your condition is not met.

 def random_string():
    rs = ''.join(choice(string.ascii_uppercase) for _ in range(5))
    while rs[-1] != "Z" or rs[0] != "A":
        rs = ''.join(choice(string.ascii_uppercase) for _ in range(5))
    return rs

With the above, we define our return after the while loop, ensure it only returns when a match has been found.

Output

for i in range(10): 
    print(random_string())

ASKPZ
AHOKZ
AYWQZ
ASHYZ
ACENZ
ASIVZ
ADTVZ
AZWHZ
AAHHZ
AKZHZ
Sign up to request clarification or add additional context in comments.

2 Comments

This makes sense -- though the intention of the original code might be to simulate the random experiment of sampling until you get a hit, in which case this suggestion skips the experiment completely.
@JohnColeman Agreed, i have also added how to achieve this with the code in question.
0

This should work as you intended.

import string
from random import choice
    
random_string = ''.join(choice(string.ascii_uppercase) for _ in range(5))

while random_string[-1] != "Z" or random_string[0] != "A":
    random_string = ''.join(choice(string.ascii_uppercase) for _ in range(5))
    print("keep going")

Comments

Your Answer

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