samedi 7 janvier 2023

SyntaxError: name 'x' is used prior to global declaration

I want to create a programm which should get random strings of an array and put it inside a sentence. The problem is that the first sentence has to be different to the next sentence. Therefore I tried to use a global variable which should store the previous sentence, because otherwise it would be overwritten. But now I get an

SyntaxError: name 'previous_sentence' is used prior to global declaration

I hope you can help me

import random

previous_sentence = ''

def create_sentence():
    names = ["x", "y", "z"]
    designations = ["a", "b", "c"]
    sentence = '' 
    while sentence == previous_sentence:
        name = random.choice(names)
        designation = random.choice(designations)
        sentence = f'{name} ist ein {designation}'
    global previous_sentence
    previous_sentence = sentence
    return sentence

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



Aucun commentaire:

Enregistrer un commentaire