Kaos Kaos - 5 months ago 14
Python Question

"while True:" loop returns nothing after one cycle

Here's the problem: my while loop doesn't repeat AT ALL, it just returns a blank line in the Python Launcher and doesn't carry on the code, i added a print function at the end to check if it did just skip.
I used several ways of getting the code to repeat, such as "While True:" and "While 0 == 0" so i have started to think there is a problem somewhere else in the code, the code in question is:

while True:
while i <= dice_amount:
dice_output = random.randint(0,dice_range)
print("dice number ", i, " is ", dice_output)
i +=1
while input_answer == "unknown":
input_answer = input("would you like to throw the dice again? Y/N")
if input_answer == "N":
time.sleep(2)
os.exit
elif input_answer != "Y":
input_answer = "unknown"

print("code is broken") #to see if code just skips loop


This is what happens when i try to repeat
I would much appreciate the help and I'd just like to say i'm new to coding so I know it may not be optimised, however a comment saying how i could optimise it would be helpful.

At the start the variables are defined as such:

dice_amount = int(input("how many times would you like to roll the dice?"))
dice_range = int(input("how many numbers would you like on the dice?"))
input_answer = "unknown"
i = 1

Answer

You need to set i to one after "while True", and set input_answer to "unknown" before the second inner loop. Corrected code:

while True:
 i = 1
 while i <= dice_amount:
   dice_output = random.randint(0,dice_range)
   print("dice number ", i, " is ", dice_output)
   i +=1
 input_answer = "unknown"
 while input_answer == "unknown":
   input_answer = input("would you like to throw the dice again? Y/N")
   if input_answer == "N":
    time.sleep(2)
    os.exit
   elif input_answer != "Y":
    input_answer = "unknown"

print("code is broken") #to see if code just skips loop
Comments