Where can I add a while loop in this code to ask for another move. I really need help I can't figure it out. I want it to re-prompt the move so when the move is invalid it will ask for another move again. And if the move is valid it will ask for the NEXT move?
def valid1(pile1):
move = False
pile1 = 3
if pile1 == 0:
print 'please choose from pile 2 and 3:'
elif pile1 == 3:
move = int(input('please choose the amount you would like:'))
if move > 0 and move <= 2:
pile1 = pile1 - move
else:
print 'you have entered a invalid move'
return pile1
elif pile1 == 2:
move = int(input('please choose the amount you would like:'))
if move > 0 and move <= 2:
pile1 = pile1 - move
else:
print 'you have entered a invalid move'
return pile1
elif pile1 == 1:
move = int(input('please choose the amount'))
if move > 0 and move <= 1:
pile1 = pile1 - move
else:
print 'you have entered a invalid move'
return pile1
else:
print pile2
print valid1(3)
I'm finding it a bit hard to understand your code precisely, so I'm not sure which bit to loop around, but I think if you use the following general principle you'll fix this:
looping = True
while looping = True :
move = int(input('please choose the amount you would like:'))
if move > 0 and move <= 2:
pile1 = pile1 - move
else:
print 'you have entered a invalid move'
return pile1
In the code above, you'll keep looping and so the input prompt will keep being asked after you've entered a move. If you want to break out of the loop when a certain condition is met, then after you've coded the condition put looping = False. In python, the first letter of Boolean values must be capitalized. There are other ways to do this, such as with break statements etc, but this is the method I prefer to use. As I said, I wasn't sure exactly what you wanted looping around in the code, but if you enclose it all in a 'while' statement like above, it should be fixed. Hope this helps!
Related
I have an assignment to create a program where a user guesses a random 5 digit number. What i have works except for one part. When a user enters a number that is longer than 5 digits its just supposed to print this is too long and move on to the next try. For what i have it instead prints the error and stops the game. Is there away that i can fix this?
while not userguess:
uniquedigits_found = 0
tries += 1
guess = str(input("Enter your 5 digit attempt: "))
if len(guess) < 5:
print("this is too short")
elif len(guess) > 5:
print("this is too long")
The solution is simple: just add two continue statements:
if len(guess) < 5:
print("this is too short")
continue
elif len(guess) > 5:
print("this is too long")
continue
These will cause execution to instantly continue on to the next pass through the while loop, skipping over the code that triggers the index error.
I'm implementing a game which allows two players to pick alternately from a pile of 27 sticks. Each player may take 1, 2, or 3 sticks on each turn; the player forced to take the final stick loses.
I've done most of the code, but I must include validation. Besides taking 1-3 sticks, a player is not allowed to take the final stick. I've tried using a continue statement, but when player two exceeds the limit, the program returns to player 1's turn.
Here's what I have so far:
count = 27
T = False
F = False
while count > 1:
Playerone = int(input("Player 1's Turn, Enter from 1-3"))
if Playerone < 1 or Playerone > 3:
print("Error")
continue
count -= Playerone
print(count)
if count == 1:
print("P1 wins")
break
if count < 1:
print("You can't pick up those many sticks")
continue
Playertwo = int(input("Player 2's Turn, Enter from 1-3"))
if Playertwo < 1 or Playertwo > 3:
print("Error")
continue
count -= Playertwo
print(count)
if count == 1:
print("P2 wins")
break
if count < 1:
print("You can't pick up those many sticks")
continue
The last if statement is the issue
Help would be much appreciated,
You have a basic flaw in your loop flow: regardless of the problem encountered with either player's input, you use continue to return to the top of the loop, which gets you back to Player 1. You need to fix this: loop on a given player's input until it's valid in all ways. Something like this should do:
valid = False
while not valid:
Playertwo = int(input("Player 2's Turn, Enter from 1-3"))
if Playertwo < 1 or Playertwo > 3:
print("Error")
elif count - Playertwo < 1:
print("You can't pick up those many sticks")
else:
valid = True
Apply this to each player's input. Once you get out of this loop, you have valid input. From there, you can decrease the count and determine whether someone has won.
One way to ensure a valid user input is to use a loop.
Here's a quick example of a function you might use:
def prompt_integer(msg, minval, maxval, err_invalid, err_oob):
while True:
resp = input(msg) # Python3, use raw_input in Python2
try:
resp = int(resp)
if minval <= resp <= maxval:
return resp
else:
print(err_oob)
except ValueError:
print(err_invalid)
x = prompt_integer("Enter an integer: ", 1, 3, "Invalid Integer.", "Integer Out of Bounds")
Here, the function will not return until the user enters a valid integer between 1 and 3 (inclusive).
If they enter, say, 'abc', then the program will display "Invalid Integer." and ask them again.
If they enter, say, 5, when you've specified that the bounds are 1 and 3 then the program will display "Integer Out Of Bounds", and then ask them again.
When this function returns you know you've got an acceptable value.
You might use this function in your code, and modify maxval argument each time you call it according to how many sticks they're able to pick up.
This is what I would do, you could go crazy with Classes, but that is a little much for you right now(but something to look into). You should also look into creating methods, but check out my code below with the comments I left.
def player_input(player_number: int): # This is a method, that requires an integer to be pass to it
p_input = int(input("Player {}'s Turn, Enter from 1-3: ".format(player_number)))
while p_input < 1 or p_input > 3: # This will cause a loop continuously asking the player to input a number until that number is between 1 or 3.
print('Please choose a number between 1 and 3')
p_input = int(input("Player {}'s Turn, Enter from 1-3: ".format(player_number))) # Format will replace the '{}' with the value of the variable you give it
return p_input # This 'return' line will return the what the results of what the player typed in
def found_winner(stick_number: int): # stick_number is a required variable and ': int' requires that that variable be an integer
winner = False
if stick_number == 1:
winner = True
return winner # This method will return if a winner is found or not
def next_player(player_number: int): # This method will swap the players turn
if player_number == 1:
player_number = 2
elif player_number == 2:
player_number = 1
return player_number
def start_game(stick_count: int = 27): # This method will start the game, the '= 27' says that you can give me any stick count you want(that is an integer), but if you don't provide one I will use '27' by default
player_number = 1
while stick_count > 1: # This will loop through until the stick count is 1 or less
sticks_to_remove = player_input(player_number) # I store the plays result just in case the stick_count goes below 1, and then I remove the sticks if the the count doesn't go below 1
if stick_count - sticks_to_remove < 1:
print('You cant pick up that many sticks')
continue
else:
stick_count -= sticks_to_remove # Remove the sticks
if found_winner(stick_count): # Look for the winner
print('Player {} wins!'.format(player_number))
else:
player_number = next_player(player_number) # If no winner go to the next player
if __name__ == '__main__': # This says only execute the 'start_game()' method automatically if this python script is called, this is useful later when you start creating more complicated Python scripts that span multiple files.
start_game()
Working on a battleship game in python. My function to check the user's 'guess' input in resulting in an endless validation loop. I want a guess in the format of 'a10' on a 10x10 grid. The validation function i have built to help validate is as follows:
def validate_guess(self,guess):
while True:
if (len(guess)) in range(2, 4):
if guess[0] not in 'abcdefghij' or guess[1:] not in '1,2,3,4,5,6,7,8,9,10':
print("Sorry the Grid is a 10x10 square you must enter a valid position. Try again...")
continue
else:
return guess
else:
if len(guess) < 2 or len(guess) > 3:
print("Oops! That's too not the right amount of characters. Please try again...")
continue
If the user guesses an incorrect value--it does spot it--but the error is returning a never ending loop with the printed error statement.
This is the portion of my game where the validation function is being used:
while True:
print("\n")
# get guess from player one in coordinate form (example: a10)
guess = input("{}'s turn to guess: ".format(player1.player))
# strip characters from the guess input
guess = guess.strip()
# validate the guess
guess = self.validate_guess(guess)
# append the guess to a list for player 1
player1.guesses.append(guess)
# break down the coordinates into x and y variables
x, y = ship1.split_guess(guess)
# increment guesses
guesses += 1
# loop to assess whether, hit, miss or a won game
if any(guess in ship for ship in grid2.play_two_board):
print("HIT")
grid2.print_guess_board(x, y, "h")
for ship in grid2.play_two_board:
try:
ship.remove(guess)
print(len(Board.play_two_board))
self.check_if_sunk(ship)
win = self.play_one_win_check(player1.player)
if win == 1:
print ("GAVE OVER!")
break
except ValueError:
pass
else:
print("Miss!")
grid2.print_guess_board(x, y, "m")
Not sure if it might be because i have two While statements? Just really stuck here would appreciate any guidance. Thanks.
*****************************8
edit --changed function to include the guess without actually passing it that value from the input statement but still getting same problem.
def validate_guess(self):
guess = input("Please enter a location:")
while True:
if len(guess) in range(2, 4):
if guess[0] not in 'abcdefghij' or guess[1:] not in '1,2,3,4,5,6,7,8,9,10':
print("Sorry the Grid is a 10x10 square you must enter a valid position. Try again...")
continue
else:
return guess
else:
if len(guess) < 2 or len(guess) > 3:
print("Oops! That's too not the right amount of characters. Please try again...")
continue
and just calling it like this:
while True:
print("\n")
# get guess from player one in coordinate form (example: a10)
# guess = input("{}'s turn to guess: ".format(player1.player))
# strip characters from the guess input
# guess = guess.strip()
# validate the guess
guess = self.validate_guess()
Within validate_guess, when the user enters a bad value, you have to get new input before you check again. See here.
Either return an error code (True/False ?) from your function, or have the function loop until the input is valid. Just add a command for new input at the bottom of the function's while loop.
The major problem I'm having is what occurs when I choose stay on hand_one, and then hit on hand_two.
Instead of asking me to hit or stay on hand_two again, it brings me back to hit or stay on hand_one, when I already chose stay on hand_one, so hand_one should have no more options. This causes issues with multiple print statements occurring and incorrect game play.
What is wrong with my code that it is like causing it to loop back to hand_one.
The full code is here: http://labs.codecademy.com/Bjaf/2#:workspace
Here is the part likely causing the issue.
def hit_or_stay(person):
hit_or_stay = raw_input("Do you want to hit or stay? You can type h or s.")
if hit_or_stay == 'h' or hit_or_stay == 'hit':
deal_one_card(person)
value_of_current_cards(person)
number_value_of_hand()
elif hit_or_stay == 's'or hit_or_stay == 'stay':
print "You stayed"
return
else:
hit_or_stay(person)
def number_value_of_hand():
if number_of_hands > 0:
value_of_hand_one = value_of_current_cards(hand_one)
if value_of_hand_one < 18:
print "\n" "You have %i" % (value_of_hand_one)
hit_or_stay(hand_one)
elif value_of_hand_one > 18:
print "You Lose"
return
elif value_of_hand_one == 18:
print "You hit HOT 18!!!"
return
if number_of_hands > 1:
value_of_hand_two = value_of_current_cards(hand_two)
if value_of_hand_two < 18:
print "\n" "Your second hand has %i" % (value_of_hand_two)
hit_or_stay(hand_two)
elif value_of_hand_two > 18:
print "You Lose"
return
elif value_of_hand_two == 18:
print "You hit HOT 18!!!"
return
number_value_of_hand()
Can anyone see why it loops back to give hand_one another option? And possibly how I can fix it? Thanks so much!
Your problem occurs on this step:
hit_or_stay(hand_two)
When you hit on hand_two, your code does this:
deal_one_card(person)
value_of_current_cards(person)
number_value_of_hand()
The problem is right there, because number_value_of_hand() brings you back to the beginning of that function, and goes through the hand_one options again.
You will probably have to rewrite your number_value_of_hand() function to include an argument that tells it where to begin (hand_one, hand_two, etc.)
I would probably make a list of hands, and iterate through the list. Then, you could call number_of_hands(hands[i]) to being at the ith hand.
I am trying to go back to the top of a function (not restart it, but go to the top) but can not figure out how to do this. Instead of giving you the long code I'm just going to make up an example of what I want:
used = [0,0,0]
def fun():
score = input("please enter a place to put it: ")
if score == "this one":
score [0] = total
if score == "here"
if used[1] == 0:
score[1] = total
used[1] = 1
elif used[1] == 1:
print("Already used")
#### Go back to score so it can let you choice somewhere else.
list = [this one, here]
I need to be able to go back so essentially it forgets you tried to use "here" again without wiping the memory. All though I know they are awful, I basically need a go to but they don't exist in python. Any ideas?
*Edit: Ah sorry, I forgot to mention that when it's already in use, I need to be able to pick somewhere else for it to go (I just didn't want to bog down the code). I added the score == "this one"- so if I tried to put it in "here", "here" was already taken, it would give me the option of redoing score = input("") and then I could take that value and plug it into "this one" instead of "here". Your loop statement will get back to the top, but doesn't let me take the value I just found and put it somewhere else. I hope this is making sense:p
What you are looking for is a while loop. You want to set up your loop to keep going until a place is found. Something like this:
def fun():
found_place = False
while not found_place:
score = input("please enter a place to put it: ")
if score == "here"
if used[1] == 0:
score[1] = total
used[1] = 1
found_place = True
elif used[1] == 1:
print("Already used")
That way, once you've found a place, you set found_place to True which stops the loop. If you haven't found a place, found_place remains False and you go through the loop again.
As Ashwini correctly points out, you should do a while loop
def fun():
end_condition = False
while not end_condition:
score = input("please enter a place to put it: ")
if score == "here":
if used[1] == 0:
score[1] = total
used[1] = 1
elif used[1] == 1:
print("Already used")