0

I have tried to figure out a way on how to restart my code in Python, but I can't get it to work properly.

if keepLooping == True:
  if userInput == randomNumber:
    if attempt == 1:
      print()
      print("Correct, First try!")
      stop = time.time()
      print("It took", int(stop - start), "seconds.")
      replay = input("Do you want to play again?: ")
      if replay.lower() in ("yes"):
        print()
        os.execl(sys.executable, '"{}"'.format(sys.executable), *sys.argv) # Restart code. You are here
      elif replay.lower() in ("no"):
        break
      else:
        print("Invalid input, Yes or No?")
        continue # Restart segment. You are here
        replayAttempt += 1
        print()

As you can see, I have tried using os.execl(sys.executable, '"{}"'.format(sys.executable), *sys.argv). Sure, it works, but then one of my inputs turn red, as you can see here. I have been trying to solve this but I can't find a solution.

I found a solution for the text being red, I added '\033[37m' before my inputs. The only problem I have now is that it can only restart once. When I try it again I get this error code here.

Nat Riddle
  • 928
  • 1
  • 10
  • 24
Neo
  • 13
  • 8
  • 1
    Your code is a bit difficult to follow. Could you please produce an [MRE](https://stackoverflow.com/help/minimal-reproducible-example). – bicarlsen Oct 11 '21 at 13:03
  • are you familiar with the looping mechanism? namely `while` and `for` loops? – Copperfield Oct 12 '21 at 14:09
  • You have a `if keepLooping == True` at the start of your code. Is that already inside a loop? – Gino Mempin Oct 12 '21 at 14:12
  • Does this answer your question? [How do I repeat the program in python](https://stackoverflow.com/questions/41365922/how-do-i-repeat-the-program-in-python) – Gino Mempin Oct 12 '21 at 14:12
  • @GinoMempin Yes it is inside a loop. – Neo Oct 13 '21 at 08:31
  • @Copperfield Yes I am. – Neo Oct 13 '21 at 08:31
  • 1
    and what is the problem with a regular loop that you feel that you have to make it into executing a new process instead of looping again in some fashion? are you familiar with functions declarations? – Copperfield Oct 13 '21 at 18:06
  • @Copperfield I am not used to functions or declarations, however, I do kind of know how they work. If you want the whole script, tell me. – Neo Oct 14 '21 at 09:38

1 Answers1

0

One way to this is to encapsulate thing into function

going from this

#start of scrip
#... game logic
#end of script 

to

def game():
   #...game logic

game()

encapsulated like this allow for easier reuse of stuff, and allow you to reduce repetition, if you do same thing in your code two or more times that is when you should factor that out into its own function, that is the DRY principle, Don't Repeat Yourself.

You can do something like this for example

def game():
   #...game logic
   return game_result

def main():
    done=False
    result=[]
    while not done:
        result.append( game() )
        reply = input("Do you want to play again?: ")
        if reply=="no":
            done=True
    #display the result in a nice way

main()

Here the main function do a couple of simple thing, play one round of the game, save the result, ask if you want to play again and display the result, and the game function do all the heavy work of playing the game.

Here is a simple working example of guess the number between 0 and 10

import random

def game(lower,upper):
    answer = str(random.randint(lower, upper))
    user_answer = input(f"Guess a number between {lower} and {upper}: ")
    game_result = user_answer == answer
    if game_result:
        print("you win")
    else:
        print("you lose, the answer was:",answer)
    return game_result


def main(lower=0,upper=10):
    done=False
    result=[]
    while not done:
        result.append( game(lower,upper) )
        reply = input("Do you want to play again?: ")
        if reply=="no":
            done=True
    print("Your result were",sum(result),"/",len(result) )
    
main()

Notice that the game function take 2 arguments, so you can play this game not just with 0 and 10, but any two number you desire, in turn the main function also take those same arguments but assign them default value so if you don't call this function with any of them it will use those default value and use them to call the game function, doing so allow for flexibility that you wouldn't have if you lock it to just 0 and 10 in this case.

(the sum(result) is because boolean are a subclass of int(numbers) so in math operation they are True==1 and False==0)

Copperfield
  • 8,131
  • 3
  • 23
  • 29
  • 1
    Thank you, I will get this in my code as fast as possible to see if it works. – Neo Oct 15 '21 at 08:05