from random import randint
from time import sleep
fight = False
def start_up():
print("Fight Simulator - Test Stages.")
userInput = str(input("Enter your name "))
user_name = userInput
return user_name
def intro():
userName = start_up()
while True:
userInput = str(input("Welcome to the dojo, {}. To commence the first battle, type 'Start', or 'Begin'".format(userName)))
if userInput == "Start" or "start" or "Begin" or "begin":
return userInput
else:
print("Enter a valid response")
break
def fight_commence():
userInput = intro()
if userInput == "Start" or "start" or "Begin" or "begin":
fight = True
userHp = 100
opponentHp = 100
while fight == True:
userDmg = randint(0,100)
opponentDmg = randint(0,100)
opponentHp -= userDmg
if opponentHp <= 0:
opponentHp == 0
print("You did {} damage".format(userDmg))
sleep(1)
print("Opponent has {} hp remaining".format(opponentHp))
sleep(1)
if opponentHp <= 0:
print("You killed him!")
fight = False
else:
print("Enter a valid action")
fight_commence()
So for some reason the code doesn't print("Enter a valid response") when a response other than "Start" or "start" or "Begin" or "begin" is given. I want it to loop back to userinput stage, but instead it just carries on with the program as if everything is A ok. I can't figure out where I messed up.
Secondly, I want the opponentHp to automatically equal 0 when the health dips below 0. For instance, when opponentHp = -45, opponentHp should equal 0.
Any help is appreciated.
Well a big problem with the testing of the 'valid input' is the way your testing.
if userInput == "Start" or "start" or "Begin" or "begin"
This is not a valid python condition. Instead do something like this:
if userInput in ["Start", "start", "Begin", "begin"]
This comparison happens twice and is no good. For the opponenthp being 0, you currently have this as your statement and result:
if opponentHp <= 0:
opponentHp == 0
The condition is perfectly fine, but the == in the action is another conditional operator, you need to change it to:
if opponentHp <= 0:
opponentHp = 0
ADDITION
Also, in addition to the above items, when you use the break statement you will end the infinite loop you have set up and end the function without a returned value, you may want to consider changing it to a continue or pass statement, or simply remove it.
The conditions (if-clause) are wrong. You should repeat 'userInput==' for every or.
Or, more concisely this:
userInput.lower() in ["start", "begin"]
Related
This question already has answers here:
Why doesn't the while loop stop when the condition becomes False?
(3 answers)
Closed last month.
I'm assuming the issue has to be with setting a global variable but even with my trying to fix it with that, I still can't seem to figure it out. Code is pretty rough but I only started learning <2 days ago so please bear with me. From my understanding, if the password is entered correctly, the game variable should be equal to False which should end the loop. However, it keeps going on and asking player 1 for input. Also, I can't seem to be getting the checkGame function to work properly inside the while loop.
board = [
0,1,2,
3,4,5,
6,7,8
]
print(board)
global counter
counter = 0
global game
game = True
def checkGame():
if board[0] == player_1:
print("Game won by player 1!")
game == False
def player_1():
player_1 = 'X'
# return player_1
selection = int(input("P1: Pick a position: "))
board[selection] = player_1
print(board)
global game
global counter
counter += 1
print("Counter = ", counter)
print("game:", game)
def player_2():
player_2 = "O"
selection = int(input("P2: Pick a position: "))
board[selection] = player_2
print(board)
global counter
counter += 1
print("Counter = ", counter)
print("game:", game)
while game == True:
password = input("password: ")
if password == 'testing':
game = False
print(game)
else:
pass
if counter == 9:
game = False
player_1()
if board[0] == player_1:
print("Game won by player 1!")
game == False
if counter == 9:
game == False
checkGame()
player_2()
if counter == 9:
game == False
checkGame()
A while loop's condition is not checked continuously, only at the start of each loop iteration. To exit the loop immediately use a break statement. For example, in this code it will print "Keep running" even after you type "exit"
running = True
while running:
password = input("password: ")
if password == "exit":
running = False # does not exit the loop, just stops the next run
print("Keep running")
but in this code it will not
running = True
while running:
password = input("password: ")
if password == "exit":
break # exits the loop
print("Keep running")
Also, unrelated to your immediate issue of not exiting on the password entry, var == False does not set var to false, it just checks if it is equal to false. Be sure to use = for assignment, not ==.
You also seem to be mixing method names and variable names (e.g. player_1) which is probably going to cause problems...
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 1 year ago.
I have a y/n query at the end of the game which will restart the game or exit the game.
y and n work as they should, but if I enter any other letter even if it does print the "please try again message", it restarts the game anyway. I thought it should only do that if I put continue, but I haven't
I also want it to recognize y or n as upper case, is there a command in python that allows a letter to be recognized regardless of if its upper or lowercase?
play_again = input('Would you like to play again?(y/n) ')
if play_again == 'y': #loop restarts
print('Starting another game...')
continue
elif play_again == 'n': #loop is exited
print('Thank you for playing! You have now exited the game.')
break
else:
print ("I don't recognize that character, please select y or n")
I have provided the loop as requested, but the last time I did this I got in trouble:
number_of_stones = int(input('Select between 30-50 stones to start your game: ' )) #player1 chooses stones
if number_of_stones >= 30 and number_of_stones <= 50:
print('Starting the game...')
has_winner = False # Winner = False since there no winners (start of game)
while True:
for player in player_list:
if has_winner: # if there is a winner, exit loop
break
# display whose turn is it
print('\n{}\'s turn:'.format(player))
while True:
# if the player is computer use strategy that is mentioned in assignment 2
if player == 'Mr Computer':
remainder = number_of_stones%3
if remainder == 0:
stones_to_remove = 2
else:
stones_to_remove = 1
# if the player is not the computer
else:
stones_to_remove = int(input('Select between 1-3 stones to remove: '))
# assess the number of stones remaining and print the remainder to the screen
if stones_to_remove >= 1 and stones_to_remove <= 3:
number_of_stones -= stones_to_remove
print('Number of stones remaining:',number_of_stones)
if number_of_stones <= 0:
print('The winner is:',player,"!")
has_winner = True
break
else: # show error and let the user input again
print("I'm sorry, that number is outside the range. Please choose a number between 1 and 3")
if has_winner == True: # if the winner=true then exit loop
break
play_again = input('Would you like to play again?(y/n) ').lower() #only accepts lower case letter
if play_again == 'y': #loop restarts
os.system('cls') # clear the console
print('Starting another game...')
continue
elif play_again == 'n': #loop is exited
print('Thank you for playing! You have now exited the game.')
break
else:
print("I'm sorry, that number is outside the range. Please select between 30 and 50 stones.")
You haven't added necessary information ,i.e. rest of the loop , try add that .
For case insensitivity , just use the following
if play_again == "n" || play_again == "N":
.
Essentially, I'm trying to create a main function that can take input, and use that list of input to calculate the median, mode, and mean by using another function. I'm a novice coder (taking my first class) so any help that can point me in the right direction while still helping me learn will be greatly appreciated.
def median(alist):
srtd = sorted(alist)
mid = len(alist) // 2
if len(alist) % 2 == 0:
return (srtd[mid -1] + srtd[mid]) / 2.0
else:
return (srtd[mid])
def main():
yourlist = []
addons = list(float(input("Enter your list of number to be calculated(stop to stop): ")))
if addons != "stop":
data.append(yourlist)
elif addons == "stop":
break
else:
print("Bad input, try again: ")
continue
medresult = median(yourlist)
return medresult
print(medresult)
break and continue are to only be used in a loop such as for or while
So your main () should have a while loop in it.
def main():
yourlist = []
while True:
addons = input("Enter your list of number to be calculated(stop to stop): ")
if addons != "stop":
data.append(yourlist)
elif addons == "stop":
break
else:
# This block will never run because an input can either equal or not equal "stop"
print("Bad input, try again: ")
continue
Personal preference, but I would change your if statements to
if 'stop' not in addons:
data.append(yourlist)
and the elif to
elif not all(isinstance(number, float) for number in addons):
print("Bad input, try again")
This checks each inputted number in the addons list to see if it is a float. If not all are floats, then print the try again message
this is a crabs simulator. Im having trouble with my while loop. Where it says
while val == True:
Is where the problem happens. It stays in the while loop but nothing happens. If you find anything, I will be most grateful.
Here is the full code. (I have tried to validate everything)
import time
import random
control1 = False
control2 = True
x = True
val = True
z = True
def throw(n):
for i in range(1,n+1):
dice_1 = random.randint(1,6);dice_2 = random.randint(1,6)
print "roll",i,", die 1 rolled",dice_1,"and die 2 rolled",dice_2,",total",dice_1+dice_2
time.sleep(2)
return n
while z == True:
if x == True:
while control1 == False:
try:
amount_1 = int(raw_input("Welcome to crabs.\nHow many times would you like to roll:"))
control1 = True
except ValueError:
print ("Enter a valid number.")
throw(amount_1)
x = False
else:
while val == True:
roll_again = raw_input("Would you like to roll again: ")
if roll_again == "1":
val = False
while control2 == True:
try:
amount_2 = int(raw_input("How many times would you like to roll:"))
control2 = False
except ValueError:
print ("Enter a valid number.")
throw(amount_2)
z = True
elif roll_again == "2":
val = False
exit()
else:
val = True
After your first run through the program x and val are both False, but z is still True. As a result, the outer loop just keeps on rolling.
Put this line:
print z, x, val
Underneath that while statement.
You'll see that after you respond to the "Would you like to roll again: " question with "2", both x and val are false. That means that it'll go through every part of your if..else statement and just keep looping back infinitely.
It's stuck in an endless loop after the else branch (of if x) is executed, because you set the value to False. In the next iteration you then say while val == True and since this statement is not False and there is no other statement to consider, you run in an endless loop.
To see what I mean simply add a print statment here:
else:
print val
while val == True:
roll_again = raw_input("Would you like to roll again: ")
if roll_again == "1":
Now, I don't know if you need all those booleans for your actual program, but if I'd to make it work, I'd start eliminating the booleans I don't need. I think you have a too complex structure.
Edit:
Here's a suggestion to make the program simpler.
import time
import random
x = True
z = True
def throw(n):
for i in range(1,n+1):
dice_1 = random.randint(1,6);dice_2 = random.randint(1,6)
print "roll",i,", die 1 rolled",dice_1,"and die 2 rolled",dice_2,",total",dice_1+dice_2
time.sleep(2)
return n
def ask(x):
if x:
print "Welcome to crabs."
try:
amount = int(raw_input("How many times would you like to roll:"))
except ValueError:
print ("Enter a valid number.")
throw(amount)
while z:
ask(x)
x = False
roll_again = raw_input("Would you like to roll again: ")
if roll_again == "1":
continue
else:
break
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.