Why is an elif statement being ignored [duplicate] - python

This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
I'm writing a program as an exercise for if-elif-else statements and I could do with some advice as to why an elif statement is not running.
I want to give the option to pick up rocks for the inventory.
That works, but if I say I do NOT want to pick up the rocks, that elif statement seems to be ignored and I pick up the rocks and they are added to my inventory.
I have no actual errors, but cannot see why the elif statement is not being actined. I have used this several times in the same program as part of this exercise and not had this continual problem.
These are the statements I seem to be having issues with:
elif num >=2 and rocks_there == True:
print("""You keep within touching distance of the castle wall.
You come across some rocks. Do you want to pick them up.""")
take = input("> ").lower()
if "yes" or "y" in take:
print("You pick up the rocks.")
inventory.append('Rocks')
rocks_there = False
print("You follow the castle walls around to the front of the castle again.")
grounds()
elif "no" or "n" in take:
inventory = inventory
rocks_there = True
print("You leave the rocks on the path.")
print("You follow the castle walls around to the front of the castle.")
grounds()
Here is the whole of the function:
def fog():
global inventory
global rocks_there
print("You walk along the path to the left of the castle when a thick fog starts swirling around you.")
print("Do you want to CARRY on or go BACK to the courtyard?")
choice = input("> ").lower()
if "back" in choice:
grounds()
elif "carry" in choice:
num = random.randint(0,10)
if num < 2:
print("""The fog envelopes you until you have no idea where you are and can see nothing else.
Suddenly you feel yourself fall as you step over the edge of a towering cliff.
You die, but at least you are not undead.""")
exit(0)
elif num >=2 and rocks_there == True:
print("""You keep within touching distance of the castle wall.
You come across some rocks. Do you want to pick them up.""")
take = input("> ").lower()
if "yes" or "y" in take:
print("You pick up the rocks.")
inventory.append('Rocks')
rocks_there = False
print("You follow the castle walls around to the front of the castle again.")
grounds()
elif "no" or "n" in take:
inventory = inventory
rocks_there = True
print("You leave the rocks on the path.")
print("You follow the castle walls around to the front of the castle.")
grounds()
elif num >= 2 and rocks_there == False:
print("You follow the castle walls around to the front of the castle.")
else:
print("The fog has scrambled your brain and I do not understand you.")
print("I hope you find your way out.")
print("Goodbye!")
exit(0)

If you try this simple code
mylist = []
if "yes" or "y" in mylist:
print("oops")
you'll see that the code is interpreted as
mylist = []
if "yes" or ("y" in mylist):
print("oops")
And since
if "yes":
print("oops")
it will always run through the if-part and never through the elif part. That's because "yes" is considered a truthy value.
What you probably wanted is
if take in ["y", "yes"]:
which is "check if the user input (take) is in the list ([]) of possible answers". And similar for the no-part of the statement.

Related

If-Else doesn't return desired output [duplicate]

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 8 months ago.
I was doing the study drills for this chapter and I've stumbled upon this problem that I can't seem to figure out, maybe I'm missing something.
Here's the code:
# write a small adventure game similar to ex31
print("""You enter a dungeon and you find yoursfelf in front of three doors.
Do you go through door #1, door #2 or door #3?""")
dungeon_door = input(">> ")
if dungeon_door == '1' or '2':
print("You stumble upon a goblin. What do you do?")
print("1 - Try to kill the goblin with your shoe.")
print("2 - Try to talk things out.")
print("3 - Exit through the door you came from.")
goblin = input(">> ")
if goblin == '1':
print("You actually manage to kill the goblin. Dude you're a beast!")
print("You have to choose between two doors, do you pick the left one or the right one?")
final_door = input(">> ").lower()
if final_door == 'left':
print("This door leads to the treasure chamber. Dungeon cleared, congrats!")
elif final_door == 'right':
print("After you open to door an enormous one-eyed monster eats you. This dungeon was too much for you, try again.")
else:
print(f"What does {final_door} even mean? You're kicked out of the dungeon, bye.")
elif goblin == '2':
print("""Can you speak Ghukliak? Don't think so. The goblin doesn't understand you, you're dead.
The dungeon was too much for you, bye.""")
elif goblin == 3:
print("The door is somehow locked. The goblin takes this chance to kill you. The dungeon was too much for you, bye.")
else:
print(f"What does {goblin} even mean? You're kicked out of the dungeon, bye.")
elif dungeon_door == '3':
print("Well, it's your lucky day. This door leads directly to the treasure chamber. Dungeon cleared, congrats!")
else:
print(f"What does {dungeon_door} even mean? You're kicked out of the dungeon, bye.")
So part of the code works fine, the only problem I have is when I ask the user to make the first choice.
When I input '3' as the answer or something completely different from the suggested answers, I get the output as if the user has answered with '1' or '2'. I hope I have been clear enough.
I know it's a bit long and boring, sorry and TIA!
Your logic is wrong here:
if dungeon_door == '1' or '2':
Should be:
if dungeon_door == '1' or dungeon_door == '2':
Or
if dungeon_door in ('1', '2'):
And you forgot quotes around the 3
elif goblin == 3:

How Can I Give the User 5 Lives for my script?

Title.
I'm currently writing a choose your own adventure python script for my computer science class and need to give the player 5 lives and when they run out have a line of text appear. Any ideas?
(I'm not sure if I need to post the script or not but I can later today if needed.)
script:
# Name: Drew Dilley
**# Date: 12/7/20
# 1 REMOVED IMPORT MATH BECAUSE IT IS NOT NEEDED FOR THIS SCRIPT.
# 2
import random
answer: str = input("Do you want to go on an adventure? (Yes/No)")
# hint: the program should convert player's input to lowercase and get rid of any space player enters
# hint: check out what .upper(), .lower(), .strip() do on a string, reference: https://www.w3schools.com/python/python_ref_string.asp
# 3
if answer.upper().strip() == "yes":
# hint: pay attention to the variable name
# 4
ANSWER= input("You are lost in the forest and the path splits. Do you go left or right? (Left/Right) ").lower().strip()
if answer == "left":
# 5 UNNECESSARY INDENT
answer = input("An evil witch tries to cast a spell on you, do you run or attack? (Run/Attack) ").lower().strip()
if answer == "attack": #(HAD TO FIX UNEXPECTED INDENT)
print("She turned you into a green one-legged chicken, you lost!")
# 6 HAD TO ADD PARENTHESES AND FIX THE SEMICOLON AFTER "ANSWER"
elif answer := "run":
print("Wise choice, you made it away safely.")
answer = input("You see a car and a plane. Which would you like to take? (Car/Plane) ").lower().strip()
if answer == "plane":
print("Unfortunately, there is no pilot. You are stuck!")
elif answer == "car":
print("You found your way home. Congrats, you won!")
# 7 SEMICOLON NEEDED AFTER "ELSE" PLANE/ANSWER + CAR/ANSWER NEEDED TO BE FLIPPED. NO INDENTATION NEEDED FOR "ELSE". == INSTEAD OF !=
elif answer != "plane" or answer != "car":
print("You spent too much time deciding...")
elif "right" != answer:
else:
print("You are frozen and can't talk for 100 years...")
# hint: the program should randomly generate a number in between 1 and 3 (including 1 and 3)
# hint: remember random module? reference: https://www.w3schools.com/python/module_random.asp
# 8 HAD TO IMPORT "RANDOM"
num: int = random.randint(0,3)
# 9
answer = input("Pick a number from 1 to 3: ")
# hint: will the following if statement ever be executed even when the values of answer and num are the same? If not, can you fix the problem?
# hint: the error is not necessarily in the line below.
if answer == num:
print("I'm also thinking about {}".format(num))
print("You woke up from this dream.")
else:
print("You fall into deep sand and get swallowed up. You lost!")
else:
print('You can\'t run away...')
# 10 NEEDED A SEMICOLON FOLLOWING THE ELSE STATEMENT, SO THAT IT KNOWS WHAT TO READ AND PERFORM NEXT IN THE SCRIPT.
else:
print ("That's too bad!")** ```
you can use a for loop with a counter variable which you can decriment at every time player looses and when it goes from 5 to zero you can use break to exit the loop or a print before break to display a message.

How can I ask the player if they want to replay my Python3 terminal number guessing game? [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 3 years ago.
I have an almost working code for my number guessing game. It runs completely fine up until the very end when asking the player if they want to play again and they type in "yes"--the Terminal outputs this:
Ha ha. You took too many guesses! I win! ^__^
Would you like to play again? (yes/no) yes
I'm thinking of a number between 1 and 99!
Ha ha. You took too many guesses! I win! ^__^
Would you like to play again? (yes/no)
I thought to just put the entire program in a while loop, but I have a few opening questions in the game that should only be asked the first time they run the program, and not every time they want to replay the game. (e.g Whats your name? Do you want to play?) I am not sure how to rerun the program but starting just after those initial questions. With my current code, I am lost at what to write for when the player types in "yes" at the ending to replay the game.
import random
import sys
guesses_taken = 0
number = random.randint(1, 99)
name = input("\nHello, what's your name? ")
print(f"\nNice to meet you, {name}.")
answer = input("Would you like to play a guessing game? (yes/no) ").lower()
while True:
if answer == "no":
print("\nToo bad, goodbye!\n")
sys.exit()
elif answer == "yes":
print(f"\nOkay, let's play!")
break
else:
print("\nSorry, I didn't get that.")
while True:
print("\nI'm thinking of a number between 1 and 99!")
while guesses_taken < 6:
guess = input("Take a guess: ")
guesses_taken += 1
if int(guess) > number:
print("\nYour guess is too high!\n")
elif int(guess) < number:
print("\nYour guess is too low!\n")
else:
print("\nArgh..you guessed my number! You win! -__-")
break
while guesses_taken >= 6:
print("\nHa ha. You took too many guesses! I win! ^__^")
break
again = input("\nWould you like to play again? (yes/no) ")
if again == "no":
break
sys.exit()
The variables guesses_taken & number will both retain their values when replaying, which makes for a not-very-interesting game. You need to do something to change that, like -
again = input("\nWould you like to play again? (yes/no) ")
if again == "no":
break
else:
guesses_taken = 0
number = random.randint(1, 99)
Functions, etc can make the code cleaner, but this is the minimal change you need to make to get things working.

snakes and ladders dice problems(python)

fixed it now thanks for the help, just needed to indent everything for my player 2
so i have made a snakes and ladders game and i'm having problems with the dice:
while player1roll != "YES":
player1roll=input("player1 ready to roll??\n").upper
player1roll=random.choice(dice)
print("you rolled a:", player1roll)
after this it just keeps repeating "player1 ready to roll??"
here is the whole of my player1 code:
while selection != "PVP" or "AI":
selection=input("player vs player(PVP) or with AI (AI)??\n").upper()
if selection == "PVP":
while player1pos or player2pos <100:
**while player1roll != "YES":
player1roll=input("player1 ready to roll??\n").upper
player1roll=random.choice(dice)
print("you rolled a:", player1roll)**
player1pos+=player1roll
if board[player1pos] >0: #if the number is bigger than 0 its a ladder
print("you found a ladder")
player1pos+= board[player1pos] #find the position its supposed to be at on the board
print("player1 is at position:",player1pos)
print("")
elif board[player1pos] <0: #if the number is negative then its a snake
print("you found a snake")
player1pos+=board[player1pos]
print("player 1 is at position:",player1pos)
print("")
else: #if its just a 0 they stay at that position
print("player1 is at position:",player1pos)
print("")
if 100<=player1pos: #if the player position is 100 or more they win
print("player1 win")
quit()
if you could suggest any other changes that would help too as i need to try and improve it as much as possible :)
You need to reset player1roll equal to NO inside of that if statement.
if the above is your code it appears there is a typo in your code.
player1roll=input("player1 ready to roll??\n").upper
is missing the ending parenthesis so it should be grabbing the function and not the "YES".
EDIT:
in the following code player1roll is used for both player input and the rolling of dice. This causes the die roll to override the acceptance of his turn. If the die roll supposed to be a part of the while loop, then you should create a new variable.
while player1_input != "YES":
player1_input=input("player1 ready to roll??\n").upper
player1roll=random.choice(dice)
print("you rolled a:", player1roll)
When you say "it just keeps repeating "player1 ready to roll?"" is that literally the only output you are seeing? No other output?
You do realize you are setting player1roll to a random element from the the "dice" sequence, right? Does it make sense to use the same variable for the user input and the roll value?
How about changing your variable names?
Change:
while player1roll != "YES":
player1roll=input("player1 ready to roll??\n").upper
To:
while player1in != "YES":
player1in=input("player1 ready to roll??\n").upper

How would I return up to a higher up line and have it execute in Python?

I'm fairly new to programming and am trying to create a very simplistic dungeon game. I have most it working but I'm having a slight issue. Here is my code:
print("Welcome to Matt's Dungeon!")
user = ""
stop = "q"
while user != "q":
first = input("You are in the kitchen. There are doors to the south (s) and east (e). ")
if first == "s":
print("You entered the furnace and fry yourself to death!")
break
elif first == "q":
break
elif first == "e":
second = input("You are in the hallway. There are doors to the west (w), south (s), and east (e). ")
if second == "w":
first == "s"
elif second == "q":
break
elif second == "e":
print("You are in the library. You found the princess! You are a hero!")
break
elif second == "s":
third = input("You are in the living room. There are doors to the west (w) and north (n). ")
if third == "w":
print("You entered the furnace and fry yourself to death!")
break
elif third == "n":
first == "e"
elif third == "q":
break
print("Goodbye!")
The issue that I'm having is that if the user enters "n" in the living room I want it to go back to the hallway but the program always sends it back to the original kitchen. However, if the user enters "w" in the hallway this works fine and returns it to the previous room, the kitchen. Any ideas on how I might be able to fix this? Thank you in advance for any help!
Lets ignore the indentation problems which presumably you copied incorrectly.
Your control flow is a huge mess. Basically lets look at your basic structure:
while True:
first = input("You are in kitchen")
# additional program logic
Can you see why, whatever happens with the remaining logic you do here you will always return to the kitchen after a continue?
One option to get the structure that you actually want is to program a little less sequentially. Here is a psuedocode example of one possible way to design your game, with some parts of the design left intentionally unspecified. I provide this to get you to think about ways in which you might design the game in a way that makes sense.
class Room():
def __init__(self,north,south,east,west):
self.north=north
self.south=south
self.east=east
self.west=west
kitchen = Rooms(None, 'hallway', 'library', None)
#initialization of other rooms are left as excercise to the reader
current_room = kitchen
while True:
print "You are in the %s" % current_room
move=raw_input("Where do you want to go")
if move=='q':
print "bye"
if move=='e':
current_room = current_room.east
#much logic is left as an exercise to the reader
You can use a dictionary comprised of a key which represents a room and a value of a list of place you can go.
For example:
# these match up to indexes for the list in the dict directions
NORTH = 0
EAST = 1
WEST = 2
SOUTH = 3
directions = {
"living room": ["dining room", None, None, "bedroom"]
}
# the current room, represented by the keys you create
current_room = "living room"
# an example imput
direction = "n"
if direction == "n":
possible_room = directions[current_room][NORTH]
if possible_room:
current_room = possible_room
Some very sloppy example code but it gets my point across. The general idea of coming up with a program is looking into how you can store your data such as using dictionaries in Python.
Python has plenty of data types that are worth looking into.
I will leave you to fix the code now since you have gained a new perspective into solving the problem.
Your indentation is messed up.
Put first = input("You are in the kitchen. There are doors to the south (s) and east (e). ") before the while loop.

Categories