Home > Enterprise >  Is my VS Code bugging or is something wrong with my code?
Is my VS Code bugging or is something wrong with my code?

Time:01-20

I've used the return keyword to end the function, and made sure that the variable (randnum1) is in the correct scope, yet Pylance says that the variable still isn't defined. How do I fix this? (code below)

        def genrand1():
            randnum1 = random.randrange(rand1a, rand1b)
            return randnum1

        rand1prompt = input("The random number will be "   randnum1   ". Is this okay? (Type yes or no")
        if rand1prompt := "yes":
            print("Okay, the number's set.")
            num1 = randnum1
        elif rand1prompt := "no":
            print("Okay. Generating a new random number...")
            genrand1()
        else:    
            print("Whoops. Something went wrong. Please type yes or no.")```

CodePudding user response:

You probably want to replace the randnum1's from the third line with the function that returns it.
I presume you are returning it from one function and using the same variable outside the function.
Instead you would want to store the return value of the function in a variable and use that variable in place of randnum1.
For example:- If you want to use the randnum1 the something like

randnum1 = function()

Replace function with your function name.
This is just my initial guess and getting a look on the full code will definitely be more insightful.

CodePudding user response:

The randnum1 in your input statement is not defined as it has not been defined globally. randnum1 is a local variable as it has only been defined in the genrand1() function so it's only accessible within the genrand1() function.

To define randnum1 globally, store the return value of the function in it: randnum1 = genrand1(). Like:

def genrand1():
    randnum1 = random.randrange(rand1a, rand1b)
    return randnum1

randnum1 = genrand1() #Stored here

rand1prompt = input("The random number will be "   randnum1   ". Is this okay? (Type yes or no")
if rand1prompt := "yes":
    print("Okay, the number's set.")
    num1 = randnum1
elif rand1prompt := "no":
    print("Okay. Generating a new random number...")
    genrand1()
else:    
    print("Whoops. Something went wrong. Please type yes or no.")
  •  Tags:  
  • Related