Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does my while loop break at end even when I make sure my game_start variable is still 0?

I’ve tried adding breaks and continues in multiple formats such as if/else structures and also just adding the break and continues right after and no matter how I structured it nothing worked. I’m not getting an error code but it is breaking out of the while loop even if x is inputted as 0 in the continue check.
The Basic set up of the code is:

import random
x = 0
while x == 0:
  guess = int(input(stuff))
    while ((guess > 9) or (guess < 0))
      guess = int(input('invalid response')
  num = random.randint(0,9)
  if guess == num:
    print('correct')
    x = int(input('continue? yes = 0, no = 1')
  else:
    print('incorrect')
    x = int(input('continue? yes = 0, no = 1')
  

I originally tried to have a check outside of the else if statement set as:

while (x != 0) or (x != 1):
  x = int(input('\nNon-valid response please pick 0 for yes or 1 for no.'))

but I kept getting an invalid syntax error.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Ok mate, you’ve got a lot of syntax errors, particularly when it comes to not closing your brackets (an open bracket ALWAYS needs a closing bracket), so if x number of open brackets, you need an x number of closing brackets.

If you’re using VSCode (Visual Studio Code), then I recommend an extension called "Rainbow Brackets", but it should already be integrated to VSCode (the extension is decprecated). The first bracket’s colour has to match the last bracket’s colour, like Good Syntax, not Bad Syntax.

Try the code below:

import random
x = 0
while x == 0:
    guess = int(input('Input guess >> '))
    while ((guess > 9) or (guess < 0)):
        guess = int(input('invalid response'))
    num=random.randint(0, 9)
    if guess == num:
        print('correct')
        x=int(input('continue? yes = 0, no = 1 > '))
    else:
        print('incorrect')
        x=int(input('continue? yes = 0, no = 1 > '))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading