I'm having an issue with (apparently) a loop not working as intended. Assuming that everything else works as intended, my second while loop is (according to the grader) calling raw_input more times than necessary.
The code plays a word game. You can play a hand, replay a hand, or exit. Second loop determines if you play the hand or the computer.
All the called functions work correctly, but the loop, as I said is calling raw_input too many times.
Sorry if there are lots of other issues, I'm relatively new to coding.
userInput = ''
playInput = ''
hasPlayed = False
# while still playing, e exits
while userInput != 'e':
userInput = raw_input("Enter n to deal a new hand, r to replay the last hand, or e to end game: ").lower()
if userInput not in 'nre':
print("Invalid command.")
elif userInput == 'r' and hasPlayed == False:
print("You have not played a hand yet. Please play a new hand first!")
print
else:
while True:
#
print
playInput = raw_input("Enter u to have yourself play, c to have the computer play: ").lower()
if playInput == 'u':
print
hand = dealHand(HAND_SIZE)
playHand(hand, wordList, HAND_SIZE)
hasPlayed = True
elif playInput == 'c':
print
hand = dealHand(HAND_SIZE)
compPlayHand(hand, wordList, HAND_SIZE)
hasPlayed = True
else:
print("Invalid command.")
print
Your loop is working perfectly fine; it is looping forever just like you told it to:
while True:
What is missing then, is a way to exit that loop. Either test for a different condition:
playing = True
while playing:
# game
#
# stop playing with
playing = False
or explicitly break out of the loop with the break keyword:
while True:
# game
#
# stop playing with
break
Related
I have a while loop that says:
game = True
while game == True:
shop = False
while shop == False:
choice = input("Press ENTER to dig. Press E(then ENTER) to end game. Press S(then enter) for shop.")
if choice == "E" or choice == "e":
game = False
And yet it keeps on repeating and I cant cant figure out why (I'm also new to coding so there could be an obvious answer)
Link to code here: https://repl.it/#WeirdDragon/ore-digging-sim#main.py
You need to break out of the inner loop so you can get back to the outer loop's test.
game = True
while game:
shop = False
while not shop:
choice = input("Press ENTER to dig. Press E(then ENTER) to end game. Press S(then enter) for shop.")
if choice == "E" or choice == "e":
game = False
break
You need shop == True to break from the inner while first. Then, it can realize that game == False
You need to understand how while loops work, take this for example:
a = 5
while a == 5:
a = 6
print('done')
Output:
done
The condition we gave the while loop tells it when to stop looping, but python must first reach the condition again in order to compare, meaning as long as there is no break statement, python will first finish the current loop. But in your code, because of the other while loop in that while loop never ends, we never gave python a chace to compare that game condition.
game = True
while game == True:
shop = False
while shop == False:
choice = input("Press ENTER to dig. Press E(then ENTER) to end game. Press S(then enter) for shop.")
if choice == "E" or choice == "e":
game = False
To fix that, simply add a break statement after the game = False:
if choice == "E" or choice == "e":
game = False
break
I'm creating a dice poker game and am trying to ask if the user would like to play before continuing with the game and then asking if the player would like to play again after each game.
I am unsure how to allow for incorrect inputs other than Y and N in order to tell the user to enter a correct answer and then loop the input until either is input. I am not allowed to use a break.
play = True
s = input("Would you like to play dice poker [y|n]? ")
if s == "y":
play = True
elif s == "n":
play = False
else:
print("Please enter y or n")
while play:
From here onward is the code for my game
This below section is repeated at the end of each game
again=str(input('Play again [y|n]? '))
if again == "n":
play = False
if again == "y":
play = True
else:
print('Please enter y or n')
wrap your input in a function that evaluates the user input, if it's not valid, call it recursively as necessary. Example:
def keep_playing():
valid = 'ny'
again=str(input('Play again [y|n]? '))
a = again.lower().strip() # allow for upper-case input or even whole words like 'Yes' or 'no'
a = a[0] if a else ''
if a and a in valid:
# take advantage of the truthiness of the index:
# 0 is Falsy, 1 is Truthy
return valid.index(a)
# Otherwise, inform the player of their mistake
print(f'{again} is not a valid response. Please enter either [y|n].')
# Prompt again, recursively
return keep_playing()
while keep_playing():
print('\tstill playing...')
My assignment is to create an ATM-type program. Below is my main function (not including the deposit, withdraw, and check balance functions). When I go to run this code, the program loops the pin function repeatedly, even when I enter 0 or 1234. It repeatedly instructs the user to enter their pin. I think I have all of the indentation right, but I guess I'm messing up somewhere in the code.
def main():
pin_number = input("Please enter your pin number")
stop = False
while not is_authorized(pin_number) and stop!= True:
if pin_number == "0":
stop == True
if pin_number == "1234":
stop == False
if stop != True:
while True:
choice = display_menu()
if choice == 1:
deposit()
elif choice == 2:
withdraw()
elif choice == 3:
check_balance()
In your if statements, you should be using = not ==. The first is used for assigning values to variables, like you are trying to do. The second is used to compare if two values are equal and returns a boolean (true/false).
Your code
if stop != True:
will run the code inside the loop if the variable stop is False (the user has entered the wrong code). However, you want to run the code if stop is True.
Therefore, use this code:
if stop == True:
this will run the encased code when stop is True (user has entered correct code)
EDIT:
My apologies. The above answer regards the code following this code:
if pin_number == "1234":
stop = False
I am writing a program with python to simulate flipping a coin or rolling dice. The coin and dice use while loops to give the user the option to roll or flip again, an example is:
def d4():
d4ing = True
while d4ing:
print(random.randint(1,4))
done = input("""would you like to roll again? Type y to roll again,
type d to roll a dice, or type anything else to exit:""")
if done == "y":
continue
elif done == "d":
break
else:
print("thank you for using my coin/dice simulator")
sys.exit("goodbye")
The problem I am having is that I would like to take every line starting from done and make it into it's own function that I can just insert into every function rather than typing the whole thing out again and again, like this.
def d4ing():
d4ing = True
while d4ing:
print(random.randint(1,4))
rerolling()
def rerolling():
done = input("""would you like to roll again? Type y to roll again, type d to roll a dice, or type anything else to exit:""")
if done == "y":
continue
elif done == "d":
break else:
print("thank you for using my coin/dice simulator")
sys.exit("goodbye")
The error message I am getting:
SyntaxError: 'continue' not properly in loop
A break or a continue must be in a loop in its current scope. You cannot break a loop in the above scope from inside a function. Here is a general example of what raises the SyntaxError: 'break' outside loop error. The same holds for continue.
def break_up():
break # This is a syntax error
while True:
break_up()
Although, this is not a problem, since you can make the function return a value and conditionally break in the upper scope.
In your specific example though, you can also return whether or not you want to reroll by assigning the return value to d4ing.
def d4():
d4ing = True
while d4ing:
print(random.randint(1,4))
d4ing = rerolling()
def rerolling():
done = input("Would you like to roll again?")
if done == "y":
return True
elif done == "d":
return False
else:
print("thank you for using my coin/dice simulator")
sys.exit("goodbye")
I am using python 2.6.6
I am simply trying to restart the program based on user input from the very beginning.
thanks
import random
import time
print "You may press q to quit at any time"
print "You have an amount chances"
guess = 5
while True:
chance = random.choice(['heads','tails'])
person = raw_input(" heads or tails: ")
print "*You have fliped the coin"
time.sleep(1)
if person == 'q':
print " Nooo!"
if person == 'q':
break
if person == chance:
print "correct"
elif person != chance:
print "Incorrect"
guess -=1
if guess == 0:
a = raw_input(" Play again? ")
if a == 'n':
break
if a == 'y':
continue
#Figure out how to restart program
I am confused about the continue statement.
Because if I use continue I never get the option of "play again" after the first time I enter 'y'.
Use a continue statement at the point which you want the loop to be restarted. Like you are using break for breaking from the loop, the continue statement will restart the loop.
Not based on your question, but how to use continue:
while True:
choice = raw_input('What do you want? ')
if choice == 'restart':
continue
else:
break
print 'Break!'
Also:
choice = 'restart';
while choice == 'restart':
choice = raw_input('What do you want? ')
print 'Break!'
Output :
What do you want? restart
What do you want? break
Break!
I recommend:
Factoring your code into functions; it makes it a lot more readable
Using helpful variable names
Not consuming your constants (after the first time through your code, how do you know how many guesses to start with?)
.
import random
import time
GUESSES = 5
def playGame():
remaining = GUESSES
correct = 0
while remaining>0:
hiddenValue = random.choice(('heads','tails'))
person = raw_input('Heads or Tails?').lower()
if person in ('q','quit','e','exit','bye'):
print('Quitter!')
break
elif hiddenValue=='heads' and person in ('h','head','heads'):
print('Correct!')
correct += 1
elif hiddenValue=='tails' and person in ('t','tail','tails'):
print('Correct!')
correct += 1
else:
print('Nope, sorry...')
remaining -= 1
print('You got {0} correct (out of {1})\n'.format(correct, correct+GUESSES-remaining))
def main():
print("You may press q to quit at any time")
print("You have {0} chances".format(GUESSES))
while True:
playGame()
again = raw_input('Play again? (Y/n)').lower()
if again in ('n','no','q','quit','e','exit','bye'):
break
You need to use random.seed to initialize the random number generator. If you call it with the same value each time, the values from random.choice will repeat themselves.
After you enter 'y', guess == 0 will never be True.