Python restart program1 - python

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.

Related

Guessing Game - Prompt the user to play again

I'm making a guessing game, but I want to add another line of code where the user can play again after, but I don't know where to start.
print ("Welcome to the Number Guessing Game in Python!")
# Initialize the number to be guessed
number_to_guess = 7
# Initialize the number of tries the player has made
count_number_of_tries = 1
# Obtain their initial guess
guess = int (input ("Please guess a number between 1 and 10: "))
while number_to_guess != guess:
print ("Sorry wrong number!")
# Check to see they have not exceeded the maximum number of attempts if so break out of loop
if count_number_of_tries == 3:
break
elif guess < number_to_guess:
print ("Your guess was lower than the number.")
else:
print ("Your guess was higher than the number.")
# Obtain their next guess and increment number of attempts
guess = int(input ("Please guess again: "))
count_number_of_tries += 1
# Check to see if they did guess the correct number
if number_to_guess == guess:
print ("Well done you won!")
print ("You took" + str(count_number_of_tries) + "attempts to complete the game.")
else:
print ("Sorry, you lose")
print ("The number you needed to guess was " + str(number_to_guess) + "." )
print ("Game Over.")
I dont know if the code should be at the bottom or in between somewhere.
I also want to remove the break if possible.
Great idea! In my mind, there are two ways of continuously asking the user to play until they enter something that will let you know they want to stop like 'q', 'quit', or 'exit'. First you could nest all of your current code a while loop (indent and write 'while(): before the code), or turn your current code into a function, and call it over and over again until the user enters the exit command
Ex:
lets say i can print hello world like this
# your game here
but now I want to keep printing it until the user enters 'quit'
user_input = '.' # this char does not matter as long as it's not 'quit'
while user_input != 'quit': # check if 'user_input' is not 'quit'
# your game here
user_input = input('Press any key to continue (and enter) or write "quit" to exit: ') # prompt user to enter any key, or write quit
Put all of that code in a game() function.
Underneath, write
while True:
game()
play=int(input('Play again? 1=Yes 0=No : '))
if play == 1:
pass
else:
break
print("Bye!")
I think this should do it, just a basic while loop
playAgain = 'y'
while playAgain == 'y':
print ("Welcome to the Number Guessing Game in Python!")
# Initialize the number to be guessed
number_to_guess = 7
# Initialize the number of tries the player has made
count_number_of_tries = 1
# Obtain their initial guess
guess = int (input ("Please guess a number between 1 and 10: "))
while number_to_guess != guess:
print ("Sorry wrong number!")
# Check to see they have not exceeded the maximum number of attempts if so break out of loop
if count_number_of_tries == 3:
print("You've guessed more than three times, you're pretty bad")
elif guess < number_to_guess:
print ("Your guess was lower than the number.")
else:
print ("Your guess was higher than the number.")
# Obtain their next guess and increment number of attempts
guess = int(input ("Please guess again: "))
count_number_of_tries += 1
# Check to see if they did guess the correct number
if number_to_guess == guess:
print ("Well done you won!")
print ("You took " + str(count_number_of_tries) + " attempts to complete the game.")
else:
print ("Sorry, you lose")
print ("The number you needed to guess was " + str(number_to_guess) + "." )
print ("Game Over.")
playAgain = (input ("Type y to play again, otherwise press enter: "))
print("Goodbye gamer")
You can add a while loop to the outermost layer that randomly generates the value of number_to_guess on each startup. And ask if you want to continue at the end of each session.
import random
print("Welcome to the Number Guessing Game in Python!")
number_range = [1, 10]
inp_msg = "Please guess a number between {} and {}: ".format(*number_range)
while True:
# Initialize the number to be guessed
number_to_guess = random.randint(*number_range)
# Initialize the number of tries the player has made
count_number_of_tries = 1
# Obtain their initial guess
guess = int(input(inp_msg))
while number_to_guess != guess:
print("Sorry wrong number!")
# Check to see they have not exceeded the maximum number of attempts if so break out of loop
if count_number_of_tries == 3:
break
elif guess < number_to_guess:
print("Your guess was lower than the number.")
else:
print("Your guess was higher than the number.")
# Obtain their next guess and increment number of attempts
guess = int(input("Please guess again: "))
count_number_of_tries += 1
# Check to see if they did guess the correct number
if number_to_guess == guess:
print("Well done you won!")
print("You took" + str(count_number_of_tries) + "attempts to complete the game.")
else:
print("Sorry, you lose")
print("The number you needed to guess was " + str(number_to_guess) + ".")
if input("Do you want another round? (y/n)").lower() != "y":
break
print("Game Over.")

Python - Loop Escaping unexpectedly and not iterating over list as expected

import random
import time
def closest_num(GuessesLog, CompNum):
return GuessesLog[min(range(len(GuessesLog)), key=lambda g: abs(GuessesLog[g] - CompNum))]
GameModeActive = True
while GameModeActive:
Guesses = None
GuessesLog = []
while not isinstance(Guesses, int):
try:
Guesses = int(input("How many guesses do you have?: "))
except ValueError:
print("Please enter a whole number")
print(" ")
CompNum = random.randint(1,99)
print(CompNum)
Players = None
while not isinstance(Players, int):
try:
Players = int(input("How many players are there?: "))
except ValueError:
print("Please enter a whole number")
print(" ")
NumberOfPlayers = []
for i in range(Players):
NumberOfPlayers.append(i+1)
NumberOfGuesses = []
for i in range(Guesses):
NumberOfGuesses.append(i+1)
print(NumberOfGuesses)
print(NumberOfPlayers)
print(len(NumberOfGuesses))
print(len(NumberOfPlayers))
for Guess in NumberOfGuesses:
if Guess != len(NumberOfGuesses):
print("ITS ROUND {}! GET READY!".format(Guess))
print(" ")
PlayersForRound = NumberOfPlayers
for Player in PlayersForRound:
print("It is Player {}'s Turn >>>".format(Player))
print(PlayersForRound)
print(NumberOfPlayers)
PlayerEntry = None
while not isinstance(PlayerEntry, int):
try:
PlayerEntry = int(input("Enter guess number {}: ".format(Guess)))
print(" ")
except ValueError:
print("Please enter a whole number")
print("CALCULATING YOUR RESULT!")
time.sleep(1)
print("***5***")
time.sleep(1)
print("***4***")
time.sleep(1)
print("***3***")
time.sleep(1)
print("***2***")
time.sleep(1)
print("***1***")
if PlayerEntry == CompNum:
print("Congratulations player {}, you have successfully guessed the number on round {}!".format(Player, Guess))
print(" ")
NumberOfPlayers.pop(Player-1)
if len(NumberOfPlayers) == 1:
print("Only {} Player remains".format(len(NumberOfPlayers)))
PlayersForRound
elif len(NumberOfPlayers) > 1:
print("Only {} Players remain".format(len(NumberOfPlayers)))
continue
elif PlayerEntry < CompNum:
print("Your guess was too low!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
elif PlayerEntry > CompNum:
print("Your guess was too high!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
if Guess == len(NumberOfGuesses):
print("ITS ROUND {}! THIS IS THE LAST ROUND! GOOD LUCK!".format(Guess))
print(" ")
print(NumberOfGuesses)
print(NumberOfPlayers)
print(len(NumberOfGuesses))
print(len(NumberOfPlayers))
PlayersForRound = NumberOfPlayers
for Player in PlayersForRound:
print("It is Player {}'s Turn >>>".format(Player))
PlayerEntry = None
while not isinstance(PlayerEntry, int):
try:
PlayerEntry = int(input("Enter guess number {}: ".format(Guess)))
print(" ")
except ValueError:
print("Please enter a whole number")
print("CALCULATING YOUR RESULT!")
time.sleep(1)
print("***5***")
time.sleep(1)
print("***4***")
time.sleep(1)
print("***3***")
time.sleep(1)
print("***2***")
time.sleep(1)
print("***1***")
if PlayerEntry == CompNum:
print("Congratulations player {}, you have successfully guessed the number on round {}!".format(Player, Guess))
print(" ")
NumberOfPlayers.pop(Player-1)
if len(NumberOfPlayers) == 1:
print("Only {} Player remains".format(len(NumberOfPlayers)))
elif len(NumberOfPlayers) > 1:
print("Only {} Players remain".format(len(NumberOfPlayers)))
continue
elif PlayerEntry < CompNum:
print("Your guess was too low!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
elif PlayerEntry > CompNum:
print("Your guess was too high!")
print(" ")
GuessesLog.append(PlayerEntry)
continue
print("The closest guess was ", closest_num(GuessesLog, CompNum))
print(" ")
while True:
Answer = input("Would you like to play again? Y/N: ")
if Answer.lower() not in ('y', 'n'):
print("Please enter either Y for Yes, or N for No.")
else:
break
if Answer == 'y':
GameActiveMode = True
elif Answer == 'n':
GameActiveMode = False
print("Thankyou for playing ;)")
break
holdCall = str(input("Holding the console, press enter to escape."))
In my above code, when there are multiple players and multiple guesses(Rounds) then it works fine unless someone successfully guesses the code. If the code is guessed the code deletes the correct record from the player list. But for some reason fails to iterate over the rest of the list or if the correct guess comes from the second user it skips the next player altogether and moves onto the next round.
I have absolutely no idea why. Anyone have any ideas? Thanks in advance.
For example, if you run this in console and then have 3 guesses with 3 users, on the first player you guess incorrectly. On the second you guess correctly, it skips player 3 and goes straight to round 2. Despite only remove player 2 from the list after a correct guess.
Or if you guess it correctly the first time around it skips to the 3rd player?
You are keeping track of players in the current round using a list of player numbers. So, if you start with three players, PlayersForRound will start as [1,2,3].
You then proceed to loop over this list to give each player their turn by using for Player in PlayersForRound. However, PlayersForRound and NumberOfPlayers are the exact same list (not a copy), so when you remove a player from one, it is removed from both.
Once a player guesses correctly, you remove them from the list you were looping over with NumberOfPlayers.pop(Player-1). For example if the second player guesses correctly, you remove their "index" from the list and the resulting list is now [1,3].
However, because Python is still looping over that same list, player 3 never gets their turn, because their "index" is now in the position where the "index" of player 2 was a moment ago.
You should not modify the list you're looping over, this will result in the weird behaviour you are seeing. If you want to modify that list, you could write a while loop that conditionally increases an index into the list and checks whether it exceeds the length of the list, but there are nicer patterns to follow to achieve the same result.
As for naming, please refer to https://www.python.org/dev/peps/pep-0008/ - specifically, your variables like PlayersForRound should be named players_for_round, but more importantly, you should name the variables so that they mean what they say. NumberOfPlayers suggests that it is an integer, containing the number of players, but instead it is a list of player numbers, etc.
The selected bits of your code below reproduce the problem, without all the fluff:
# this line isn't in your code, but it amounts to the same as entering '3'
Players = 3
NumberOfPlayers = []
for i in range(Players):
NumberOfPlayers.append(i+1)
PlayersForRound = NumberOfPlayers
for Player in PlayersForRound:
# this line is not in your code, but amounts to the second player guessing correctly:
if Player == 2:
NumberOfPlayers.pop(Player-1)
if Player == 3:
print('this never happens')
# this is why:
print(PlayersForRound, NumberOfPlayers)
When you pop the list, you intervene in the for loop. Here, you can play with this and see yourself.
players = 3
player_list = []
for p in range(players):
player_list.append(p + 1)
for player in player_list:
print(player)
if player == 2:
print("popped:",player_list.pop(player-1))
Output
1
2
popped: 2

in python 3.6.3, what is wrong with this program? It says invalid syntax on the line with: if Ui3 == "no":

sorry if the formatting is a little screwy. first question asked on here.
from random import randint
num=randint(1,9) #generates random number
print("welcome to the guessing game! the number is between 1 and 9.")
tries=0
player_input=int(input("enter your guess"))
while num != player_input:
if player_input == " ":
print("Invalid entry.")
player_input=int(input("please entera valid number between 1 and 9"))
if player_input < num:
tries = tries +1
print("too low")
print(" ")
player_input=int(input("guess again "))
if player_input > num:
tries = tries +1
print("too high!")
print(" ")
player_input = int(input("guess again "))
if player_input == num:
tries = tries +1
print("You Got It!!")
print(" ")
print("you have tried",tries,"times")
next
newg=("yes") # = new game
endg=("no") # = stop game
print("To start a new game enter ", newg, ". Or to stop the game, enter ", endg)
user=(input("Y/N")
# the syntax error shows up here. i have tries different variable instead of ui3 such as new_game_a, ng, U_I, ui, etc.i have fixed that problem, but now it is the " : " at the end of the line. i tried many variations in spacing. but still no lee-way with error.
if user == "no":
print("close window")
else user == "yes":
tries=0
player_input=int(input("enter your guess"))
while num != player_input:
if player_input == " ":
print("Invalid entry.")
player_input=int(input("please enter valid number between 1 and 9"))
if player_input < num:
tries = tries +1
print("too low")
print(" ")
player_input=int(input("guess again "))
if player_input > num:
tries = tries +1
print("too high!")
print(" ")
player_input = int(input("guess again "))
if player_input == num:
tries = tries +1
print("You Got It!!")
print(" ")
print("you have tried",tries,"times")
PLEASE help me if possible, thanks.
an example of the error message!!
There's most likely more than this (the extra closing parentheses required which may have just been a typo), but I see that your syntax is incorrect.
else user == "yes":
Should be replaced with:
elif user == "yes":
You're missing a closing ) on the line defining user and else doesn't take another condition:
user=(input("Y/N"))
if user == "no":
print("close window")
else:
tries=0
player_input=int(input("enter your guess"))

Python craps game, while-loop issue

I'm looking to create a simple craps game and I am having issues.
When this code is inputted:
import random
def main():
starting_money = int(input("How much do you have to gamble? : "))
print()
player_bet = int(input("Enter your bet: "))
number_1 = (random.randint(1,6))
number_2 = (random.randint(1,6))
print("Dice roll 1: ", number_1)
print("Dice roll 2: ", number_2)
roll = number_1 + number_2
print("Your roll: ", roll)
rounds = input("Play again? (Y/N): ")
while rounds != "n" and rounds == "y":
if rounds == "n":
print("Congratulations, you left with")
if roll == 7 or roll == 11:
print("You win $", player_bet, sep="")
new_money = starting_money + player_bet
print("You have $", new_money, " remaining.", sep="")
elif roll == 2 or roll == 3 or roll == 12:
new_money = starting_money - player_bet
print("You lost $", player_bet, sep="")
print("You have $", new_money, " remaining.", sep="")
else:
print("You push.")
new_money = starting_money
print("You have $", new_money, " remaining.", sep="")
break
main()
this happens when I input "n".
Enter your bet: 5
Dice roll 1: 6
Dice roll 2: 6
Your roll: 12
Play again? (Y/N): n
and this happens when I input "y".
Enter your bet: 5
Dice roll 1: 2
Dice roll 2: 3
Your roll: 5
Play again? (Y/N): y
You push.
You have $10 remaining.
In both instances, it needs to tell the user whether or not they push, win, or lose before it asks if they want to play again. How can I accomplish this?
If I put "rounds" within the while loop, it tells me that rounds is referenced before it's assigned.
I think there's a lot here to neaten up, but why not start with:
rounds = 'y'
while .....
....
....
else:
....
rounds = input("Play again (y/n)")
This way you automatically fall into the while loop after the first roll and give the user results before asking if they want to play again. The next problem you have to deal with is that within the while loop, there is no provision for placing new bets or rolling the dice again.
The first problem is that all of the code that tells the user whether they push, win, or lose is inside the loop, and if the user enters "n", that code never runs. The real problem is that most of your code really should be inside the loop, including asking the user how much they want to bet and rolling the dice.
I would start by initializing the rounds variable to a default value of "y" so that the loop runs at least once, then don't ask the user if they want to play again until the end of the loop. Then move all of your other code inside the loop. (Except for the "How much do you have to gamble?" part. That should probably stay outside the loop.)
This is untested, but the order of things should be something like:
import random
def main():
starting_money = int(input("How much do you have to gamble? : "))
print()
rounds = "y"
while rounds != "n" and rounds == "y":
player_bet = int(input("Enter your bet: "))
number_1 = (random.randint(1,6))
number_2 = (random.randint(1,6))
print("Dice roll 1: ", number_1)
print("Dice roll 2: ", number_2)
roll = number_1 + number_2
print("Your roll: ", roll)
if rounds == "n":
print("Congratulations, you left with")
if roll == 7 or roll == 11:
print("You win $", player_bet, sep="")
new_money = starting_money + player_bet
print("You have $", new_money, " remaining.", sep="")
elif roll == 2 or roll == 3 or roll == 12:
new_money = starting_money - player_bet
print("You lost $", player_bet, sep="")
print("You have $", new_money, " remaining.", sep="")
else:
print("You push.")
new_money = starting_money
print("You have $", new_money, " remaining.", sep="")
rounds = input("Play again? (Y/N): ")
main()
You should probably also think about ending the game if the player runs out of money.

Restarting a Python Program

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??")

Categories