Restarting a Python Program - python

I know this has been asked before, but I haven't understood the answer.
My code is this:
# Code by Jake Stringer
# 2014
import os
print(" Hailstone Numbers ")
print("")
print("An interesting area of Maths - demonstrated by Jake Stringer")
print("")
input("Please press enter to continue.")
os.system('CLS')
print("Hailstone Numbers:")
print("")
print("RULE 1: Start with any number.")
print("If it is even > divide it by 2.")
print("If it is odd > multiply it by 3, then add 1")
print("")
print("RULE 2: Keep going")
print("")
print("RULE 3: You will always end up at 1.")
print("")
print ("Let's put Hailstone Numbers into action.")
print("")
user = int(input("Please enter any number: "))
print("")
os.system('CLS')
print (user)
print("")
if user % 2 == 0 :
print("What you entered is an even number.")
print("")
print("So, according to RULE 1, we must now divide it by 2.")
user = int(user)/2
thing2 = "So, now we're left with " + str(user) + "."
print (thing2)
else :
print("What you entered is an odd number.")
print("")
print("So, according to RULE 1, we must now multiply it by 3, and add 1.")
user = int(user)*3
user += 1
thing2 = "So, now we're left with " + str(user) + "."
print (thing2)
input("Please press enter to continue.")
os.system('CLS')
print("According to RULE 2, we need to keep on going.")
while user > 1:
thing3 = "We are currently on the number " + str(user) + "."
print (thing3)
if user % 2 == 0 :
print("This number is an even number.")
print("")
print("So, according to RULE 1, we must now divide it by 2.")
user = int(user)/2
thing2 = "So, now we're left with " + str(user) + "."
print (thing2)
else :
print("This number is an odd number.")
print("")
print("So, according to RULE 1, we must now multiply it by 3, and add 1.")
user = int(user)*3
user += 1
thing2 = "So, now we're left with " + str(user) + "."
print (thing2)
print("Now we will continue.")
input("Please press the enter key.")
os.system('CLS')
print("")
print(user)
print("")
print("As you can see, you have ended up on the number 1.")
print("")
print(" Hailstone Numbers ")
print("")
print("An interesting area of Maths - demonstrated by Jake Stringer")
print("")
restart = input("Would you like a try the program again??")
if restart == "yes":
# restart code here!
else:
# quit the program!
.... So, how do I make the program restart? I have seen in past answers to use some code that when I tried out, says that "sys" isn't defined (so I'm guessing it doesn't exist). It should also be noted that I'm a beginner at Python. Thanks for any help!!

Stick the whole thing in a function and then put a repeat-loop outside the function.
import os
def my_function():
print(" Hailstone Numbers ")
print("")
# more code here
print("An interesting area of Maths - demonstrated by Jake Stringer")
print("")
while True:
my_function()
restart = input("Would you like a try the program again??")
if restart == "yes":
continue
else:
break
You might want to head over to Code Review and get some folks to look over your code, by the way.

You can put it in a loop as follows:
# Code by Jake Stringer
# 2014
import os
restart = 'yes'
while restart in ('yes', 'Yes', 'y', 'Y'):
print(" Hailstone Numbers ")
print("")
print("An interesting area of Maths - demonstrated by Jake Stringer")
print("")
input("Please press enter to continue.")
os.system('CLS')
print("Hailstone Numbers:")
print("")
print("RULE 1: Start with any number.")
print("If it is even > divide it by 2.")
print("If it is odd > multiply it by 3, then add 1")
print("")
print("RULE 2: Keep going")
print("")
print("RULE 3: You will always end up at 1.")
print("")
print ("Let's put Hailstone Numbers into action.")
print("")
user = int(input("Please enter any number: "))
print("")
os.system('CLS')
print (user)
print("")
if user % 2 == 0 :
print("What you entered is an even number.")
print("")
print("So, according to RULE 1, we must now divide it by 2.")
user = int(user)/2
thing2 = "So, now we're left with " + str(user) + "."
print (thing2)
else :
print("What you entered is an odd number.")
print("")
print("So, according to RULE 1, we must now multiply it by 3, and add 1.")
user = int(user)*3
user += 1
thing2 = "So, now we're left with " + str(user) + "."
print (thing2)
input("Please press enter to continue.")
os.system('CLS')
print("According to RULE 2, we need to keep on going.")
while user > 1:
thing3 = "We are currently on the number " + str(user) + "."
print (thing3)
if user % 2 == 0 :
print("This number is an even number.")
print("")
print("So, according to RULE 1, we must now divide it by 2.")
user = int(user)/2
thing2 = "So, now we're left with " + str(user) + "."
print (thing2)
else :
print("This number is an odd number.")
print("")
print("So, according to RULE 1, we must now multiply it by 3, and add 1.")
user = int(user)*3
user += 1
thing2 = "So, now we're left with " + str(user) + "."
print (thing2)
print("Now we will continue.")
input("Please press the enter key.")
os.system('CLS')
print("")
print(user)
print("")
print("As you can see, you have ended up on the number 1.")
print("")
print(" Hailstone Numbers ")
print("")
print("An interesting area of Maths - demonstrated by Jake Stringer")
print("")
restart = input("Would you like a try the program again??")

Related

How would I do a definition for a name validation

What I want to do:
I am trying to make a definition that takes an input (name as string) and checks if the name is in a set list.
If it is, the program will continue.
If it isn't, it will give the user 2 more chances to enter their name correctly.
Requirements:
I need to use the name variable after the definition.
I need the system to exit if the name is wrong 3 times.
Problems:
If the name is correct it works properly
However, if the name is wrong, it doesn't allow another name input, printing "You have 2 more tries" and "You have 1 more try" then ends the loop and exits.
Code:
names_allowed_to_play = ["MUM","DAD"]
def val_1 (name_1):
print("Player 1, you have 3 tries to enter the correct name")
print("")
a = 0
while a < 3:
name_1 = name_1.upper()
if name_1 in names_allowed_to_play:
print(name_1 + ", you are authorised to play, have fun!")
print("")
a = a + 4
names_allowed_to_play.remove(name_1)
elif name_1 not in names_allowed_to_play:
a = a + 1
if name_1 not in names_allowed_to_play and a ==1:
print("You have 2 more tries")
print("")
print("")
elif name_1 not in names_allowed_to_play and a ==2:
print("You have 1 more try")
print("")
print("")
if a == 3:
print("")
print("Sorry Player 2, " + name_1 + " ruined it! " + name_1 + ", you are NOT AUTHORISED!")
sys.exit()
#Run definition
name_1 = input("Player 1, please enter your name to play: ")
val_1(name_1)
There are a few problems with your code:
you never ask the user for new input within the loop, instead just testing the first name again
you modify the (local) name_1 variable, but never return the value to the caller
you do not have to repeat all the conditions, and can use math to determine the number of tries remaining
You can try something like this:
def get_name(player, tries, names_allowed_to_play):
print(f"Player {player}, you have {tries} tries to enter the correct name")
for i in range(1, tries+1):
name = input("Please enter your name to play: ").upper()
if name in names_allowed_to_play:
print("You are authorised to play, have fun!")
names_allowed_to_play.remove(name)
return name
elif i < tries:
print(f"You have {tries - i} more tries")
else:
print("You messed up")
exit()
names_allowed_to_play = ["MUM","DAD"]
name1 = get_name(1, 3, names_allowed_to_play)
name2 = get_name(2, 3, names_allowed_to_play)
print(name1, name2)
This is working for me, I think the way you had structured it meant the logic was flawed.
import sys, time
names_allowed_to_play = ["MUM","DAD"]
def main():
authorised = False
attempts = 3
while authorised == False:
if attempts < 3:
print("You have",attempts,"remaining.")
if attempts > 0:
name = input("Player 1, please enter your name to play: ")
name = name.upper()
elif attempts <= 0:
print("You are locked out.")
time.sleep(1)
sys.exit()
if name in names_allowed_to_play:
print(name," you are authorised to play, have fun!")
names_allowed_to_play.remove(name)
authorised = True
else:
attempts -= 1
main()
Major changes:
put input() in while loop so you can get new input when the name is wrong, otherwise you only get the input once and the wrong name is checked by the if-statement 3 times
add return statement for allowed name so you can use the name later (such as print out or other functions)
You can find other minor changes in my code comment.
# change the names to lowercase so you don't need upper() for input
names_allowed_to_play = ["mum","dad"]
def player_validate():
# \n for new line, just works like your print("")
print("Player 1, you have 3 tries to enter the correct name\n")
tries = 0
while tries < 3:
player_name = input("Player 1, please enter your name to play: ")
if player_name in names_allowed_to_play:
print(player_name + ", you are authorised to play, have fun!\n")
names_allowed_to_play.remove(player_name)
# return will stop the loop so you don't need to break it by other code
return player_name
else:
tries = tries + 1
# use calculation instead of many elif statment
print(f"You have {3-tries} tries.")
# I have change Player 2 to Player 1, if it is not typo, you can change it back
print("Sorry Player 1, " + player_name + " ruined it! " + player_name + ", you are NOT AUTHORISED!")
# use exit() instead of sys.exit() or you will need to import sys at beginning
exit()
# Run function (I think function is a more common name then definition)
name_to_use_later = player_validate()
print(name_to_use_later)
I have fixed your code problem.
names_allowed_to_play = ["MUM", "DAD"]
def val_1():
print("Player 1, you have 3 tries to enter the correct name")
name_1 = input("enter your name")
a=0
while a < 3:
name_1 = name_1.upper()
if name_1 in names_allowed_to_play:
print(name_1 + ",you are authorised to play, have fun!")
a = a + 4
names_allowed_to_play.remove(name_1)
elif name_1 not in names_allowed_to_play:
a = a + 1
if name_1 not in names_allowed_to_play and a == 1:
print("You have 2 more tries")
name_1 = input("enter your name")
print("")
elif name_1 not in names_allowed_to_play and a == 2:
print("You have 1 more try")
name_1 = input("enter your name")
elifa == 3:
print("")
print("Sorry Player 2, " + name_1 + " ruined it! " + name_1 + ", you are NOT AUTHORISED!")
exit()
val_1()

Trying to call a function outside of an if statement

I'm doing some Python exercises and I came across a frustrating error:
line 18, in <module>
modulo()
NameError: name 'modulo' is not defined
Code is below:
number = input("Please enter a number: ")
if number.isdigit():
def modulo():
answer = int(number) % 2
if answer == 0:
print("Your number, " + number + " is even.")
elif answer > 0:
print("Your number, " + number + " is odd.")
else:
print("Error. Please try again.")
else:
print("Please try again")
modulo()
Make modulo accept an argument, define it outside the if-statement
def modulo(num):
answer = int(num) % 2
if answer == 0:
print("Your number, " + num + " is even.")
elif answer > 0:
print("Your number, " + num + " is odd.")
else:
print("Error. Please try again.")
number = input("Please enter a number: ")
if number.isdigit():
modulo(number)
else:
print("Please try again")
You should write your function outside the if statement, in this case the function will be defined ONLY if number.isdigit() is True.

Python restart program1

I am trying to restart this program if what the user gets from picking the two numbers from the dice roll is already gone from the overall list. It will ask them to roll again and everything that just happened will go back like they never clicked 'e'.
roll = input("Player turn, enter 'e' to roll : ")
dice_lst = []
if roll == "e":
for e in range(num_dice):
d_lst = random.randint(1,6)
dice_lst.append(d_lst)
else:
print("Invalid ----- Please enter 'e' to roll the dice")
# Add in the invalid input error
print("")
print("You rolled", dice_lst)
dice_choose = int(input("Choose a dice : "))
dice_lst.remove(dice_choose)
print("")
print("You are left with", dice_lst)
dice_choose1 = int(input("Choose a dice : "))
dice_lst.remove(dice_choose1)
print("")
while True:
sum1 = dice_choose + dice_choose1
if sum1 in lst_player:
break
else:
print("You have made an invalid choice")
sum1 = dice_choose + dice_choose1
print(dice_choose, "+", dice_choose1, "sums to", sum1)
print(sum1, "will be removed")
print("")
lst_player.remove(sum1)
If you want to repeat code until some conditions are met, you can use a while True loop or while <condition> loop, using continue (continue to the next iteration) to "reset" when some invalid situation is reached:
while True:
roll = input("Player turn, enter 'e' to roll : ")
dice_lst = []
if roll == "e":
for e in range(num_dice):
d_lst = random.randint(1,6)
dice_lst.append(d_lst)
else:
print("Invalid input")
continue # Go back to asking the player to roll
print("")
print("You rolled", dice_lst)
dice_choose = int(input("Choose a dice : "))
dice_lst.remove(dice_choose)
print("")
print("You are left with", dice_lst)
dice_choose1 = int(input("Choose a dice : "))
dice_lst.remove(dice_choose1)
print("")
sum1 = dice_choose + dice_choose1
if sum1 not in lst_player:
print("You have made an invalid choice")
continue # Go back to asking the player to roll
print(dice_choose, "+", dice_choose1, "sums to", sum1)
print(sum1, "will be removed")
print("")
lst_player.remove(sum1)
break # Break out of the loop
I'm not entirely sure how this code is intended to work, but you may need to move blocks around and/or reset dice before continue.

Python: How do I return to the beginning of my game from input at the end?

So I'm new to programming, and made a little game, with help from google. The first code of the game works, but I want to ask how I would add a function that asks if I want to play again, and if I say "Yes" for example, then it plays the game again, and returns to "I am thinking of a number....." or if I say "No" then it exits...
The second code is the code that doesn't work, where I tried adding a function for the game to play again, and suggested I add another while loop, but not too sure where to put it. Currently with the second code, when I guess the correct number, it just closes and doesn't ask for input.
I apologise for the dumb question, but I can't figure it out.
import random
guessesTaken = 0
print("Hello, I am your computer. What is your name?")
myName = input()
number = random.randint(1, 20)
print("\nHello " + myName + ", and welcome to the game! Do you want to play?")
playGame = input()
while playGame == "Yes":
print("I am thinking of a number between 1 and 20, can you guess my number?\n")
while guessesTaken < 6:
print("Take a guess. ")
guess = input()
guess = int(guess)
guessesTaken += 1
if guess < number:
print("Your guess is too low.")
if guess > number:
print("Your guess is too high.")
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print("Well done " + myName + "! You guessed my number in " + guessesTaken + " guesses!")
if guess != number:
number = str(number)
print("Sorry " + myName + ", but you couldn't figure it out, my number was " + number)
break
while playGame == "No":
print("Then you opened this for nothing, goodbye")
break
input()
import random
guessesTaken = 0
print("Hello, I am your computer. What is your name?")
myName = input()
number = random.randint(1, 20)
print("\nHello " + myName + ", and welcome to the game! Do you want to play?")
playGame = input()
while playGame == "Yes" or playAgain == "Yes":
print("I am thinking of a number between 1 and 20, can you guess my number?\n")
while guessesTaken < 6:
print("Take a guess. ")
guess = input()
guess = int(guess)
guessesTaken += 1
if guess < number:
print("Your guess is too low.")
if guess > number:
print("Your guess is too high.")
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print("Well done " + myName + "! You guessed my number in " + guessesTaken + " guesses! \nWould you like to play again?")
playAgain = input()
if guess != number:
number = str(number)
print("Sorry " + myName + ", but you couldn't figure it out, my number was " + number + "\nWould you like to play again?")
playAgain = input()
break
while playAgain == "No":
print("Thank you for playing, goodbye")
break
while playGame == "No":
print("Then you opened this for nothing, goodbye")
break
input()
You can add the playing features as a function and call that in a while loop.
import random
def PlayGame():
guessesTaken = 0
print("Hello, I am your computer. What is your name?")
myName = input()
number = random.randint(1, 20)
print("\nHello " + myName + ", and welcome to the game!")
print("I am thinking of a number between 1 and 20, can you guess my number?\n")
while guessesTaken < 6:
print("Take a guess. ")
guess = input()
guess = int(guess)
guessesTaken += 1
if guess < number:
print("Your guess is too low.")
if guess > number:
print("Your guess is too high.")
if guess == number:
break
if guess == number:
guessesTaken = str(guessesTaken)
print("Well done " + myName + "! You guessed my number in " + guessesTaken + " guesses!")
if guess != number:
number = str(number)
print("Sorry " + myName + ", but you couldn't figure it out, my number was " + number)
print("Would you like to play again? Enter 1 for Yes and 2 for No")
playAgain = input()
if playAgain == 1:
return True
else:
return False
playing = True
while playing == True:
playing = PlayGame()

I need help in while loop for this program

So I'm trying to create a while loop so the user can choose whether they want to continue the program or not. Any suggestions?
import random
while True:
print ("--------------------------------------------------------------------\n")
name = input("Please enter your name: ")
pack = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]
random.shuffle(pack)
print ("Welcome {0}! Hope you have fun playing! \n".format(name))
print("Original deck:", pack, "\n")
print ("--------------------------------------------------------------------\n")
for i in range(3):
pack1 = pack[::3]
pack2 = pack[1::3]
pack3 = pack[2::3]
print("1: ", pack1, "\n")
print("2: ", pack2, "\n")
print("3: ", pack3, "\n")
user = input("Pick a number and enter the row it is in: ")
while not (user == "1" or user == "2" or user == "3"):
print(user, " is not a valid answer. Please try again \n")
user = input("Pick a number and enter the row it is in: ")
if user == "1":
pack = pack3 + pack1 + pack2
elif user == "2":
pack = pack1 + pack2 + pack3
elif user == "3":
pack = pack2 + pack3 + pack1
print("The number you are thinking of is:", pack[10], "\n")
answer = input("Would you like to play again (y/n)? ")
if answer != "y" or answer != "n":
break
print ("Please press 'y' or 'n' and then Enter... ")
if answer == "y":
continue
else:
print ("Thank you for playing!")
break
Just to bring in some context about what this is about, this is a 21 Cards Trick program. Try it out if you want.
Edit: Also what's happening when the question at the end is asked is that it's not really restarting the program when you type 'y'.
Use a control boolean to handle the status of the user involvement.
Also your while loop indentation was incorrect, as Vasilis G. pointed out.
import random
controlFlag = True #add boolean control
while controlFlag == True:
print ("--------------------------------------------------------------------\n")
name = input("Please enter your name: ")
pack = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21]
random.shuffle(pack)
print ("Welcome {0}! Hope you have fun playing! \n".format(name))
print("Original deck:", pack, "\n")
print ("--------------------------------------------------------------------\n")
for i in range(3):
pack1 = pack[::3]
pack2 = pack[1::3]
pack3 = pack[2::3]
print("1: ", pack1, "\n")
print("2: ", pack2, "\n")
print("3: ", pack3, "\n")
user = input("Pick a number and enter the row it is in: ")
while not (user == "1" or user == "2" or user == "3"):
print(user, " is not a valid answer. Please try again \n")
user = input("Pick a number and enter the row it is in: ")
if user == "1":
pack = pack3 + pack1 + pack2
elif user == "2":
pack = pack1 + pack2 + pack3
elif user == "3":
pack = pack2 + pack3 + pack1
print("The number you are thinking of is:", pack[10], "\n")
answer = input("Would you like to play again (y/n)? ")
if answer == "y":
controlFlag = True # unnecessary, left in for completeness.
elif answer == 'n':
print ("Thank you for playing!")
controlFlag = False
else:
print('wrong choice')
break
General main loop structure usually goes somewhat like this:
def func():
while True
#run your game or whatever
#ask for input somehow
if input==truthy:
break
func()

Categories