Return' outside the function

I’m trying to make it so that if the input is equal to a specific word, the program returns the while loop. But it gives me an error

while tloopcheck:
            ct = input("Write two letters in the next order: temp to temp (f for fahrenheit, c for celcius, k for kelvin): ")
            if ct == "c to f":
                cng = input("You chose celcius to fahrenheit. To change it type 'change'")
                if cng == 'change':
                   return tloopcheck
                else:
                    ctf = input("Enter a celcius value: ")
                    tempans = (int(ctf) * 9/5)+32
                    print(round(tempans, 2))

Hello, @tera4895717912.

Welcome to the forums!

while needs a bool expression to evaluate. The code inside the loop will repeat while the expression is truthy. Unless you have additional code that you didn’t share, tloopcheck is currently undefined, so that’s one thing to fix.

return hands a value back to the line of code that called the function that the return statement is located in. A while loop is not a function. Your code does not define a function, so there is nowhere for a return statement to reside.

To get the code inside the while loop to repeat, you only need to maintain the truthiness of the expression. Here’s a really simple example:

answer = ""
count = 0

while answer.lower() != "yes": #convert answer to lowercase to accept Yes, YES, etc.
    answer = input("Do you like Python? ") #this code will repeat until the user enters yes
    count += 1

print(f'It took you {count} tries to answer, {answer}.')

Output:

Do you like Python? Sort of
Do you like Python? a little
Do you like Python? somewhat
Do you like Python? no, I love it!
Do you like Python? YES
It took you 5 tries to answer, YES.

1 Like