Loop to ask user to go again [duplicate] - python

This question already has answers here:
Ask the user if they want to repeat the same task again
(2 answers)
Closed 2 years ago.
I have a simple program that runs a game of Craps. All of the logic of the craps game is in the playOnce() method. I need to use a main() method that calls the playOnce() method in order to determine whether a user wants to play again by entering either yes or no. I need to constantly ask the user if they want to play after each round. I'm having trouble implementing that piece of the logic of asking the user. I have tried using a while loop, but so far no output. Here's a sample: http://tinypic.com/r/2las1v/8
----------------------------------------------------
import random
def playOnce():
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
roll = dice1 + dice2
print("You rolled", dice1, "+", dice2, "=", roll)
print()
if roll == 2 or roll == 3 or roll == 12:
print("You lose!")
elif roll == 7 or roll == 11:
print("You win!")
else:
print("Point is", roll)
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
roll2 = dice1 + dice2
print("You rolled ",roll2)
while roll2 != 7:
if roll == roll2:
print("You win!")
break
else:
print("Point is ", roll)
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
roll2 = dice1 + dice2
print("You rolled ",roll2)
if roll2 == 7:
print("You lose!")
def main():
playOnce()
print("Would you like to go again?")
main()

How about:
def main():
keep_playing = True
while keep_playing:
playOnce()
ans = raw_input("Would you like to go again?")
if ans != 'y':
keep_playing = False

You can use this:
import random
def playOnce():
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
roll = dice1 + dice2
print("You rolled", dice1, "+", dice2, "=", roll)
print()
if roll == 2 or roll == 3 or roll == 12:
print("You lose!")
elif roll == 7 or roll == 11:
print("You win!")
else:
print("Point is", roll)
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
roll2 = dice1 + dice2
print("You rolled ",roll2)
while roll2 != 7:
if roll == roll2:
print("You win!")
break
else:
print("Point is ", roll)
dice1 = random.randint(1, 6)
dice2 = random.randint(1, 6)
roll2 = dice1 + dice2
print("You rolled ",roll2)
if roll2 == 7:
print("You lose!")
def main():
playOnce()
#print("Would you like to go again?")
flag = input("Would you like to go again?")
#flag = True
while flag:
playOnce()
flag = input("Would you like to go again?")
main()
Then you need reply True or False or 1 or 0

Related

Python -- 3 dices game question by using while loop

I am a new learner on Python, I created a game to roll 3 dices randomly. I want to know how to go back to the "play" under "else". Please check my screenshot
import random
game = False
game1 = False
def roll():
money = 0
while game == False :
money += 1
key = input("Please hit 'y' to roll the 3 dicks: ")
if key == "y":
roll1 = random.randint(0,10)
roll2 = random.randint(0,10)
roll3 = random.randint(0,10)
print("Roll 1,2,3 are: ", roll1, roll2, roll3)
else:
print("Invalid input, try again")
return roll()
if roll1 == roll2 == roll3:
money +=1
print("You Win!")
print("Your award is ", money)
game == False
else:
play = input("Loss, try again? y or n? ")
if play == "y":
money -= 1
game == False
elif play == "n":
break
else:
??????????????????????
roll()
You can just put it inside a while loop there:
else:
while True: # you can
play = input("Loss, try again? y or n? ")
if play == "y":
money -= 1
game == False
elif play == "n":
break
else:
pass

How to get function to loop properly?

I made a coin flip game with a gambling aspect but it wont iterate. It goes through once but then will only run line 6 on the second run after the user says they want to play again.
import random
import sys
money = 1000000
flip = random.randint(0,1)
def game():
print ("welcome to the coin flip")
answer=input("do you want to play the coin flip? y/n")
answer = str(answer)
if answer == "n":
sys.exit("goodbye")
if answer == "y":
print ("your balance is",money)
guess = input("heads or tails? 0 for heads 1 for tails")
guess = int(guess)
if flip == 0:
print("heads")
if flip == 1:
print("tails")
if guess == flip:
print("you win")
money = money + 250000
else:
print("you lose")
money = money - 250000
print ("your balance is",money)
if money == 0:
sys.exit("you are bankrupt")
replay = input("play again? y/n")
if replay == "y":
game()
if replay == "n":
sys.exit("goodbye")
This is the output:
do you want to play the coin flip? y/ny
your balance is 1000000
heads or tails? 0 for heads 1 for tails1
heads
you lose
your balance is 750000
play again? y/ny
welcome to the coin flip
you need to call game() at the end of the code once more.
import random
import sys
money = 1000000
flip = random.randint(0,1)
step=25000
def game():
print ("welcome to the coin flip")
answer=input("do you want to play the coin flip? y/n")
answer = str(answer)
if answer == "n":
sys.exit("goodbye")
if answer == "y":
print ("your balance is",money)
guess = input("heads or tails? 0 for heads 1 for tails")
guess = int(guess)
if flip == 0:
print("heads")
if flip == 1:
print("tails")
if guess == flip:
print("you win")
fact=1
else:
print("you lose")
fact=-1
print ("your balance is",money+fact*step)
if money == 0:
sys.exit("you are bankrupt")
replay = input("play again? y/n")
if replay == "y":
print("welcome again")
game()
if replay == "n":
sys.exit("goodbye")
game()
Add this up in your game function:
global money, flip

establishing a win streak in dice game

Hi all. Really, REALLY stuck here. I've updated my code below.
I'm trying to establish a counter to track games played, correct guesses and > incorrect guesses plus, when the number of consecutive correct guesses
= 4 or user stops playing, game summary is provided.
I cannot get the counter to work correctly.
Help appreciated!
import math
import dice
import random
# Print introduction and game explanation
print ("")
print ("")
print ("Would you like to play a game?")
print ("The game is...'Petals Around the Rose'. Cool eh?")
print ("Pay attention - the name of the game is important.")
print ("Each round, five dice are rolled and")
print ("You'll be asked for the score. (Hint? The score")
print ("will always be either 'zero' or an even number).")
print ("Your challenge is to deduce how the computer has")
print ("calculated the score.")
print ("You need to input your guess, after which")
print ("You'll learn if you were right. If not, you'll")
print ("be told the correct score & asked to roll again.")
print ("If you can guess correctly four times in a row,")
print ("You'll be declared the winner and receive the")
print ("majestic title of 'Potentate of the Rose'")
print ("")
# Define win count (four correct guesses in a row required)
win_count = 0
# Obtain input from user:
answer = input("Are you up for the challenge? Enter 'y' or 'n' : ")
# If answer = no, exit game
if answer == 'n':
print("Really? fine then. See ya!")
exit()
# If answer = yes, commence game
elif answer == 'y':
print("")
print ("Ok...here comes the first roll!")
print("")
# import dice representation
import dice
# Roll random dice x 5
die1 = random.randint(1, 6)
die2 = random.randint(1, 6)
die3 = random.randint(1, 6)
die4 = random.randint(1, 6)
die5 = random.randint(1, 6)
dice.display_dice(die1, die2, die3, die4, die5)
# Obtain player's guess for the roll
roll_guess = int(input("Enter your guess for this roll: "))
# Define die results for all dice for guess purposes to
# match the 'petals around the rose'. So, if roll a 2, 4 or 6,
# the result is zero. If return a 3, the result is 2. If
# return a 5, the result is 4.
def roll_result(die1):
if die1 == 1 or die1 == 2 or die1 == 4 or die1 == 6:
die1 = 0
elif die1 == 3:
die1 = 2
elif die1 == 5:
die1 = 4
return die1
def roll_result(die2):
if die2 == 1 or die2 == 2 or die2 == 4 or die2 == 6:
die2 = 0
elif die2 == 3:
die2 = 2
elif die2 == 5:
die2 = 4
return die2
def roll_result(die3):
if die3 == 1 or die3 == 2 or die3 == 4 or die3 == 6:
die3 = 0
elif die3 == 3:
die3 = 2
elif die3 == 5:
die3 = 4
return die3
def roll_result(die4):
if die4 == 1 or die4 == 2 or die4 == 4 or die4 == 6:
die4 = 0
elif die4 == 3:
die4 = 2
elif die4 == 5:
die4 = 4
return die4
def roll_result(die5):
if die5 == 1 or die5 == 2 or die5 == 4 or die5 == 6:
die5 = 0
elif die5 == 3:
die5= 2
elif die5 == 5:
die5 = 4
return die5
# tally all 5 dice rolls
a = roll_result(die1)
b = roll_result(die2)
c = roll_result(die3)
d = roll_result(die4)
e = roll_result(die5)
total_roll_result = a + b + c + d + e
# Compare user input to dice result
if roll_guess == total_roll_result:
print("")
print('Well done! You guessed it!')
print("")
elif guess % 2 == 0:
print("")
print("No sorry, it's", total_roll_result, "not", roll_guess)
print("")
else:
print("")
print ("No, sorry, it's", total_roll_result, 'not', roll_guess,"")
print ("Remember,the answer will always be an even number")
print("")
# Obtain user input if continuing to play
another_attempt = input("Are you up to play again? If so, enter y or n ")
print("")
# Commence loop and win count.
while another_attempt == 'y' and win_count <4:
# Commence win count
win_count = 0
# Commence games played count
games_played = 0
# Commence incorrect guesses count
incorrect_guesses = 0
# If user has not yet gotten 4 guesses in a row:
if win_count < 4:
die1 = random.randint(1,6)
die2 = random.randint(1,6)
die3 = random.randint(1,6)
die4 = random.randint(1,6)
die5 = random.randint(1,6)
result = dice.display_dice(die1, die2, die3, die4, die5)
a = roll_result(die1)
b = roll_result(die2)
c = roll_result(die3)
d = roll_result(die4)
e = roll_result(die5)
total_roll_result = a + b + c + d + e
roll_guess = int(input('Enter your guess for this roll: '))
print("")
if roll_guess == total_roll_result:
# Update win count
win_count += 1
# Update games played count
games_played += 1
print("")
print('Nice work - you got it right!')
elif roll_guess %2 == 0:
# reset win count
win_count = 0
# Update games played count
games_played += 1
# Update incorrect guesses count
incorrect_guesses += 1
print("")
print("Nah, sorry, it's", total_roll_result, "not", roll_guess)
else:
# Reset win count
win_count = 0
# Update games played count
games_played += 1
# Update incorrect guesses count
incorrect_guesses += 1
print("")
print ("Nah, sorry, it's", total_roll_result, 'not', roll_guess,"")
print ("Remember,the answer will always be an even number")
print("")
another_attempt = input("Are you up to play again? ")
# Quit loop if user no longer wishes to play
# Provide game summary
if another_attempt == 'n':
print ("")
print ("Game Summary")
print ("------------")
print ("")
print ("You played ", games_played, "games.")
print ("")
print ("You had ", correct_guesses, "overall and ")
print ("")
print ("a total of ", incorrect_guesses, "overall ")
print ("")
print ("Cheerio!")
exit()
if win_count == 4:
# Inform player has correctly guessed 4 in a row
# Print congratulations message
print ("")
print ("")
print ("You've done it! You've successfully guessed")
print ("Four times in a row. Looks like you worked ")
print ("out the secret. Now, stay stum & tell no one!")
print ("")
# Provide game summary
print ("Game Summary")
print ("")
# Provide tally of games played & print:
print ("You played ", games_played, "games.")
print ("")
# Provide tally of correct guesses & print:
print ("You had ", correct_guesses, "overall and ")
print ("")
# Provide tally of total incorrect guesses & print:
print ("a total of ", incorrect_guesses, "overall ")
print ("")
print ("Cheerio!")
exit()
def game_stats():
win_count
games_played
incorrect_guesses
You look very lost here. This part does not make any sense
def win_count():
win_count() == 0
correct == total_roll_result
I think you mean something like this
win_count = 0
correct = total_roll_result == roll_guess
Note
When you say
def win_count:
# some code
you are defining win_count as a function! But clearly you want win_count to be an integer counting something.

Python3 can't repeat the loop after else statement (googled it and did'nt find a solid resault)

can't repeat the loop after the "else statement" (googled it and did'nt find a solid resault)
example:
I'm trying to make a dice game
import random
import time
print("=" * 34)
print("= Welcome to Roll the Dice Game. =")
print("=" * 34)
min = 1
max = 6
user_input = input("Roll the Dice? [Y/N] ")
def dice_roll():
time.sleep(1)
print("Rolling dices...")
time.sleep(1)
print("Getting the values...")
time.sleep(1)
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
print(" Dice #1 -> ", dice1)
print(" Dice #2 -> ", dice2)
time.sleep(1)
dices_sum = dice1 + dice2
print(" The sum is", dices_sum)
while user_input:
if user_input == 'Y' or user_input =='y':
print(dice_roll())
elif user_input =='N' or user_input == 'n':
print('exiting')
else:
print('Invalid')
continue
user_input = input("Roll again? [Y/N] ")
print(user_input)
Your while loop needs a condition. While x == 1: or while 1:
If you use x = 1. When the value of x is other than 1, the while loop will stop or when a break is used.
If you use while 1, it will continue to loop until you use break.
Another point, you want to have the user_input within the while loop so that it can ask the user if they would like to roll again.
import random
import time
print("=" * 34)
print("= Welcome to Roll the Dice Game. =")
print("=" * 34)
min = 1
max = 6
def dice_roll():
time.sleep(1)
print("Rolling dices...")
time.sleep(1)
print("Getting the values...")
time.sleep(1)
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
print(" Dice #1 -> ", dice1)
print(" Dice #2 -> ", dice2)
time.sleep(1)
dices_sum = dice1 + dice2
print(" The sum is", dices_sum)
x = 1
while x == 1:
user_input = input("Roll the Dice? [Y/N] ")
print(user_input)
if user_input == 'Y' or user_input =='y':
print(dice_roll())
elif user_input =='N' or user_input == 'n':
print('exiting')
break
else:
print('Invalid')
Answer: As noted by Klaus, removing the continue in the while user_input will fix the loop, to only re-roll when the user responds 'y'
Changing print(dice_roll()) to just dice_roll() (function call without printing it's return value) will keep this program from printing 'None' after dice rolls.
If you want it to print the return, you can change the
print(" The sum is", dices_sum) to
return(" The sum is", dices_sum)
try this
import random
import time
print("=" * 34)
print("= Welcome to Roll the Dice Game. =")
print("=" * 34)
min = 1
max = 6
def dice_roll():
time.sleep(1)
print("Rolling dices...")
time.sleep(1)
print("Getting the values...")
time.sleep(1)
dice1 = random.randint(min, max)
dice2 = random.randint(min, max)
print(" Dice #1 -> ", dice1)
print(" Dice #2 -> ", dice2)
time.sleep(1)
dices_sum = dice1 + dice2
print(" The sum is", dices_sum)
while 1:
user_input = input("Roll? [Y/N] ")
print(user_input)
if user_input == 'Y' or user_input == 'y':
dice_roll()
elif user_input == 'N' or user_input == 'n':
print('exiting')
break
else:
print('Invalid')
There are two problems that you need to fix.
Since your function dice_roll ends without return syntax, python interpreter will add return None at the end of the function. I change 'print(dice_roll())' to 'dice_roll()'.
In your while loop, if elif else syntax has covered all situations, the code will never go to
user_input = input("Roll again? [Y/N] ")
print(user_input)
So, I just put these two lines in front of 'if elif else'. and remove ' again'.

running tally for dice game

I am one week into a coding bootcamp so forgive my simplistic and probably sloppy coding, but I was wondering how I could put in a running tally of wins for my two player dice rolling game. I am able to produce the final score and loop the function back around to start again if the players want to keep playing but I would like to keep a running tally of wins so the players know how many times each player has won. Here is my function:
def DiceRoll():
Dice1 = random.randint(1, 20)
Dice2 = random.randint(1, 12)
Dice3 = random.randint(1,6)
Dice4 = random.randint(1, 20)
Dice5 = random.randint(1, 12)
Dice6 = random.randint (1, 6)
DoubleDice1 = (((Dice1 + Dice2)*2) + Dice3)
DoubleDice2 = (((Dice1 + Dice3)*2) + Dice2)
DoubleDice3 = (((Dice2 + Dice3)*2) + Dice1)
DoubleDice4 = (((Dice4 + Dice5)*2) + Dice6)
DoubleDice5 = (((Dice4 + Dice6)*2) + Dice5)
DoubleDice6 = (((Dice5 + Dice6)*2) + Dice4)
TripleDice1 = ((Dice1 + Dice2 +Dice3) * 3)
TripleDice2 = ((Dice4 + Dice5 +Dice6) * 3)
print("Player 1, Roll?")
Roll = input("Y/N?")
if Roll =="y":
print("Ok!")
if Roll == "n":
print("Goodbye!")
time.sleep(2)
sys.exit(0)
print(" ")
print(Dice1, Dice2, Dice3)
Score1 = Dice1 + Dice2 + Dice3
if Dice1 == Dice2:
Score1 = DoubleDice1
print(Score1)
elif Dice1 ==Dice3:
Score1 = DoubleDice2
print(Score1)
elif Dice2 == Dice3:
Score1 = DoubleDice3
print(Score1)
elif Dice1 == Dice2 ==Dice3:
Score1 = TripleDice1
print(Score1)
else:
print(Dice1 + Dice2 + Dice3)
print("""
""")
print("Player 2, Roll?")
Roll2 = input("Y/N?")
if Roll2 =="y":
print("Ok!")
if Roll2 == "n":
print("Goodbye!")
time.sleep(2)
sys.exit(0)
print(" ")
print(Dice4, Dice5, Dice6)
Score2 = (Dice4 + Dice5 + Dice6)
if Dice4 == Dice5:
Score2 = DoubleDice4
print(Score2)
elif Dice4 == Dice6:
Score2 = DoubleDice5
print(Score2)
elif Dice5 == Dice6:
Score2 = DoubleDice6
print(Score2)
elif Dice4 == Dice5 ==Dice6:
Score2 = TripleDice2
print(Score2)
else:
print(Dice4 + Dice5 + Dice6)
print("""
""")
if Score1 > Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Player 1 Wins!")
if Score1 < Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Player 2 Wins!")
if Score1 == Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Tie!")
Since there is no loop in your function, I assume that you have that control loop in the program that calls DiceRoll. To make a clean tally, you'll need to return the win/lose designation to that program, something like this:
if Score1 > Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Player 1 Wins!")
winner = 1
elif Score1 < Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Player 2 Wins!")
winner = 2
else:
print("Player 1:", Score1, "Player 2:", Score2)
print("Tie!")
winner = 0
Now, back in your main program, we'll have something like:
p1_wins = 0
p2_wins = 0
ties = 0
while game_on:
result = DiceRoll()
if result == 1:
p1_wins += 1
elif result = 2
p2_wins += 1
else:
ties += 1
I've kept this at the level of programming I think you're using. First you get to understand it. In a few more boot camp sessions, come back to see how you'd like to improve your coding.
The most simplistic solution would be to have the DiceRoll function return which player won.
winner = None
if Score1 > Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Player 1 Wins!")
winner = 1
elif Score1 < Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Player 2 Wins!")
winner = 2
elif Score1 == Score2:
print("Player 1:", Score1, "Player 2:", Score2)
print("Tie!")
winner = 0
return winner
Then in the loop that calls DiceRoll, just check the returned result.
Now, you've got a lot of repeated code in this function. You're basically doing everything twice. This makes it a prime candidate for breaking into another function. I would suggest making a function that takes the player as a parameter, and then does the dice rolls for just that player, and returns the score. Then you could just call the function for each player, compare the results, and determine the winner from that.
One last thing. If a player chooses not to roll, it's exiting the program. That should probably be changed to be considered a forfeit, and have it exit at the outer loop so you can display the final tally.

Categories