How do you make a conditional statement In Python? - python-2.7

I'm confused on how to make conditional statements. I just can't seem to figure it out. In the example bellow I want the shoot input to only work if the user chose in this case the gun earlier in the game. Same with the knife and so on.
def chap4():
print "You feel around the room.\n"
time.sleep(3)
print "You find a small chest...\n"
time.sleep(3)
print "You open the chest...\n"
time.sleep(2)
print "[pickaxe, shovel, lighter, axe, 9mm(0), knife]\n"
while (True):
chest = raw_input("What will you take?: ")
if chest == "pickaxe":
print "You take the pickaxe"
break
elif chest == "shovel":
print "You take the shovel"
break
elif chest == "lighter":
print "You take the axe"
break
elif chest == "9mm":
print "You take the empty 9mm pistol"
break
elif chest == "knife":
print "You take the knife"
break
elif chest == "axe":
print "You take the axe"
break
else:
print "Invalid choice. Try again..."
chap4()
def zombie():
print "A zombie is seem in the distance"
while (True):
attack = raw_input("> ")
if attack == "shoot":
print "Zombie hp 50/100"
elif attack == "stab":
print "Zombie hp 70/100"
else:
print "Invalid input. Try again..."
So as you can tell by the code in having trouble... I originally thought maybe I'd make another if statement within the if statement but I'm not sure. Please help if you can... Thanks!

I recommend putting a conditional if
def chap4():
....
return(chest)
def zombie()
weapon = chap4()
if weapon == "9mm":
if attack =="shoot":
print(...)
elif attack =="stab":
...
And so on.
So specify the weapon in the conditional in zombie(). Also, zombie() will have to know the chest variable, soreturn(chest) at the end of chap4() function, and call chap4() within zombie()
EDIT: when calling chap4() in zombie(), it needs to called a variable, in this case, weapon

The conditional statements are fine, so far as they go. The problem is that you aren't saving the outcomes anywhere. Do something like
if chest == "pickaxe":
print "You take the pickaxe"
weapon = "pickaxe"
elif chest == "shovel":
print "You take the shovel"
weapon = "shovel"
etc.
When the user choose an attack mode, you can check that he has the appropriate weapon:
if attack == "shoot":
if weapon == "9mm":
print "Zombie hp 50/100"
else:
print "you don't have a pistol"
Here too, printing is probably not enough. You'll want to keep track of what's happened, I would think

You can store what chest cointain like this:
chestContainer= {"pickaxe": "pickaxe", "shovel": "shovel", "lighter": "lighter", "9mm(0)": "9mm(0)", "knife": "knife", }
And then you can print the option like this:
print chestContainer[chest]
And you can evaluate if the input is valid like this:
if chestContainer[chest] == None:
print "Invalid choice. Try again..."
Edit:
As user908293 said you have to save what weapon you chose.
weapon = chestCointainer[chest]

Related

How to make Python continue with a game after while loop or if statement

I’m trying to get my game to continue to the games after a user inputs “yes” or “no”. Here is the code:
user_name =input ("What is your name? ")
user = user_name
print(f"Welcome {user}!")
user_ans = ''
while True:
user_ans = input("Are you ready to play ROCK, PAPER, SCISSORS? (yes or no?) ")
if user_ans.lower() == 'yes':
print("Alright, Let's play!")
continue
elif user_ans.lower() == 'no':
print('Not ready to play? Okay, see ya later!')
exit()
else:
print('Type yes or no')
if user_ans.lower() == 'yes':
def get_choices(): #get_choices is a function
player_choice = input("Enter a choice (rock, paper, scissors): ")
options = ['rock', 'paper', 'scissors']
computer_choice = random.choice(options)
choices = {"player":player_choice, "computer":computer_choice}
return choices
def check_win(player, computer ):
print(f"You chose {player}, computer chose {computer}.")
if player == computer:
return "It's a tie!"
#if player chooses "ROCK"
elif player == "rock":
if computer == "scissors":
return "Rock smashes scissors! You win!"
The main part I need help with is yes or no part. The loop works except for the fact that it won’t continue to the game after that.
I initially tried using an if/else statement but I’d didn’t work well. I’ve only made progress with the while loop.
You can do that way:
import random
user_name = input("What is your name? ")
user = user_name
print(f"Welcome {user}!")
user_ans = ''
while True:
user_ans = input("Are you ready to play ROCK, PAPER, SCISSORS? (yes or no?) ")
if user_ans.lower() == 'yes':
print("Alright, Let's play!")
break
elif user_ans.lower() == 'no':
print('Not ready to play? Okay, see ya later!')
exit()
else:
print('Type yes or no')
def get_choices():
player_choice = input("Enter a choice (rock, paper, scissors): ")
options = ['rock', 'paper', 'scissors']
computer_choice = random.choice(options)
choices = {"player": player_choice, "computer": computer_choice}
return choices
def check_win(player, computer):
print(f"You chose {player}, computer chose {computer}.")
if player == computer:
return "It's a tie!"
elif player == "rock":
if computer == "scissors":
return "Rock smashes scissors! You win!"
else:
return "Paper covers rock! You lose!"
elif player == "paper":
if computer == "rock":
return "Paper covers rock! You win!"
else:
return "Scissors cut paper! You lose!"
elif player == "scissors":
if computer == "paper":
return "Scissors cut paper! You win!"
else:
return "Rock smashes scissors! You lose!"
else:
return "Invalid input. Please try again."
while True:
choices = get_choices()
result = check_win(choices["player"], choices["computer"])
print(result)
play_again = input("Do you want to play again? (yes or no) ")
if play_again.lower() == "no":
print("Thanks for playing!")
break

Error in Tic tac toe Program (Python)

The code shown below is that of a Tic tac toe game in which there are two players (Player1 and Player2 are humans). I have an issue in the if else statements in the "# Player 1 Plays now" and "# Player 2 Plays now" sections of the code. To be precise, the computer always thinks that every box is already filled with some value other than 1,2,3,4,5,6,7,8,9 and it keeps displaying the message "That cell is already marked. Please try another cell" defined in the nested else statement.
Can somebody enlighten me how to fix this problem ?
board = [0,1,2,3,4,5,6,7,8,9]
print type(board[1])
def board_invoke():
print "| ",board[1], " | ", board[2], " | ", board[3], " | ", "\n", "-------------------", "\n", "| ", board[4], " | ",board[5], " | ", board[6], " | ", "\n", "-------------------", "\n", "| ", board[7], " | ",board[8], " | ", board[9], " | "
def game_start():
Player1= raw_input("Select Player 1 between X or O : ")
if Player1 not in ('X','x','O','o'):
print "That is not an expected player"
game_start()
else:
print "\nSince you have selected Player 1 as %s" %Player1
print "\nThe Player 2 is assigned :",
if Player1 in ('X','x'):
Player2 = ("O")
else:
Player2 = ("X")
print Player2
print "\nThe game Starts now....\n"
board_invoke()
while (1 or 2 or 3 or 4 or 5 or 6 or 7 or 8 or 9) in board:
# Winning Condition
if board[1]==board[2]==board[3]==Player1:
print Player1," wins"
break
elif board[4]==board[5]==board[6]==Player1:
print Player1, " wins"
break
elif board[7]==board[8]==board[9]==Player1:
print Player1, " wins"
break
elif board[1]==board[2]==board[3]==Player2:
print Player2, " wins"
break
elif board[4]==board[5]==board[6]==Player2:
print Player2, " wins"
break
elif board[7]==board[8]==board[9]==Player2:
print Player2, " wins"
break
elif board[1]==board[5]==board[9]==Player1:
print Player1, " wins"
break
elif board[3]==board[5]==board[7]==Player1:
print Player1, " wins"
break
elif board[1]==board[5]==board[9]==Player2:
print Player2, " wins"
break
elif board[3]==board[5]==board[7]==Player2:
print Player2, " wins"
break
elif board[1]==board[4]==board[7]==Player1:
print Player1, " wins"
break
elif board[2]==board[5]==board[8]==Player1:
print Player1, " wins"
break
elif board[3]==board[6]==board[9]==Player1:
print Player1, " wins"
break
elif board[1]==board[4]==board[7]==Player2:
print Player2, " wins"
break
elif board[2]==board[5]==board[8]==Player2:
print Player2, " wins"
break
elif board[3]==board[6]==board[9]==Player2:
print Player2, " wins"
break
# Player 1 Plays now
Cell_no = raw_input("Player 1 : Please select a number you want to mark....")
Cell_no = int(Cell_no)
if Cell_no not in board:
print "Please enter a cell number within the scope of available cells"
else:
if 'X' or 'x' or 'O' or 'o' in board[Cell_no]:
print "That cell is already marked. Please try another cell"
continue
else:
board[Cell_no] = Player1
board_invoke()
# Player 2 Plays now
Cell_no = raw_input("Player 2 : Please select a number you want to mark....")
Cell_no = int(Cell_no)
if Cell_no not in board:
print "Please enter a cell number within the scope of available cells"
else:
if 'X' or 'x' or 'O' or 'o' in board[Cell_no]:
print "That cell is already marked. Please try another cell"
continue
else:
board[Cell_no] = Player2
board_invoke()
print "Do you want to play again ?"
user_decision = raw_input("Please type Yes or No : ")
if user_decision == ('YES' or 'Yes' or 'yes'):
game_start()
else:
print "Ok. I take it that we will wrap up !"
print "See you again !"
game_start()
Your if statement is not completely correct.
You are evaluating:
else:
if 'X' or 'x' or 'O' or 'o' in board[Cell_no]:
print "That cell is already marked. Please try another cell"
which is always true. The or keywords combines each comparison logically. The first compare statement would then simply be 'X', which is not null or 0 and therefor always true. As the first statement is true, the whole if-statement is true.
I see this quite often on people starting to learn programming. If-statements can't be written exactly like human sentences. You have to compare every single character to your variable.
Here is a simple (not python specific and quite ugly) solution to your problem:
else:
if 'X' == board[Cell_no] or 'x' == board[Cell_no] or 'O' == board[Cell_no] or 'o' == board[Cell_no]:
print "That cell is already marked. Please try another cell"
An even better approach though would be to turn that check around and compare it with a list:
else:
if board[Cell_no] in ['X','x', 'O', 'o']:
print "That cell is already marked. Please try another cell"

Python 2.7, trouble printing docstrings (doc comments) "function has no attribute _doc_" error

I'm working on LPTHW ex 41, where we modify a bunch of print statements to use a docstring style and then use a runner to print them.
The code originally was like this:
Function()
Print "Several lines of printed material"
Revised, the functions begin:
Function()
"""doc comment"""
A runner connects all the functions ("rooms") like so, with the goal being to print doc comments instead of print commands.
ROOMS = {
'death': death,
'central_corridor': central_corridor,
'laser_weapon_armory': laser_weapon_armory,
'the_bridge': the_bridge,
'escape_pod': escape_pod
}
def runner(map, start):
next = start
while True:
room = map[next]
print "\n----------------"
print room._doc_
next = room()
runner(ROOMS, 'central_corridor')
But I keep getting the error
'function" object has no attribute '_doc_'
Example room:
def central_corridor():
"""You wanna blow thing up.
You running toward place for to get bomb.
Emeny approach!
1 = shoot at enemy
2 = avoid emenemeny
3 = use bad pick up line on emenie
4 = hint"""
#print(_doc_)
action = int(raw_input("> "))
if action == 1:
print "He shoot you first."
return 'death'
elif action == 2:
print "No he still gots you."
return 'death'
elif action == 3:
print "Oh yeah sexy boy."
print "You get past laughing enemy."
return 'laser_weapon_armory'
elif action == 4:
print "Emeny like good joke."
return 'central_corridor'
else:
print "You enter wrong input"
return 'central_corridor'
Can anyone tell me how to get the doc comments to print? Thanks!
Noticed doc needs two underscores. Fixed
_doc_
__doc__

calling function twice or more and getting TypeError 'int' is not callable

I need some help with one my functions, The first time you call it, it works perfectly, however on subsequent runs through an if/else statement it gives out TypeError 'int' is not callable. in order to see this, when given the option use Hunt, then on the second run use Hunt again. I am using Python 2.7, code is: -
from sys import exit
import random
equipment = ['Bolter', 'Bolt Pistol', 'Combat Knife']
print "Your ship has crash landed on an unknown planetoid, what do you do?
Explore, Overwatch, Hunt or Nothing"
def enemy_attack():
enemy_attack = random.randrange(0, 7)
if enemy_attack <= 5:
print "Enemy Misses"
print "Your Turn"
you_attack()
elif enemy_attack == 6:
print "Enemy kills you"
else:
print "Enemy ran away"
def you_attack():
you_attack = random.randrange(0, 7)
if you_attack <= 2:
print "You missed"
print "Thier Turn"
enemy_attack()
else:
print "You killed the enemy"
print "What do you do? Explore, Overwatch, Hunt, or Nothing"
do = raw_input("> ")
if "Explore" in do:
print "You find a sealed container"
print "Your Equipment is", equipment
print "Do you want to open the container? Yes or No"
container = raw_input("> ")
if "Yes" in container:
open_container()
else:
print "You left it alone"
elif "Overwatch" in do:
print "Orks Attack!!!"
enemy_attack()
elif "Hunt" in do:
print "You attack the Orks!"
you_attack()
else:
print "The planetoid swallows you whole, and adds your mass to it!!"
exit(0)
def open_container():
open_container = random.randrange(0,5)
if open_container == 0:
print "You have found a Plasma Gun!"
equipment.append('Plasma Gun')
print "Your equipment is now", equipment
elif open_container == 1:
print "You have found a Chainsword!"
equipment.append('Chainsword')
print "Your equipment is now", equipment
elif open_container == 2:
print "You have found a Power Sword"
equipment.append('Power Sword')
print "Your equipment is now", equipment
else:
print "There is nothing here for you!!"
do = raw_input("> ")
if "Explore" in do:
print "You find a sealed container"
print "Your Equipment is", equipment
print "Do you want to open the container? Yes or No"
container = raw_input("> ")
if "Yes" in container:
open_container()
else:
print "You left it alone"
elif "Overwatch" in do:
print "Orks Attack!!!"
enemy_attack()
elif "Hunt" in do:
print "You attack the Orks"
you_attack()
else:
print "The planetoid swallows you whole, and adds your mass to it!!"
exit(0)

Python Breaking a While Loop with user input

new to Python. Within a while loop, I'm asking the user for an input which is a key for a dict. and then print the value of that key. This process should continue until the input does not match any key in the dict. I'm using an if statement to see if the key is in the dict. If not I'like the while loop to break. So far I can't get it to break.
Thank you all
Animal_list = {
'lion': 'carnivora', 'bat': 'mammal', 'anaconda': 'reptile',
'salmon': 'fish', 'whale': 'cetaceans', 'spider': 'arachnida',
'grasshopper': 'insect', 'aligator': 'reptile', 'rat': 'rodents',
'bear': 'mammal', 'frog': 'amphibian', 'turtles': 'testudines'
}
while True:
choice = raw_input("> ")
if choice == choice:
print "%s is a %s" % (choice, Animal_list[choice])
elif choice != choice:
break
choice == choice will always be true. What you really want to do is check if choice is in the Animal_list. Try changing to this:
Animal_list = {
'lion': 'carnivora', 'bat': 'mammal', 'anaconda': 'reptile',
'salmon': 'fish', 'whale': 'cetaceans', 'spider': 'arachnida',
'grasshopper': 'insect', 'aligator': 'reptile', 'rat': 'rodents',
'bear': 'mammal', 'frog': 'amphibian', 'turtles': 'testudines'
}
while True:
choice = raw_input("> ")
if choice in Animal_list:
print "%s is a %s" % (choice, Animal_list[choice])
else:
break