Home > Enterprise >  How do i stop loops getting in the way of the rest of my code?
How do i stop loops getting in the way of the rest of my code?

Time:04-22

how do i stop this loop getting in the way of the rest of my code? i have had to make this project for one of my assignments so any help would be greatly appreciated. So ive put a "while True" statement in the code to restart the program if the user inputs a number outside of the specified range, but it gets in the way of the rest of the code if the user enters a correct number within the specified range. how can i keep this feature in place but not have it get in the way of the rest of the code?

for i in range (99999):
hat_list = [1, 2, 3, 4, 5]  # This is an existing list of numbers hidden in the hat.

print("the current list is", hat_list)
new_number = int(input("enter a number between 6 and 10 to replace the middle number '3': "))


# Step 1: write a line of code that prompts the user
# to replace the middle number with an integer number entered by the user.

while True:
if new_number >= 10: print("you have entered a number outside of the specified range. Try 
again")
elif new_number <= 6: print("you have entered a number outside of the specified range. Try 
again")
continue 


if new_number == 6 or 7 or 8 or 9 or 10: print("correct number(s) entered")
hat_list[2] = new_number


# Step 2: write a line of code that removes the last element from the list.
del hat_list[4]
print("the last number of the list is now deleted")

# Step 3: write a line of code that prints the length of the new / updated list.

print("the list is now: ", hat_list)
print("and the length of it is: ", len(hat_list), "lines long \n-----------------------------------------------------------------------------")

CodePudding user response:

You mentioned this is your assignment so I cant give you the full solution. But I believe you have to use break statement within the while loop just to break out of the loop.

Here is the doc for it. https://docs.python.org/3/tutorial/controlflow.html#break-and-continue-statements-and-else-clauses-on-loops

CodePudding user response:

While True runs forever until you exit from the loop. You can break the loop by using the keyword break

while True:
  if new_number >= 10:
    print("you have entered a number outside of the specified range. Try again")
    break
  elif new_number <= 6:
    print("you have entered a number outside of the specified range. Try again")
  • Related