I've written a very simple dice rolling script in Python. It'll allow you to roll three times. However, I don't know how to break out of the while loop and avoid the raw_input the final time.
#!/usr/bin/python
from random import randrange, uniform
def rollDice():
dice = randrange(3,18)
print ("You rolled: %s" % dice)
maxReRoll = 2
c = 0
reRoll = "y"
while reRoll in ["Yes", "yes", "y", "Y"]:
if c > maxReRoll:
break
else:
rollDice()
c+=1
reRoll = raw_input("Roll again? y/n ")
Just a little swap is needed.
while reRoll in ["Yes", "yes", "y", "Y"]:
rollDice()
c+=1
if c >= maxReRoll: # notice the '>=' operator here
break
else:
reRoll = raw_input("Roll again? y/n ")
This should work for you:
from random import randrange
def roll_dice():
dice = randrange(3,18)
print("You rolled: %s" % dice)
max_rolls = 2
c = 0
re_roll = "y"
while re_roll.lower() in ["yes", "y"] and (c < max_rolls):
roll_dice()
c += 1
if c != max_rolls:
re_roll = input("Roll again? y/n ")
Related
Until this semester I didn't even know a while True was a thing. I have to write a while True loop to loop until the user enters 'n' to break. My problem is restarting the loop if the user enters anything other than 'y' or 'n'. Currently, I can loop with any character besides 'n'. I need a way to catch the if say 'q' was entered, "please enter 'y' or 'n'" and prompt the user again. I have considered doing another while loop within the loop but I feel like there is a more optimal way to achieve this.
def main():
userinput = "y"
display_title()
while True:
userinput.lower() == "y"
choice = ""
display_menu()
choice = str(input("Select a conversion (a/b): "))
while choice == "a" or "b":
if choice == "a":
print()
feet = int(input("Enter feet: "))
meters = conversions.to_meters(feet)
print(str(round(meters, 2)) + " meters")
print()
break
elif choice == "b":
print()
meters = int(input("Enter Meters: "))
feet = conversions.to_feet(meters)
print(str(round(feet, 2)) + " feet")
print()
break
elif choice != "a" or "b":
print("Please enter a valid option a or b")
choice = str(input("Select a conversion (a/b): "))
userinput = input("Would you like to perform another conversion? (y/n): ")
if userinput == "n":
print()
print("Thanks, Bye!")
break
You don't need another while loop. You could just need to put the input check to the beginning of the loop and add a check for any other character than 'y' and 'n', e.g.:
def main():
userinput = "y"
display_title()
while True:
if userinput == "n":
print()
print("Thanks, Bye!")
break
elif userinput != "y":
userinput = input("Please select yes (y) or no (n)").lower()
continue
### If you get this far, userinput must equal 'y'
choice = ""
display_menu()
choice = str(input("Select a conversion (a/b): "))
while choice == "a" or "b":
if choice == "a":
print()
feet = int(input("Enter feet: "))
meters = conversions.to_meters(feet)
print(str(round(meters, 2)) + " meters")
print()
break
elif choice == "b":
print()
meters = int(input("Enter Meters: "))
feet = conversions.to_feet(meters)
print(str(round(feet, 2)) + " feet")
print()
break
elif choice != "a" or "b":
print("Please enter a valid option a or b")
choice = str(input("Select a conversion (a/b): "))
userinput = input("Would you like to perform another conversion? (y/n): ").lower()
continue
Be aware, the way you implemented the inner loop asking for the conversion type doesn't allow you to exit the xcript if you suddenly decide abort the procedure e.g. a Keyboard interrupt.
[Edit]
I've not looked at your inner loop. As someone else has suggested,
while choice == "a" or "b"
will always evaluate to True. Why? beacuse internally python will split this expression:
(choice == "a") or "b"
It doesn't matter if choice == "a", as "b" is a non-empty string and thus evaluates to True.
If you were to rewrite yout inner loop as follws:
while choice: # Will evaluate to True as long as choice isn't an empty string.
if choice == "a":
print()
feet = int(input("Enter feet: "))
meters = conversions.to_meters(feet)
print(str(round(meters, 2)) + " meters")
print()
break
elif choice == "b":
print()
meters = int(input("Enter Meters: "))
feet = conversions.to_feet(meters)
print(str(round(feet, 2)) + " feet")
print()
break
else:
print("Please enter a valid option a or b")
choice = input("Select a conversion (a/b): ")
you'll be able to give the user an option to exit the inner loop by inputing nothing and you'll remove an uneccessary double-check if the choice equals a or b.
Tip: If you want to check if one variable matches one of some different options in a while statement, you could use the following:
while var in [opt1, opt2 ...]:
...
import random
min = 1
max = 6
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print ("Rolling Dice...")
print ("The number is...")
print (random.randint(min, max))
print (random.randint(min, max))
roll_again = raw_input("Want to roll again?");
You need to make sure that the user input is in the while loop, otherwise roll_again is permanently set to "yes" and you are stuck in an infinite loop.
import random
min = 1
max = 6
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print ("Rolling Dice...")
print ("The number is...")
print (random.randint(min, max))
print (random.randint(min, max))
roll_again = raw_input("Want to roll again?");
And the following is a more pythonic approach
import random
min = 1
max = 6
while True:
print ("Rolling Dice...")
print ("The number is...")
print (random.randint(min, max))
print (random.randint(min, max))
roll_again = input("Want to roll again?");
if roll_again != "yes" and roll_again != "y":
break
Because you're setting your loop to always be "yes". Thus its looping over and over and over until it becomes false which it will not.
Try this:
import random
while True:
min = 1
max = 6
roll_again = input("Do you want to roll again? Type: Yes or y")
if roll_again.lower() == "yes" or roll_again == "y":
print ("Rolling Dice...")
print ("The number is...")
print (random.randint(min, max))
This code will promt a user everytime after the roll to see if they want to roll again.
I'm making a 2-player battleship game in python. I've made it so that each 'game' allows a total of 6 turns (3 from each player), after which a message will appear saying 'The number of turns has ended'.
Once this happens, they will be asked to play again. If they answer 'yes' or 'y', the game should reload. However it doesn't. The board loads but the program then exits. I believe the issue lies with my play_again() function but I'm not quite sure what it is.
I want to make it so that the players can play as many games as they want until they decide to answer 'no' or 'n'. How do I go about implementing this?
from random import randint
game_board = []
player_one = {
"name": "Player 1",
"wins": 0,
}
player_two = {
"name": "Player 2",
"wins": 0,
}
colors = {"reset":"\033[00m",
"red":"\033[91m",
"blue":"\033[94m",
"cyan":"\033[96m"
}
# Building our 5 x 5 board
def build_game_board(board):
for item in range(5):
board.append(["O"] * 5)
def show_board(board):
for row in board:
print(" ".join(row))
# Defining ships locations
def load_game(board):
print("WELCOME TO BATTLESHIP!")
print("Find and sink the ship!")
del board[:]
build_game_board(board)
print(colors['blue'])
show_board(board)
print(colors['reset'])
ship_col = randint(1, len(board))
ship_row = randint(1, len(board[0]))
return {
'ship_col': ship_col,
'ship_row': ship_row,
}
ship_points = load_game(game_board)
# Players will alternate turns.
def player_turns(total_turns):
if total_turns % 2 == 0:
total_turns += 1
return player_one
return player_two
# Allows new game to start
def play_again():
positive = ["yes", "y"]
negative = ["no", "n"]
global ship_points
while True:
answer = input("Play again? [Y(es) / N(o)]: ").lower().strip()
if answer in positive:
ship_points = load_game(game_board)
break
elif answer in negative:
print("Thanks for playing!")
exit()
# What will be done with players guesses
def input_check(ship_row, ship_col, player, board):
guess_col = 0
guess_row = 0
while True:
try:
guess_row = int(input("Guess Row:")) - 1
guess_col = int(input("Guess Col:")) - 1
except ValueError:
print("Enter a number only: ")
continue
else:
break
match = guess_row == ship_row - 1 and guess_col == ship_col - 1
not_on_game_board = (guess_row < 0 or guess_row > 4) or (guess_col < 0 or guess_col > 4)
if match:
player["wins"] += 1
print("Congratulations! You sunk my battleship!")
print('The current match score is %d : %d (Player1 : Player2)' % (player_one["wins"], player_two["wins"]))
print("Thanks for playing!")
play_again()
elif not match:
if not_on_game_board:
print("Oops, that's not even in the ocean.")
elif board[guess_row][guess_col] == "X" or board[guess_row][guess_col] == "Y":
print("You guessed that one already.")
else:
print("You missed my battleship!")
if player == player_one:
board[guess_row][guess_col] = "X"
else:
board[guess_row][guess_col] = "Y"
print(colors['cyan'])
show_board(game_board)
print(colors['reset'])
else:
return 0
def main():
begin = input('Type \'start\' to begin: ')
while (begin != str('start')):
begin = input('Type \'start\' to begin: ')
for turns in range(6):
if player_turns(turns) == player_one:
print(ship_points)
print("Player One")
input_check(
ship_points['ship_row'],
ship_points['ship_col'],
player_one, game_board
)
elif player_turns(turns) == player_two:
print("Player Two")
input_check(
ship_points['ship_row'],
ship_points['ship_col'],
player_two, game_board
)
if turns == 5:
print("The number of turns has ended.")
print(colors['red'])
show_board(game_board)
print(colors['reset'])
print('The current match score is %d : %d (Player1 : Player2)' % (player_one["wins"], player_two["wins"]))
play_again()
if __name__ == "__main__":
main()
It also worked for me when I added an invocation to main in your play_again() function:
# Allows new game to start
def play_again():
positive = ["yes", "y"]
negative = ["no", "n"]
global ship_points
while True:
answer = input("Play again? [Y(es) / N(o)]: ").lower().strip()
if answer in positive:
ship_points = load_game(game_board)
main()
break
elif answer in negative:
print("Thanks for playing!")
exit()
Try modifying main with:
turns = 0
while turns < 6:
# Process turn...
if turns == 5:
# Show endgame board
if play_again():
turns = -1
turns += 1
And have play_again return True on positive input ['y', 'yes'] and False otherwise.
The problem is that your play_again() call, upon receiving "Y" as answer, loads the board, but then simply returns. Where? Well, to the place it was called from - the for loop in main(). And unfortunately, it is the last iteration of said for loop, so the loop then ends and the program exits.
You should've put another loop around the for loop:
while True:
for turns in range(6):
...
I have typed the code from this page PythonForBeginners
but if I execute it, it will go on forever and not ask me whether I want to roll the dices again. Did I miss something? Should this work?
import random
min = 1
max = 6
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print "Rolling the dices..."
print "The values are...."
print random.randint(min, max)
print random.randint(min, max)
roll_again = raw_input("Roll the dices again?")
Well one way to do it is using a class like this.
import random
class RollTheDice(object):
def __init__(self):
self.min = 1
self.max = 6
super(RollTheDice, self).__init__()
def ask_something(self):
while True:
userInput = str(raw_input("Roll Again? Yes or No" + "\n"))
if (userInput == "Yes" or userInput == 'Y'):
self.rollDice()
else:
print("You didn't type 'Yes' or 'Y' no roll for you. Bye....")
exit()
def rollDice(self):
print "Rolling the dices..."
print "The values are...."
print random.randint(self.min, self.max)
print random.randint(self.min, self.max)
RollTheDiceObject = RollTheDice()
RollTheDiceObject.ask_something()
I exit the program if the user doesn't type "Yes" or "Y" with some more code you can make this smarter.
some information on the while loop - https://www.tutorialspoint.com/python/python_while_loop.htm
I've just been working on the same problem as a beginner. I made a few tweaks to your initial code, set out below, and it worked.
import random
min = 1
min = 6
roll_again = "yes"
while roll_again == "yes" or roll_again == "y":
print "You rolled..."
print random.randint (1,6)
roll_again = raw_input("Do you want to roll again?")
A more efficient and elegant solution would be the following:
import random
repeat = True
while repeat:
print ("You rolled", random.randint(1,6))
print ("Do you want to roll again? Y/N")
repeat = ("y" or "yes") in input().lower()
I am using Python 2.7. The program generates a random number and asks the user to guess what it is. The while statements work good. The conditional if statement ends the program without following instructions of print followed by calling the function to see if the user wants to play again.
What makes an if statement not follow instructions? Is there a conflict with the later while statements?
# generate random number between 1 & 9
# have user guess the number, then
# tell them if they guessed too low,
# too high, or exactly right
# keep the game going until user types "exit"
# track how many guesses the user has taken, and when game ends, print it out
import random
a = random.randint(1, 9)
#def whatUp():
#print ("You got it correct")
def playAgain():
wieder = input("Do you wish to play again? Y or N ")
if wieder == "Y":
guessThis()
elif wieder == "N":
print ("Have a day")
elif wieder != "Y" or "N":
wieder = input("Do you wish to play again? Y or N ")
def guessThis():
#a = random.randint(1, 9)
findout = int(input("Enter a number from 1 to 9 "))
i = 1
if findout == a:
#whatUp()
print ("You got it correct")
playAgain()
while findout > a:
print ("too high")
findout = int(input("Enter a number from 1 to 9 "))
i += 1
while findout < a:
print ("too low")
findout = int(input("Enter a number from 1 to 9 "))
i +=1
#while findout != a:
#print ("Incorrect")
#findout = int(input("Enter a number from 1 to 9 "))
#i += 1
guessThis()
Two issues (might be more):
wieder != "Y" or "N": you can't do that, you probably meant to do: wieder not in ["Y", "N"]:
When you declare findout inside a function - it will not be recognized outside. If you want it to be accessed from the outside - create it outside and pass it to the function, or alternatively, make the function return the value that you want back to the caller. Same goes for i.
Comment: regards #1, since you already checked both for 'Y' and 'N', the last condition can be modified from elif wieder != "Y" or "N": to a simple else
import random
a = random.randint(1, 9)
#def whatUp():
#print ("You got it correct")
def playAgain():
wieder = raw_input("Do you wish to play again? Y or N ")
if wieder == 'Y':
guessThis()
elif wieder == 'N':
print ("Have a day")
elif wieder != 'Y' or 'N':
wieder = input("Do you wish to play again? Y or N ")
def guessThis():
#a = random.randint(1, 9)
findout = int(input("Enter a number from 1 to 9 "))
i = 1
if findout == a:
#whatUp()
print ("You got it correct")
playAgain()
if findout > a:
print ("too high")
guessThis()
i += 1
if findout < a:
print ("too low")
guessThis()
i +=1
#while findout != a:
#print ("Incorrect")
#findout = int(input("Enter a number from 1 to 9 "))
#i += 1
guessThis()
Replace guessThis() and everything after with this:
def guessThis():
findout = int(input("Enter a number from 1 to 9 "))
i = 1
#Keep going until win condition reached
while findout != a:
#too high guess
if findout > a:
print ("too high")
#too low guess
if findout < a:
print ("too low")
#get next guess
findout = int(input("Enter a number from 1 to 9 "))
i += 1
#We got out of the while, so the game is done :)
print ("You got it correct")
playAgain()
guessThis()
As yours is currently it will not work if the user guesses too high and then too low.
The main problem was that none of your code was executed in the right order cause your indents were off. You need to put the checking logic in the guessThis() function.
Also there is are issues on this function:
def playAgain():
wieder = input("Do you wish to play again? Y or N ")
if wieder == "Y":
#need to reset a when playing again
a = random.randint(1, 9)
guessThis()
elif wieder == "N":
print ("Have a day")
#because we have already checked (Y || N), simple 'else' gives us (!Y && !N)
else:
wieder = input("Do you wish to play again? Y or N ")
The !"Y" or "N" doesn't work quite like you expect it does, and I assume you want a new value of a for a new game