3

I am making a program on python 3. I have a place that I need the script to restart. How can I do this.

 #where i want to restart it
name= input("What do you want the main character to be called?")
gender = input("Are they a boy or girl?")

if gender == "boy":
    print("Lets get on with the story.")
elif gender == "girl":
    print("lets get on with the story.")
else:
    print("Sorry. You cant have that. Type boy or girl.")
    #restart the code from start

print("Press any key to exit")
input()

3 Answers3

3

It's a general question about programming an not specific to Python ... by the way you can shorten your code with the two conditions on boy and girl...

while True:
    name= input("What do you want the main character to be called?")
    gender = input("Are they a boy or girl?")

    if gender == "boy" or gender == "girl":
        print("Lets get on with the story.")
        break

    print("Sorry. You cant have that. Type boy or girl.")

print("Press any key to exit")
input()
Colonel Beauvel
  • 30,423
  • 11
  • 47
  • 87
0

Simple but bad solution but you get the idea. I am sure, you can do better.

while True:
    name= input("What do you want the main character to be called?")
    gender = input("Are they a boy or girl?")

    if gender == "boy":
        print("Lets get on with the story.")
    elif gender == "girl":
        print("lets get on with the story.")
    else:
        print("Sorry. You cant have that. Type boy or girl.")
        #restart the code from start

    restart = input("Would you like to restart the application?")
    if restart != "Y":
        print("Press any key to exit")
        input()
        break
khajvah
  • 4,889
  • 9
  • 41
  • 63
0

Don't have the program exit after evaluating input from the user; instead, do this in a loop. For example, a simple example that doesn't even use a function:

phrase = "hello, world"

while (input("Guess the phrase: ") != phrase):
    print("Incorrect.") //Evaluate the input here
print("Correct") // If the user is successful

This outputs the following, with my user input shown as well:

Guess the phrase: a guess
Incorrect.
Guess the phrase: another guess
Incorrect.
Guess the phrase: hello, world
Correct

or you can have two separate function written over, It's same as above(only it's written as two separate function ) :

def game(phrase_to_guess):
return input("Guess the phrase: ") == phrase_to_guess

def main():
    phrase = "hello, world"
    while (not(game(phrase))):
        print("Incorrect.")
    print("Correct")

main()

Hope this is what you are looking for .

coder3521
  • 2,608
  • 1
  • 28
  • 50