0

I've recently started to code and wanted to try my luck on a beginners program after 10 hrs of Udemy courses.

I've coded a "Guess the number" minigame, where a number is generated between 1-10 and I want the program to restart if someone guesses wrong.

import random
import os
import sys

def restart_program():
    python = sys.executable
    os.execv(sys.executable, ['python'] + sys.argv)

number = str(random.randrange(1,10))

choice = input("Which number did the PC pick?\n")

if choice == number:
    print("You won!")
    restart_program()
elif choice != number:
    print("You lose!")
    restart_program()

For some reason JupyterLab' kernel keeps dying on me the second I input a number.

I've tried restructuring the code and using completely different code but I always kill the kernel.

Can someone tell me if I did smth wrong?

Wasloos
  • 3
  • 2
  • Hi, welcome to SO. Could you clarify, what exactly do you mean by dying on you? What is the specific error message you receive? – R_Dax Aug 11 '21 at 11:59
  • Hey, so the error message I receive is: "The kernel for *PATH* appears to have died. It will restart automatically." – Wasloos Aug 11 '21 at 12:06

1 Answers1

0

I believe it is not a good idea to spawn a new Python interpreter as means of "restarting" program, especially if you are not its owner (did you spawn the program in the first place? No, a Jupyter kernel did it for you → you should not try to kill it and replace by another process as os.execv does).

Also, depending on what is in sys.argv you may actually invoke a different module which also could lead to a crash. See it for yourself - when running a notebook with IPython kernel sys.argv contains IPython internal commands, you should not play with those!

For this simple beginner program you probably should use a loop:

import random

done = False

while not done:
    number = str(random.randrange(1,10))
    choice = input("Which number did the PC pick?\n")

    if choice == number:
        print("You won!")
    elif choice != number:
        print("You lose!")

    if choice == 'x':
        done = True

But if you really need to restart the kernel you should use one of the solutions for restarting IPython kernel from code cell (or equivalent for any other kernel that you may be using).

krassowski
  • 13,598
  • 4
  • 60
  • 92
  • Really appreciated. It worked. And I honestly forgot loops were a thing, no idea why I wanted to do it the hard way lmao. – Wasloos Aug 16 '21 at 07:20