Home > Blockchain >  My code isnt continueing after it breaks from a while loop
My code isnt continueing after it breaks from a while loop

Time:01-01

okay so im new to coding in general and during a practice activity i ran into a problem with using while loops, im trying to simulate a 8-ball that doesnt work unless you ask it a question, so far all im trying to do is to cause the code to re ask the question until it meets the peramiters of a none empty input but everytime now that the input isnt empty it just ends before printing out the 8-balls answer

question = input("Isaiah's MagicAndTotallyNotSentient 8-Ball: what is your question? ")
while len(question) == 0:
    if len(question) == 0:
        print("...")
        question = input("Isaiah's MagicAndTotallyNotSentient 8-Ball: What is your question?")
        continue
    elif len(question) < 0:
        break

ive been at this all day yesterday and today ive finally got the loop to end in general but now i dont know how to get it to continue to execute the code after my while loop without breaking the current loop i have in place ive tried using an else statement to break the loop and this elif statment to break the loop but now im not quite sure what to do

CodePudding user response:

You can utilize walrus operator (:=) to assign and evaluate a variable and also reduce repeated code. So the while loop will keep continue until the value of the variable is not None or not empty:

while not (question := input("Isaiah's MagicAndTotallyNotSentient 8-Ball: what is your question? ")):
    print("...")

# next code

CodePudding user response:

I think it would be more practical if you just check if the input is empty, instead of enter a while loop right away. Something like this:

question = input("Isaiah's MagicAndTotallyNotSentient 8-Ball: what is your 
                  question? ")

if len(question) == 0: 
    while len(question) == 0:
            print("...")
            question = input("Isaiah's MagicAndTotallyNotSentient 8-Ball: What is your question?")
        
print("The answer to your question is...etc")
#(rest of the code)

CodePudding user response:

You only need to enter the loop if the input is empty. And going if len(question) == 0: and while len(question) == 0: seems redundant.

I think I'd do it like this:

question = input("Isaiah's MagicAndTotallyNotSentient 8-Ball: What is your question?")

while len(question) == 0:
    print("...")
    question = input("Isaiah's MagicAndTotallyNotSentient 8-Ball: What is your question?")


print("The answer is:")


  • Related