Everything is leading to an else instead of it reading the input - python

The code:
import math
import time
import os
from random import *
def intro():
print("Welcome to battle. This is a game where you battle monsters.")
print("You will try to get the highest score you can.")
print("You start with 100HP. You will need to survive.")
print("You get a max revive every 10 battles.")
print("PS: This game is still in early alpha.")
print("Bugs are expected.")
game()
def game():
health = 100
revive = 0
print("You are greeted by a monster...")
print("1 = Fight")
print("2 = Take a chance at running")
choice = input("")
if choice == 1:
damage = randint(1,100)
health = health - damage
print("You killed the monster!")
print("But you took "+damage+" damage")
print("Your new health is: "+health)
if choice == 2:
print("You tried to run but failed.")
damage = randint(70,100)
health = health - damage
print("Your new health is: "+health)
else:
print("Wrong choice. You died.")
intro()
intro()
The problem: If you use 1 for choice it leads to else. Same with 2. Thanks to anyone that helps! PS: I am using Python 3. I don't know if that's important, I just need to fill out these lines.

Convert your input to int.
Ex:
choice = int(input())
and then replace
if choice == 2:
with
elif choice == 2:
Edit as per comments
def game():
health = 100
revive = 0
print("You are greeted by a monster...")
print("1 = Fight")
print("2 = Take a chance at running")
choice = int(input(""))
if choice == 1:
damage = randint(1,100)
health = health - damage
print("You killed the monster!")
print("But you took "+str(damage)+" damage") #-->Convert int to str before concatenation
print("Your new health is: "+str(health)) #-->Convert int to str before concatenation
elif choice == 2:
print("You tried to run but failed.")
damage = randint(70,100)
health = health - damage
print("Your new health is: "+str(health)) #-->Convert int to str before concatenation
else:
print("Wrong choice. You died.")

You firstly need to cast your input to an int by using int(input(""))
Then:
You need to use elif choice == 2: instead of if choice == 2:.

Related

Function and keyword argument

Why is my code not working? I am following UDEMY's 100 days of code and it is essentially the same as the instructor but I wanted to have keyword named arguments. First of all it's not printing the correct turn_left after each turn and it's not stopping the game.
from random import randint
EASY_LEVEL_TURNS = 10
HARD_LEVEL_TURNS = 5
def check_answer(user_guess, correct_answer, tracking_turns):
"""
Checks answer with guess.
"""
if user_guess > correct_answer:
print("Too high")
return tracking_turns - 1
elif user_guess < correct_answer:
print("Too low")
return tracking_turns - 1
elif user_guess == correct_answer:
print(f"Right the answer is {correct_answer}")
def set_difficulty(game_level):
"""
Sets game difficulty
"""
if game_level == "easy":
return EASY_LEVEL_TURNS
elif game_level == "hard":
return HARD_LEVEL_TURNS
def game():
"""
Setting up the game
"""
guess = 0
answer = randint(1, 100)
print("Welcome to the number guessing game!")
print("I am thinking of a number between 1 to 100")
level = input("How difficult would you like the game to be? Easy or Hard ").lower()
turn_left = set_difficulty(game_level=level)
while guess != answer:
print(f"You have {turn_left} attempts to guess the answer.")
guess = int(input("What is your guess? "))
answer_checked = check_answer(user_guess=guess, correct_answer=answer,
tracking_turns=turn_left)
if turn_left == 0:
print("You have ran out of terms")
return
game()
You can modify your game function like this, mainly by updating the turn_left value and setting the end-of-function condition
def game():
"""
Setting up the game
"""
guess = 0
answer = randint(1, 100)
print("Welcome to the number guessing game!")
print("I am thinking of a number between 1 to 100")
level = input("How difficult would you like the game to be? Easy or Hard ").lower()
turn_left = set_difficulty(game_level=level)
while guess != answer:
print(f"You have {turn_left} attempts to guess the answer.")
guess = int(input("What is your guess? "))
turn_left = check_answer(user_guess=guess, correct_answer=answer,
tracking_turns=turn_left)
if turn_left == 0:
print("You have ran out of terms")
return
elif not turn_left:
return

I would like to add Debt to my blackjack game

this is a simple blackjack game. I want to add debt and user will have bank account as;
bank=1000
Program will ask to user: "How much do you debt? $" and his money in the bank will increase or decrease then if user has 0 dollar in the bank game will over. The issue is whenever I input "y" for cont, the bank becomes 1000 again.I declared debt in the main function and the condition was below the "while cmp_sc!=0 and cmp_sc<17" when I tried to do that.
import os
import random
cards=[11,2,3,4,5,6,7,8,9,10,10,10,10]
def rand_card(card):
r_card=random.choice(card)
return r_card
def result_card(card):
sum_card=sum(card)
if sum_card == 21 and len(card)==2:
return 0
if 11 in card and sum(card)==21:
card.remove(11)
card.append(1)
return sum(card)
def comparing(result1,result2):
if result1>result2 and result1<=21:
return "You win"
elif result1==result2:
return "Draw"
elif result2>result1 and result2<=21:
return "You lose"
elif result1>21 and result2>21:
return "You are flying, you lose"
elif result1==0:
return "Blackjaack, You win!"
elif result2==0:
return "Computer Blackjaack, You lose!"
elif result1 > 21:
return "You went over. You lose"
elif result2 > 21:
return "Opponent went over. You win"
def main():
user=[]
computer=[]
flag=False
for i in range(2):
user.append(rand_card(cards))
computer.append(rand_card(cards))
while not flag:
usr_sc = result_card(user)
cmp_sc = result_card(computer)
print(f" Your cards: {user}, current score: {usr_sc}")
print(f" Computer's first card: {computer[0]}")
if usr_sc==0 or cmp_sc==0 or usr_sc>21:
flag=True
else:
cont = input("Type 'y' to get another card, type 'n' to pass: ").lower()
if cont=='y':
user.append(rand_card(cards))
else:
flag=True
while cmp_sc!=0 and cmp_sc<17:
computer.append(rand_card(cards))
cmp_sc=result_card(computer)
print(f" Your final hand: {user}, final score: {usr_sc}")
print(f" Computer's final hand: {computer}, final score: {cmp_sc}")
print(comparing(usr_sc, cmp_sc))
while input("Do you want to play a game of Blackjack? Type 'y' or 'n': ") == "y":
clearConsole = lambda: os.system('cls' if os.name in ('nt', 'dos') else 'clear')
clearConsole()
main()
The typical use of main() would be as a way to start your program, not as something that would be called each round. So, let's change that up a bit and call your current main() something like play_game(). Then we can reimplement main() more like:
def main():
balance = 1000
while input(f"You have {balance}. Do you want to play a game of Blackjack? Type 'y' or 'n': ") == "y":
clearConsole()
bet = 100
balance -= bet
balance += play_game(bet)
print(f"Final Balance: {balance}")
if __name__ == "__main__":
main()
So now we have a balance and each round we have a bet and what we bet will initially decrease our balance but with luck it will increase as a result of play_game()
The changes we will make to play_game(bet) will be to accept a "bet amount" and then return winnings based on how our hand compares to the computers hand. This will require a small change to comparing() to return not only a message but an indication of a win/draw/loss so we can figure out what to give back.
At the end of play_game(bet) rather than:
print(comparing(usr_sc, cmp_sc))
We will:
win_multiplier, message = comparing(usr_sc, cmp_sc)
print(message)
return win_multiplier * bet
Finally, the return values of comparing() need to include the absolute indication of a win/draw/loss that we will use as a multiplier against bet.
def comparing(result1,result2):
if result1>result2 and result1<=21:
return (2, "You win")
elif result1==result2:
return (1, "Draw")
elif result2>result1 and result2<=21:
return (0, "You lose")
elif result1>21 and result2>21:
return (0, "You are flying, you lose")
elif result1==0:
return (2, "Blackjaack, You win!")
elif result2==0:
return (0, "Computer Blackjaack, You lose!")
elif result1 > 21:
return (0, "You went over. You lose")
elif result2 > 21:
return (2, "Opponent went over. You win")
If you really want to have it persisted, you need to store it somewhere outside the process memory e.g in some file on disk. The easiest way could be with something like that:
try:
with open("bank.txt", "r") as f:
# assing bank to content of your file
bank = int(f.read())
except FileNotFoundError:
# if file not exist, it's first game of user, we set bank to 1000 then
bank = 1000
print(bank)
bet = int(input("What is your bet?"))
# at the end of program
bank = bank + bet if user_won else bank - bet
with open("bank.txt", "w+") as f:
f.write(str(bank))
Now the actual bank of player will be stored in bank.txt file. You can set its content manually before run to modify user bank

Text-based game stats

I'm working on a mini-project I'm doing for fun to practice python skills and I am stuck on a problem I can't seem to figure out. I have a function that gives me the default stats for every class in the game and I want it to change depending on what class/weapon I choose in the beginning. I am still trying to learn functions so any input will be valuable. So gameStat() is the default stats while gameStat() is the changed one.
import time
import random
inventory = []
def intro():
print("Hello for playing my game. It is a text based game that I am working on. \n")
print("I hope you enjoy playing it \n")
def chooseClass():
print("Please choose a class you would like to play as. Each class has a different background story to them")
print("-----------------------------------------------------------")
print("Please use the number given below to select them")
print("1: Priest\n" "2: Warrior\n" "3: Thief\n" "4: Ninja\n" "5: Pirate\n")
def classChosen(starterClass):
if starterClass == 1:
print("You have chosen Priest")
return "Priest"
elif starterClass == 2:
print("You have chosen Warrior")
return "Warrior"
elif starterClass ==3:
print("You have chosen Thief")
return "Thief"
elif starterClass ==4:
print("You have chosen Ninja")
return "Ninja"
elif starterClass ==5:
print("You have chosen Pirate")
return "Pirate"
else:
return None
def gameStat():
health = 100
mana = 100
strength = 5
magic = 5
exp = 0
baseStats(health,mana,strength,magic,exp)
def ChosenPriest(var):
if var == "Priest":
selectAns=""
selectAns=input("Would you like to know the backstory? \n:Please type 1 :Yes or 2 :No\n:")
if selectAns == 1:
print("INC")
#print("Since a child, you have been serving under the Church of Agathor.\n")
#print("You didn't have much of a choice because you had nowhere else to go.\n")
#print("You don't know who your parents are and the only thing the church would tell you that you suddenly appeared in front of the chruch with a gold cross.\n")
#print("You still have that cross til this day.\n")
#print("At the age of 16, everyone who serves for the lord will get their own holy weapon.\n")
#print("The weapon is used to fight off The Shadows. The Shadows are creatures created by the Shadow Lord, Gilmah.\n")
#print("Since the very beginning, Gilmah would rummaged through the land destorying and pillaging everything he sees.\n")
#print("One priest was able to seal him for thousands of years but he is soon to be awaken and he'll become stronger than ever.\n")
else:
print("Alright!")
def Weapons(weapon):
if weapon == 1:
print("You have chosen Magical Book!")
inventory.append("Magical Book")
return "Magical Book"
elif weapon == 2:
print("You have choosen a staff")
inventory.append("Staff")
return "Staff"
def baseStats(character,weapon):
if character == "Priest":
if weapon == "Magical Book":
mana=100
mana = mana + 50
return mana
elif weapon == "Staff":
magic=5
magic = magic + 5
return magic
#intro()
chooseClass()
userClass=None
while True:
try:
x=input("What class would you like to play?\n:")
if x>5 or x<1:
continue
else:
userClass=classChosen(x)
break
except NameError:
continue
character=ChosenPriest(userClass)
weapon=Weapons(input("What kind of holy weapon would you like to take? \n 1: Magical Book \n 2: Staff \n Use 1 or 2 to select your weapon! :"))
print(baseStats(character,weapon))
Thank you so much.
When you take any input it will be in string format to compare it with an integer you need to convert it to integer using int() function
I modified the code and it returns the value of "mana" or "magic" correctly
import time
import random
inventory = []
def intro():
print("Hello for playing my game. It is a text based game that I am working on. \n")
print("I hope you enjoy playing it \n")
def chooseClass():
print("Please choose a class you would like to play as. Each class has a different background story to them")
print("-----------------------------------------------------------")
print("Please use the number given below to select them")
print("1: Priest\n" "2: Warrior\n" "3: Thief\n" "4: Ninja\n" "5: Pirate\n")
def classChosen(starterClass):
if starterClass == 1:
print("You have chosen Priest")
return "Priest"
elif starterClass == 2:
print("You have chosen Warrior")
return "Warrior"
elif starterClass ==3:
print("You have chosen Thief")
return "Thief"
elif starterClass ==4:
print("You have chosen Ninja")
return "Ninja"
elif starterClass ==5:
print("You have chosen Pirate")
return "Pirate"
else:
return None
def gameStat():
health = 100
mana = 100
strength = 5
magic = 5
exp = 0
baseStats(health,mana,strength,magic,exp)
def ChosenPriest(var):
if var == "Priest":
selectAns=""
selectAns=int(input("Would you like to know the backstory? \n:Please type 1 :Yes or 2 :No\n:"))
if selectAns == 1:
print("INC")
#print("Since a child, you have been serving under the Church of Agathor.\n")
#print("You didn't have much of a choice because you had nowhere else to go.\n")
#print("You don't know who your parents are and the only thing the church would tell you that you suddenly appeared in front of the chruch with a gold cross.\n")
#print("You still have that cross til this day.\n")
#print("At the age of 16, everyone who serves for the lord will get their own holy weapon.\n")
#print("The weapon is used to fight off The Shadows. The Shadows are creatures created by the Shadow Lord, Gilmah.\n")
#print("Since the very beginning, Gilmah would rummaged through the land destorying and pillaging everything he sees.\n")
#print("One priest was able to seal him for thousands of years but he is soon to be awaken and he'll become stronger than ever.\n")
else:
print("Alright!")
def Weapons(weapon):
if weapon == 1:
print("You have chosen Magical Book!")
inventory.append("Magical Book")
return "Magical Book"
elif weapon == 2:
print("You have choosen a staff")
inventory.append("Staff")
return "Staff"
def baseStats(character,weapon):
if character == "Priest":
if weapon == "Magical Book":
mana=100
mana = mana + 50
return mana
elif weapon == "Staff":
magic=5
magic = magic + 5
return magic
#intro()
chooseClass()
userClass=None
while True:
try:
x=int(input("What class would you like to play?\n:"))
if x>5 or x<1:
continue
else:
userClass=classChosen(x)
break
except NameError:
continue
character=ChosenPriest(userClass)
weapon=Weapons(int(input("What kind of holy weapon would you like to take? \n 1: Magical Book \n 2: Staff \n Use 1 or 2 to select your weapon! :")))
print(baseStats(userClass,weapon))
In the gameState() function the baseStats takes 5 argument but when you defined baseStats it only takes two arguments character and weapon which is confusing.

UnboundLocalError: local variable 'ehp' referenced before assignment

I've been writing a shitty text-based game for the first time using python, and I've encountered a problem whilst making a function for a battle. It would be called upon each time you encounter an enemy, and the variables will be defined before each fight.
The problem I'm having is that my variable, 'ehp', is being referenced before the assignment of the variable. (Stands for Enemy Health Points). My code is listed below and I would like some help as to what to change to my code to prevent the error code that I'm getting with my program.
import random
hp = int(20)
ehp = int(10)
def fight():
print("You have encountered",(enemy))
if speed >= espeed:
first = "c"
for x in range(100):
if ehp <= 0:
print("You have won!")
break
elif hp <= 0:
print("You have died!")
break
else:
print("1: Light Attack")
print("2: Heavy Attack")
print("3: Dodge")
attack = input("1/2/3: ")
if attack == "1":
print("You have used, Light Attack!")
lightdam = (random.randint(0,damage/2))
print("You have inflicted,",edam,"to",enemy)
ehp = ehp - (random.randint(0,damage/2))
print("Enemy Health:",ehp)
print(character,"Health:",hp)
print(enemy,"Has used attack!")
eattack = (random.randint(0,edam/2))
print(enemy,"Has inflicted",eattack,"damage!")
hp = hp - eattack
print("Enemy Health:",ehp)
print(character,"Health:",hp)
elif attack == "2":
print("You have used, Heavy Attack!")
heavydam = (random.randint(0,damage))
print("You have inflicted,",heavydam,"to",enemy)
ehp = ehp - (random.randint(0,damage))
print("Enemy Health:",ehp)
print(character,"Health:",hp)
print(enemy,"Has used attack!")
eattack = (random.randint(0,edam))
print(enemy,"Has inflicted",eattack,"damage!")
hp = hp - eattack
print("Enemy Health:",ehp)
print(character,"Health:",hp)
print("Welcome to the tales of Iryophia, please enter your characters name.")
character = input("Character name: ")
print("Garnier the Honorable:")
print("Welcome to the city of Iryophia, do you remember how you got here?")
y0 = input("Y/N: ")
for x in range(6):
if y0 == "N":
print("Garnier the Honorable:")
print("Well",character,", all I can remember is a certain man entering a neighbouring town, and well, I'm not sure how to put this, but, you were killed.")
print("I understand how crazy this may sound but you were brought back to life. You would have lost all of your memory, but, you are alive!")
print("Do you remember the name of the man who killed you?")
nemesis = input("Nemesis: ")
print("Garnier the Honorable:")
print("Ah yes, I remember now,",nemesis,"was his name.")
break
if y0 == "Y":
print("Garnier the Honorable:")
print("Okay, well the man that attacked you, what was his name?")
nemesis = input("Nemesis: ")
print("Garnier the Honorable:")
print("Ah yes, I remember now,",nemesis,"was his name.")
break
print("Come back with me to my home.")
print("")
print("Garnier the Honorable:")
print("I have a bow, an axe, or a sword for you. Which one do you pick?")
weapon = input("Bow/Axe/Sword: ")
for x in range(6):
if weapon == "Bow":
damage = int(3)
speed = int(5)
break
if weapon == "Axe":
damage = int(7)
speed = int(3)
break
if weapon == "Sword":
damage = int(5)
speed = (4)
break
print("You have collected:",weapon+"!")
print("Damage:",damage)
print("Speed:",(speed))
print("Garnier the Honorable:")
print("Would you like to have a practice fight?")
fight0 = input("Y/N: ")
for x in range(6):
if fight0 == "Y":
ehp = int(10)
enemy = "Garnier the Honorable"
espeed = int(3)
edam = int(4)
fight()
break
Examine these two code lines in fight() (at least these two, though there may be others):
ehp = ehp - (random.randint(0,damage/2))
hp = hp - eattack
For variables not explicitly marked as global, Python makes some assumptions:
if you only use the variable, it will follow the scope up through different levels until it finds a matching name; and
if you set or change it anywhere in a function, it's considered a local variable everywhere in the function.
Hence a simple fix would be to explicitly mark it global in the function:
def fight():
global ehp
global hp
print("You have encountered",(enemy))
:
and so on
A better fix would probably involve not using globals at all :-)
You should probably also review your hit-point processing, which contains such things as:
heavydam = (random.randint(0,damage))
print("You have inflicted,",heavydam,"to",enemy)
ehp = ehp - (random.randint(0,damage))
Telling the player they've inflicted some amount of damage then subtracting a totally different number of hit points is likely to have players scratching their heads trying to figure out how things work :-)

Text-based adventure in Python 3

I'm working on a text-based RPG, but I've found numerous problems, like:
being unable to go anywhere after entering the shop;
I cannot access the "tavern" for some reason; and
the computer just says "buy is not defined in crossbow".
Code:
gold = int(100)
inventory = ["sword", "armor", "potion"]
print("Welcome hero")
name = input("What is your name: ")
print("Hello", name,)
# role playing program
#
# spend 30 points on strenght, health, wisdom, dexterity
# player can spend and take points from any attribute
classic = {"Warrior",
"Archer",
"Mage",
"Healer"}
print("Choose your race from", classic,)
classicChoice = input("What class do you choose: ")
print("You are now a", classicChoice,)
# library contains attribute and points
attributes = {"strenght": int("0"),
"health": "0",
"wisdom": "0",
"dexterity": "0"}
pool = int(30)
choice = None
print("The Making of a Hero !!!")
print(attributes)
print("\nYou have", pool, "points to spend.")
while choice != "0":
# list of choices
print(
"""
Options:
0 - End
1 - Add points to an attribute
2 - remove points from an attribute
3 - Show attributes
"""
)
choice = input("Choose option: ")
if choice == "0":
print("\nYour hero stats are:")
print(attributes)
elif choice == "1":
print("\nADD POINTS TO AN ATTRIBUTE")
print("You have", pool, "points to spend.")
print(
"""
Choose an attribute:
strenght
health
wisdom
dexterity
"""
)
at_choice = input("Your choice: ")
if at_choice.lower() in attributes:
points = int(input("How many points do you want to assign: "))
if points <= pool:
pool -= points
result = int(attributes[at_choice]) + points
attributes[at_choice] = result
print("\nPoints have been added.")
else:
print("\nYou do not have that many points to spend")
else:
print("\nThat attribute does not exist.")
elif choice == "2":
print("\nREMOVE POINTS FROM AN ATTRIBUTE")
print("You have", pool, "points to spend.")
print(
"""
Choose an attribute:
strenght
health
wisdom
dexterity
"""
)
at_choice = input("Your choice: ")
if at_choice.lower() in attributes:
points = int(input("How many points do you want to remove: "))
if points <= int(attributes[at_choice]):
pool += points
result = int(attributes[at_choice]) - points
attributes[at_choice] = result
print("\nPoints have been removed.")
else:
print("\nThere are not that many points in that attribute")
else:
print("\nThat attribute does not exist.")
elif choice == "3":
print("\n", attributes)
print("Pool: ", pool)
else:
print(choice, "is not a valid option.")
print("Here is your inventory: ", inventory)
print("What do you wish to do?")
print("please input shop, tavern, forest.")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
crossbow = int(50)
spell = int(35)
potion = int(35)
if choice == "shop":
print("Welcome to the shop!")
print("You have", gold,"gold")
buy = input("What would you like to buy? A crossbow, a spell or a potion: ")
if buy == "crossbow":
print("this costs 50 gold")
answer = input("Do you want it: ")
if answer == "yes":
print("Thank you for coming!")
inventory.append("crossbow")
gold = gold - crossbow
print("Your inventory is now:")
print(inventory)
print("Your gold store now is: ", gold)
if answer == "no":
print("Thank you for coming!")
if buy == "spell":
print("this costs 35 gold")
answear2 = input("Do you want it: ")
if answear2 == "yes":
print("Thank you for coming!")
inventory.append("spell")
gold = gold - spell
print("Your inventory is now:")
print(inventory)
if answear2 == "no":
print("Thank you for coming!")
if buy == "potion":
print("this costs 35 gold")
answear3 = input("Do you want it: ")
if answear3 == "yes":
print("Thank you for coming!")
inventory.append("spell")
gold = gold - potion
print("Your inventory is now:")
print(inventory)
if answear3 == "no":
print("Thank you for coming!")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
while choice != "shop" or "tavern" or "forest":
print("Not acepted")
print("What do you wish to do?")
print("please input shop, tavern, forest.")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
if choice == "teavern":
print("You enter the tavern and see a couple of drunken warriors singing, a landlord behind the bar and a dodgy figure sitting at the back of the tavern.")
tavernChoice = input("Would you like to talk to the 'drunken warriors', to the 'inn keeper', approach the 'dodgy figure' or 'exit'")
if tavernChoice == "drunken warriors":
print("You approach the warriors to greet them.")
print("They notice you as you get close and become weary of your presence.")
print("As you arrive at their table one of the warriors throughs a mug of ale at you.")
if dexterity >= 5:
print("You quickly dodge the mug and leave the warriors alone")
else:
print("You are caught off guard and take the mug to the face compleatly soaking you.")
print("The dodgy figure leaves the tavern")
The first time you ask the user where to go on line 111, what happens if they enter something besides "shop"? then the if choice == "shop": condition on line 119 will fail, and buy = input("...") will never execute. At that point, buy doesn't exist, so when the next conditional executes, it crashes because it can't evaluate if buy == "crossbow". buy has no value, so you can't compare it to anything.
You need to indent all of your shop logic so that it lies inside the if choice == "shop" block.
if choice == "shop":
print("Welcome to the shop!")
print("You have", gold,"gold")
buy = input("What would you like to buy? A crossbow, a spell or a potion: ")
if buy == "crossbow":
print("this costs 50 gold")
#...etc
if buy == "spell":
print("this costs 35 gold")
And the same problem is present for your tavern code. Even if you don't go to the tavern, you check for tavernChoice. That needs to be indented as well.
if choice == "teavern":
print("You enter the tavern and see a couple of drunken warriors singing, a landlord behind the bar and a dodgy figure sitting at the back of the tavern.")
tavernChoice = input("Would you like to talk to the 'drunken warriors', to the 'inn keeper', approach the 'dodgy figure' or 'exit'")
if tavernChoice == "drunken warriors":
print("You approach the warriors to greet them.")
At this point, your program will end, but I'm guessing you want to continue to be able to explore areas. You could put everything in a while loop, starting with the first input command.
while True:
print("Here is your inventory: ", inventory)
print("What do you wish to do?")
print("please input shop, tavern, forest.")
choice = input("Go to the shop, go to the tavern, go to the forest: ")
if choice == "shop":
print("Welcome to the shop!")
#...etc
elif choice == "tavern":
print("You enter the tavern...")
#...etc
elif choice == "forest":
print("You enter the forest...")
#etc
else:
print("Not acepted")
print("What do you wish to do?")
print("please input shop, tavern, forest.")
This is also a little cleaner than your current method, since you only have to ask the user where they're going once, instead of three times on lines 112, 165, and 170.
Building on Kevin's answer, here is a version with redundancy squeezed out, so you can add a new place just by adding a new def go_xyz(): ... near the top.
def go_shop():
print("Welcome to the shop!")
#...etc
def go_tavern():
print("You enter the tavern...")
#...etc
def go_forest():
print("You enter the forest...")
#etc
places = {name[3:]:globals()[name] for name in globals() if name.startswith('go_')}
placenames = ', '.join(places)
inventory = ['book']
retry = False
while True:
if not retry:
print("Here is your inventory: ", inventory)
else:
print("I do not know that place")
print("Where do you wish to go?")
print("Possible places: ", placenames, '.')
choice = input("? ")
try:
places[choice]()
retry = False
except KeyError:
retry = True

Categories

Resources