Okay, weird question. So I'm making a text adventure game for a school project, and I'm making a shop system. It's supposed to only allow you to buy one of each item, with the exception of potions.
schoice = str(input("> "))
def shopresults(item, itemvar, price):
if schoice == str(item):
if itemvar == 0 and gold >= price:
print("Here ya go! One " + str(item) + " coming right up!")
# itemvar = 1 this should change the variable determining the status of the item, e.g. swordfire1 or swordfire2
gold == gold - price
if item == "fire sword" or itemvar == "water sword" or itemvar == "thunder sword":
freesword = 0
elif itemvar == 1 and (item != potion1 or item != potion2 or item != potion3):
print("You already have that, kiddo!")
elif gold < price:
print("You're a little short on gold there, bud...")
shopresults("fire sword", swordfire1, (100 - (100 * freesword)))
shopresults("flame sword", swordfire2, 500)
How do I change the variable that is called before you get into the shopresults program, in this case swordfire1, instead of the itemvar itself? swordfire1 determines if you have the 1st fire sword, and there's variables like this for every weapon. Ignore the freesword variable, you basically get one free sword in the game, and that's not the problem as far as I know. I know this is confusing, but please help if you can.
I guess I'm wondering what is the value of swordfire1 and swordfire2- they look like integers? My thinking is you should think about creating weapon objects and maintaining a registry of weapons. Based on the status, call your registry and return your weapon object to that variable. When I say registry you can use a simple dict or you can design a factory like pattern.
Variable assignment is done with = not ==. And you need combine the conditions with parentheses:
schoice = str(input("> "))
def shopresults(item, itemvar, price):
if schoice == str(item):
if (itemvar == 0) and (gold >= price):
print("Here ya go! One " + str(item) + " coming right up!")
# itemvar = 1 this should change the variable determining the status of the item, e.g. swordfire1 or swordfire2
gold = gold - price
if (item == "fire sword") or (itemvar == "water sword") or (itemvar == "thunder sword"):
freesword = 0
elif (itemvar == 1) and (item != potion1) or (item != potion2) or (item != potion3):
print("You already have that, kiddo!")
elif gold < price:
print("You're a little short on gold there, bud...")
shopresults("fire sword", swordfire1, (100 - (100 * freesword)))
shopresults("flame sword", swordfire2, 500)
Related
Quite new to programming and have got an issue with some of my python code. I feel like there would be an easier way to write it/ simplify it. I am still working through it (working on the first item before and have got my 'tea' in the virtual vending machine. However I am not sure using that many if elif statements is the cleanest way to complete the code? Also, I want the code to constantly have an input available to the user so they can order more that one drink (if they have the money). So I would like it to loop and start again without losing the coin, how would I go about that?
I know it isn't much, but its my first assignment and I am happy that I have got it this far!
class Vending_Machine:
aussie_coins = (0.05, 0.10, 0.20, 0.50, 1.00, 2.00)
items = ['Tea','Coffee', 'Coke', 'Orange Juice']
item_price = [0.50, 1.00, 1.50, 1.00]
item_code = ['1', '2', '3', '4']
def __init__(self): #define total in vending machine.
self.total = 0.00
def insert_coin(self,coin):
if float(coin) not in (self.aussie_coins):
print ('The Vending Machine accepts only: {}. ' .format(self.aussie_coins), end = '')
else:
self.total += coin
print ('Currently there is a total of {: .2f} in machine' .format(self.total))
class interface(Vending_Machine):
def menu(self):
print("##################################")
print(" Welcome to my Vending Machine ")
print("All items below are readily available")
print(Vending_Machine.item_code[0], Vending_Machine.items[0], "${: .2f}".format(Vending_Machine.item_price[0])) #
print(Vending_Machine.item_code[1], Vending_Machine.items[1], "${: .2f}".format(Vending_Machine.item_price[1]))
print(Vending_Machine.item_code[2], Vending_Machine.items[2], "${: .2f}".format(Vending_Machine.item_price[2]))
print(Vending_Machine.item_code[3], Vending_Machine.items[3], "${: .2f}".format(Vending_Machine.item_price[3]))
print("##################################")
class user_input(interface):
def choice (self):
choice = input("Please enter the item code of an item you would like to purchase: ")
if choice == Vending_Machine.item_code[0]:
print ("You have selected {} - the price is ${: .2f}. Currently you have a total of ${: .2f} in the machine." .format(Vending_Machine.items[0], Vending_Machine.item_price[0], self.total))
if self.total < Vending_Machine.item_price[0]:
coins = float(input("Insert a coin into the vending machine: "))
Vending_Machine.insert_coin(self,coins)
if self.total == Vending_Machine.item_price[0]:
self.total -= Vending_Machine.item_price[0]
print('Please take your {}. There is currently ${: .2f} left in the Machine. Thanks, have a nice day!'.format(Vending_Machine.items[0], self.total))
elif self.total > Vending_Machine.item_price[0]:
self.total -= Vending_Machine.item_price[0]
print ('Please take your {}. There is currently ${: .2f} left in the Machine. Thanks, have a nice day!'.format(Vending_Machine.items[0], self.total))
elif self.total > Vending_Machine.item_price[0]:
self.total -= Vending_Machine.item_price[0]
print('Please take your {}. Total of {: .2f} in the machine' .format(Vending_Machine.items[0],self.total))
elif self.total == Vending_Machine.item_price[0]:
self.total -= Vending_Machine.item_price[0]
print('Please take your {}. Thanks, have a nice day!'.format(Vending_Machine.items[0]))
elif choice == Vending_Machine.item_code[1]:
print ("You have selected {} - the price is ${: .2f}. Currently you have a total of ${: .2f} in the machine." .format(Vending_Machine.items[1], Vending_Machine.item_price[1], self.total))
if self.total < Vending_Machine.item_price[1]:
insert_coin(input("Insert a coin into the vending machine: "))
elif self.total > Vending_Machine.item_price[1]:
self.total -= Vending_Machine.item_price[1]
print('Please take your {}. Total of {: .2f} in the machine' .format(Vending_Machine.items[1],self.total))
elif self.total == Vending_Machine.item_price[1]:
self.total -= Vending_Machine.item_price[1]
print('Please take your {}. Thanks, have a nice day!'.format(Vending_Machine.items[1]))
elif choice == Vending_Machine.item_code[2]:
print ("You have selected {} - the price is ${: .2f}. Currently you have a total of ${: .2f} in the machine." .format(Vending_Machine.items[2], Vending_Machine.item_price[2], self.total))
if self.total < Vending_Machine.item_price[2]:
insert_coin(input("Insert a coin into the vending machine: "))
elif self.total > Vending_Machine.item_price[2]:
self.total -= Vending_Machine.item_price[2]
print('Please take your {}. Total of {: .2f} in the machine' .format(Vending_Machine.items[2],self.total))
elif self.total == Vending_Machine.item_price[2]:
self.total -= Vending_Machine.item_price[2]
print('Please take your {}. Thanks, have a nice day!'.format(Vending_Machine.items[2]))
elif choice == Vending_Machine.item_code[3]:
print ("You have selected {} - the price is ${: .2f}. Currently you have a total of ${: .2f} in the machine." .format(Vending_Machine.items[3], Vending_Machine.item_price[3], self.total))
if self.total < Vending_Machine.item_price[3]: #if not the price of tea then..
insert_coin(input("Insert a coin into the vending machine: "))
elif self.total > Vending_Machine.item_price[3]:
self.total -= Vending_Machine.item_price[3]
print('Please take your {}. Total of {: .2f} in the machine' .format(Vending_Machine.items[3],self.total))
elif self.total == Vending_Machine.item_price[3]:
self.total -= Vending_Machine.item_price[3]
print('Please take your {}. Thanks, have a nice day!'.format(Vending_Machine.items[3]))
elif choice not in item_code:
print("Sorry we do not have item number {} available. Please try again" .format(choice))
vm = Vending_Machine()
i1 = interface()
u1 = user_input()
i1.menu()
u1.choice()
This is probably better suited for the code review board, but anyways...
Really great for a first project! That being said, you've already identified the major shortcoming of your code - you shouldn't have to use all those if/elifs. I also don't think you can justify wrapping most of your code into classes, like you've done. These are my suggestions:
Define two classes, VendingMachine and Item (an instance of this
class represents a single available item in the vending machine).
Follow good naming conventions. Notice the class names start with an
uppercase letter, and are camel-case.
Define an explicit entry point for your program, such as main.
Use a loop to iterate over your vending machine items when displaying
them. You can do something similar to cull all those if-statements.
Code:
class Item:
def __init__(self, name, price):
self.name = name
self.price = price
class VendingMachine:
def __init__(self):
self.items = [
Item("Tea", 0.50),
Item("Coffee", 1.00),
Item("Coke", 1.50),
Item("Orange Juice", 1.00)
]
self.money_inserted = 0.00
def display_items(self):
for code, item in enumerate(self.items, start=1):
print(f"[{code}] - {item.name} (${item.price:.2f})")
def insert_money(self, money):
if money <= 0.00:
raise ValueError
self.money_inserted += money
def main():
vending_machine = VendingMachine()
vending_machine.display_items()
while True:
try:
user_selection = int(input("Please enter the desired item code: "))
except ValueError:
continue
if user_selection in range(1, len(vending_machine.items)+1):
break
item = vending_machine.items[user_selection-1]
print(f"You've selected \"{item.name}\" - the price is ${item.price:.2f}")
while vending_machine.money_inserted < item.price:
print(f"You've inserted ${vending_machine.money_inserted:.2f} into the machine so far.")
while True:
try:
money_to_insert = float(input("Please enter the amount of money you'd like to insert: "))
vending_machine.insert_money(money_to_insert)
except ValueError:
continue
else:
break
print(f"Thank you! Please take your \"{item.name}\".")
print(f"The remaining change in the machine is ${vending_machine.money_inserted - item.price:.2f}.")
return 0
if __name__ == "__main__":
import sys
sys.exit(main())
Output:
[1] - Tea ($0.50)
[2] - Coffee ($1.00)
[3] - Coke ($1.50)
[4] - Orange Juice ($1.00)
Please enter the desired item code: d32
Please enter the desired item code: 3
You've selected "Coke" - the price is $1.50
You've inserted $0.00 into the machine so far.
Please enter the amount of money you'd like to insert: 4ff4
Please enter the amount of money you'd like to insert: 1
You've inserted $1.00 into the machine so far.
Please enter the amount of money you'd like to insert: .10
You've inserted $1.10 into the machine so far.
Please enter the amount of money you'd like to insert: .90
Thank you! Please take your "Coke".
The remaining change in the machine is $0.50.
>>>
Good work. I've got one word to say to you: loops.
Where you've got 4 lines printing the vending machine items (at the start), you could replace it with a loop, like so:
for index in range(len(VendingMachine.items)):
print(Vending_Machine.item_code[index], Vending_Machine.items[index], "${: .2f}".format(Vending_Machine.item_price[index]))
Hopefully that gives you enough information to work out how to shrink the rest of your code too. If it needs to be elif (as in, you only want to check one of them, not all of them), use a break in the loop (see below for an example of a break).
As for your second question, you could have a loop around the insert_coin function call (in the user_input function) which keeps adding coins until the user inputs 'done'.
Here's a pretty basic example. There could be better ways to do this, but it should work.
while True:
coins = float(input("Insert a coin into the vending machine: "))
if coins == "done":
break
Vending_Machine.insert_coin(self,coins)
I'm trying to create a text-based adventure game and all is going well until I encountered a problem with assigning points to attributes. I've been using this website to help with the process but realized that it might be in Python 2. Here's all that I've done so far code:
#Date started: 3/13/2018
#Description: text-based adventure game
import random
import time
def display_intro():
print('It is the end of a 100-year war between good and evil that had \n' +
'killed more than 80% of the total human population. \n')
time.sleep(3)
print('The man who will soon be your father was a brave adventurer who \n' +
'fought for the good and was made famous for his heroism. \n')
time.sleep(3)
print('One day that brave adventurer meet a beautiful woman who he later \n' +
'wed and had you. \n')
time.sleep(3)
def get_gender(gen=None):
while gen == None: # input validation
gen = input('\nYour mother had a [Boy or Girl]: ')
return gen
def get_name(name = None):
while name == None:
name = input("\nAnd they named you: ")
return name
def main():
display_intro()
gender_num = get_gender()
charater_name = get_name()
print("You entered {} {}.".format(gender_num, charater_name))
if __name__ == "__main__":
main()
character_name = get_name()
# Assignning points Main
my_character = {'name': character_name, 'strength': 0, 'wisdom': 0, 'dexterity': 0, 'points': 20}
#This is a sequence establises base stats.
def start_stat():
print("\nThis is the most important part of the intro\n")
time.sleep(3)
print("This decides your future stats and potentially future gameplay.")
time.sleep(4)
print("\nYou have 20 points to put in any of the following category:
Strength, Health, Wisdom, or Dexterity.\n")
def add_charater_points(): # This adds player points in the beginnning
attribute = input("\nWhich attribute do you want to assign it to? ")
if attribute in my_character.keys():
amount = int(input("By how much?"))
if (amount > my_character['points']) or (my_character['points'] <= 0):
print("Not enough points!!! ")
else:
my_character[attribute] += amount
my_character[attribute] -= amount
else:
print("That attribute doesn't exist!!!")
def print_character():
for attribute in my_character.keys():
print("{} : {}".format(attribute, my_character[attribute]))
playContinue = "no"
while playContinue == "no":
Continue = input("Are you sure you want to continue?\n")
if Continue == "yes" or "Yes" or "y":
playContinue = "yes"
start_stat()
add_charater_points()
else:
display_intro()
gender_num = get_gender()
charater_name = get_name()
running = True
while running:
print("\nYou have {} points left\n".format(my_character['points']))
print("1. Add points\n2. Remove points. \n3. See current attributes. \n4. Exit\n")
choice = input("Choice: ")
if choice == "1":
add_charater_points()
elif choice == "2":
pass
elif choice == "3":
print_character()
elif choice == "4":
running = False
else:
pass
And here's what happens when I run it:
It is the end of a 100-year war between good and evil that had
killed more than 80% of the total human population.
The man who will soon be your father was a brave adventurer who fought for
the good and was made famous for his heroism.
One day that brave adventurer meet a beautiful woman who he later wed and
had you.
Your mother had a [Boy or Girl]: boy
And they named you: Name
You entered boy Name.
And they named you: Name
Are you sure you want to continue?
yes
This is the most important part of the intro
This decides your future stats and potentially future gameplay.
You have 20 points to put in any of the following category: Strength,
Health, Wisdom, or Dexterity.
Which attribute do you want to assign it to? strength
By how much? 20
You have 20 points left
1. Add points
2. Remove points.
3. See current attributes.
4. Exit
Choice: 3
name : Name
strength : 0
wisdom : 0
dexterity : 0
points : 20
You have 20 points left
1. Add points
2. Remove points.
3. See current attributes.
4. Exit
Choice:
Oh, and prompt for the name of the play goes again twice for some reason. Also, what does the my_character.keys() under def add_charater_points() mean? Since I just started to learn to code python, if there are any other tips you guys can give me it would be greatly appreciated.
The last two lines of this snippet
if (amount > my_character['points']) or (my_character['points'] <= 0):
print("Not enough points!!! ")
else:
my_character[attribute] += amount
my_character[attribute] -= amount
add the character points to the attribute, and immediately subtract them again. I think you might mean
my_character['points'] -= amount
Your repeated prompt is probably because you have a whole lot of code that logically seems to belong in function main() but is coded to run after main() finishes.
I have had problems with the shell saying local variable referenced before assignment and don't feel any previous answers have helped. Can I have some specific advice to this code:
import random
marginalCheck = random.randint(0,1)
print("This is the political campaign simulator")
global popularity
popularity = 50
def unpopularT():
if popularity <= 30 and popularity < 0:
print("You are decreasing in popularity.")
popularityRecover = input("Do you wish to carry on or resign. If this carries on, you are likely to lose to a landslide by your Labour opposition")
if popularityRecover == "resign":
print("You have become an infamous, unpopular politician. You are remembered as a horrible, unkind person")
else:
print("You are hanging by a thread")
elif popularity > 70:
print("You are seriously doing well among your supporters and gaining new ones every day")
else:
print("You are doing fine so far in the campaign")
def campaignT():
leadershipT = input("You are chosen as a candidate by your colleagues in the Tory leadership contest. Do you wish to take an A - Far Right, B - Right, C - Centre, D - Left or E - Far Left stance on the political spectrum")
if leadershipT == "A" or leadershipT == "B":
print("You have been elected as leader of the Tories and leader of the opposition. Now the election campaign starts")
ClassicToryAusterity = input("What do you wish to do about the poor funding in the NHS by the Labour government. A - Do you wish to keep the current program, B - Do you wish to increase funding dramatically and increase taxes, C - Do you propose minor increases with small raises on tax, D - Do you support austere implementations on the Health Service")
if ClassicToryAusterity == "A":
popularity += -5
elif ClassicToryAusterity == "B":
popularity += 5
elif ClassicToryAusterity == "C":
popularity += 2
elif ClassicToryAusterity == "D":
popularity += -10
BedroomTax = input("What do you propose to do about the bedroom tax. A - increase it, B - freeze it, C - Decrease it, D - Scrap it")
if BedroomTax == "A":
popularity += -10
elif BedroomTax == "B":
popularity += -5
elif BedroomTax == "C":
popularity += -1
else:
popularity += 10
unpopularT()
else:
print("The Tory whip dislikes your stance and you have not been voted as leader")
chosenParty = input("Choose a party. A - LibDem, B - Labour, C- Tory")
if chosenParty == "C":
print("You have been elected as a councillor by your fellow peers.")
marginality = input("They want you to stand as a MP in a seat. Do you want to stand in a safe or marginal seat")
if marginality == "marginal":
if marginalCheck == 0:
print("You have failed to be elected to parliament")
else:
print("You are duly elected the MP for your constituency!")
campaignT()
else:
campaignT()
What I don't understand is that I have referenced popularity as a global variable, but according to the shell, it is local.
If you want to use access global variables inside functions you don't need to declare anything, but if you need to re-assign the variable by any means, you need to declare it inside the function. For example:
test = 'hello'
def print_test():
print test
def set_test():
global test
test = 'new value'
in your case, you didn't declare the global variable popularity inside your function and you were trying to re-assign it.
So in your case:
def unpopularT():
global popularity
# your code
def campaignT():
global popularity
# your code
I am a programming beginner and I am trying to build a fill-in-the-blank quiz. I am almost finished but I am stuck on 2 problems I am not able to solve, whatever I do. I would really appreciate your help with this. Thank you for helping me with this!
If you try to run the code and play the game:
1) It prints the quiz according to the difficulty(easy-insane) and quiz you want to play(apple, bond and programming quiz) which is great but afterwards it prompts you to choose difficulty again (the player_level() function keeps going even though the player/user has already chosen the difficulty level. I don't really understand why it does it? The player_level() procedure seems perfectly okay and logical to me.
2) The errors:
a) local variable blanks_index referenced before assignment
b) global name list_of_answers is not defined.
I know that it is related to the initialize_game() function but I don't know how to change the code so it refers all the variables (blanks_index, answers_index, player_lives) correctly.
It could be solved by creating global variables(I guess) but that is not a good practice so I am trying to avoid it. Formerly, the whole function initialise_game() and play_game() were one function, but as there are over 25 lines of code in one function, it is not a good practice as it is long and messy and I know that I can separate it but I don't know how.
Here is the code:
"""3 diffferent quizzes : Apple quiz, James Bond quiz, Programming quiz"""
"""Quiz and answers about Apple"""
Apple_quiz = ("The most valuable company in terms of market cap in 2016 is, ___1___."
"It was founded in ___2___. Its flagship product is called ___3___."
"___1___ has many competitors, the biggest rival is ___4___,founded by"
" nobody but the richest man on the planet,___5___ ___6___.")
list_of_answers_Apple = ["Apple", "1976", "Iphone", "Microsoft", "Bill", "Gates"]
"""Quiz and answers about Bond"""
Bond_quiz = ("James Bond is agent ___1___. He serves his country,___2___ ___3___"
" against its enemies. His car of choice is usually ___4___ ___5___."
" His favorite drink is ___6___.")
list_of_answers_Bond = ["007", "United", "Kingdom", "Aston", "Martin", "Martini"]
"""Quiz and answers about programming basics"""
Programming_quiz = ("___1___ are created with the def keyword. ___1___ are also called ___2___"
" You specify the inputs a ___1___ take by adding ___3___ separated by commas"
" between the parentheses. ___3___ can be standard data types such as string, number"
" ,dictionary, tuple, and ___4___ or can be more complicated such as ___5___"
" and ___6___ functions.")
list_of_answers_Programming = ["Functions", "procedures", "arguments", "lists", "objects", "lambda"]
blank_space = ["___1___", "___2___", "___3___", "___4___", "___5___", "___6___]"]
#List of levels with corresponding lives/guesses that player can have
quiz_list = ["Apple", "Bond", "Programming"]
level_list = ["easy", "medium", "hard", "superhard", "insane"]
lives_easy = 5
lives_medium = 4
lives_hard = 3
lives_superhard = 2
lives_insane = 1
def choose_quiz():
""" Prompts player to pick a type of quiz and loads the quiz """
#Input = player_quiz (raw input from player)
#Output = loaded quiz, player chose
while True:
player_quiz = raw_input("Please, select a quiz you want to play: "
"(Apple, Bond or Programming): ")
if player_quiz == "Apple":
return Apple_quiz
elif player_quiz == "Bond":
return Bond_quiz
elif player_quiz == "Programming":
return Programming_quiz
else:
print "We don't have such quiz, pick again!"
def answers_for_quiz():
""" Loads appropiate answers to the quiz that player has chosen"""
#Input = player quiz (raw input from player)
#Output = loaded quiz answers from the quiz player chose
player_quiz_pick = choose_quiz()
if player_quiz_pick == Apple_quiz:
return list_of_answers_Apple
elif player_quiz_pick == Bond_quiz:
return list_of_answers_Bond
elif player_quiz_pick == Programming_quiz:
return list_of_answers_Programming
def player_level():
""" Loads a difficulty that player chooses """
#Input = player_level_input (raw input of player choosing a difficulty)
#Output = corresponding number of lives:
#Easy = 5 lives, Medium = 4 lives
#Hard = 3 lives, Superhard = 2 lives
#Insane = 1 life
while True:
player_level_input = raw_input("Please type in a difficulty level: "
"(easy, medium, hard, superhard, insane): ")
if player_level_input == "easy":
return lives_easy #Easy = 5 lives
elif player_level_input == "medium":
return lives_medium #Medium = 4 lives
elif player_level_input == "hard":
return lives_hard #Hard = 3 lives
elif player_level_input == "superhard":
return lives_superhard #Superhard = 2 lives
elif player_level_input == "insane":
return lives_insane #Insane = 1 life
else:
print "We do not have such difficulty! Pick again!"
def correct_answer(player_answer, list_of_answers, answers_index):
""" Checks, whether the the answer from player matches with the answer list. """
#Input: player_answer (raw input that player enters in order to fill in the blank)
#Output: "Right answer!" or "Wrong! Try again!" this output will be later used in the game
if player_answer == list_of_answers[answers_index]:
return "Right answer!"
return "Wrong! Try again!"
def initialize_game():
"""Functions that sets up a game so we can play it """
player_quiz_pick, player_level_pick, list_of_answers = choose_quiz(), player_level(), answers_for_quiz()
print player_quiz_pick
print "\nYou will get maximum " + str(player_level_pick) + " guesses for this game. Good luck.\n"
blanks_index, answers_index, player_lives = 0, 0, 0
#for elements in blank_space:
while blanks_index < len(blank_space):
player_answer = raw_input("Please type in your answer for " + blank_space[blanks_index] + ": ")
if correct_answer(player_answer,list_of_answers,answers_index) == "Right answer!":
print "Correct answer! Keep going!\n"
player_quiz_pick = player_quiz_pick.replace(blank_space[blanks_index],player_answer)
answers_index += 1
blanks_index += 1
print player_quiz_pick
if blanks_index == len(blank_space):
print "Congratulations! You nailed it! You are the winner!"
else:
player_level_pick -= 1
if player_level_pick == 0:
print "Game over! Maybe next time!"
break
else:
print "One life less, that sucks! Have another shot!"
print "You have " + str(player_level_pick) + " guesses left."
initialize_game()
Your main problem is that you keep calling the same functions over and over again and do not save the input into variables. Here are some tips about your code and questions:
You are not doing anything with your player_level() method call, so the player doesn't actually chooses a level in a way that affects the game. You should change the function call, so the returned value will be stored.
//the call to the method:
player_level_pick = player_level()
Afterwards, you keep calling the player_level() method, and not using the actual answer that the user supplied. Change all player_level() appearences to player_level_pick - the variable you use to save the answer (as I showed above). Same goes to all other unneeded function calls such as choose_level().
You should initialize number_of_guesses, player_lives, list_of_answers, and other vars to a matching value to player_level_pick as well, so it will hold the right value according to the level. Likewise, you should change this line:
# the line that checks if game is over
# change from:
if number_of_guesses == player_lives:
# to :
if number_of_guesses == 0:
In order to return multiple values, you have to use tuples. Using multiple return statements one after the other does not work anywhere.
so, instead of:
return list_of_answers
return number_of_guesses
return blanks_index
return answers_index
return player_lives
you should use tuples, and unpack them properly:
# the return statement:
return (list_of_answers, number_of_guesses, blanks_index, answers_index, player_lives)
# and the unpacking in the calling function:
list_of_answers, number_of_guesses, blanks_index, answers_index, player_lives = initialize_game()
this way, all of the returned values go into the wanted variables in the calling function. this way, you need to call the initialize_game() from play_game(). it will be the efficient way for you.
Just saying it again, as I said in the end of (4) - you should unit initialize_game() and play_game() into a single function (because a lot of data is the same needed data), or just call initialize_game() from play_game().
Better practice then using this recursivly: return choose_level(), you should use a while True: loop, and just brake when you get a proper answer.
I'm mostly new to this so apologies in advance if the answer is blindingly obvious to this. For a school assignment (and out of interest also) I'm building a sort of basic car app that uses lists to store cars (objects) as they are made then a separate list to record cars that are rented.
The rent process works perfectly fine and when I tested it it was appending a car to my rentedcars list, however when I call it (rentedcars) later in a separate function its saying that it cannot pop an empty list.
I assumed this was because the list was being modified inside a function, however when I returned the outputed modified list and assigned a variable to the function for later use it gave me the error that I was calling a variable before assigning it and giving the variable a global definition didn't resolve it.
The segment of code is below, anyone have any thoughts? It would be much appreciated. I've looked this sort of problem a couple of times on the forums here but the solutions (at least as I tried to implement them) didn't seem to fix it.
The function rental_system is called later, I've just shown the section I'm having problems with due to size, all lists for the 4 types of car are made under init self. etc and work.
def rent(self, car_list, rented_cars, amount): # Process to rent a car function
if len(car_list) < amount:
print 'Not enough cars in stock' # Make sure enough cars in stock
return
total = 0
while total < amount:
carout = car_list.pop() # Pop last item from given car list and return it
rented_cars.append(carout) # Then append to a new list of rented cars that are now unavailable
total = total + 1
print 'Make: ' + carout.getMake()
print 'Colour: ' + carout.getColour()
print 'Engine Size(Cylinders): ' + carout.getEngineSize()
print 'You have rented ' + str(amount) + ' car(s)'
return rented_cars
def rented(self, car_list, rented_cars, amount): # Process for returning cars
total = 0
while total < amount:
carin = rented_cars.pop()
car_list.append(carin)
total = total + 1
print 'You have returned' +str(amount) + 'car(s)'
return rented_cars, car_list
def rental_system(self):
rentedcars = []
rented = raw_input('Are you returning or renting a car? Type either return/rent ')
if rented.lower() == 'return': # Return system
type = raw_input('Are you returning a petrol, electric, diesel or hybrid car? ')
amount = raw_input('How many would you like to return? ')
if type == 'petrol':
self.rented(self.petrolcars, rentedcars, amount)
elif type.lower() == 'diesel':
self.rented(self.dieselcars, rentedcars, amount)
elif type.lower() == 'hybrid':
self.rented(self.hybridcars, rentedcars, amount)
elif type.lower() == 'electric':
self.rented(self.electriccars, rentedcars, amount)
else:
print 'Error, please check your spelling'
return
if rented.lower() == 'rent':
Rental process
answer = raw_input('What type of car would you like? Type: petrol/diesel/hybrid/electric ')
amount = int(raw_input('How many of that type of car?'))
if answer.lower() == 'petrol':
self.rent(self.petrolcars, rentedcars, amount)
elif answer.lower() == 'diesel':
self.rent(self.dieselcars, rentedcars, amount)
elif answer.lower() == 'hybrid':
self.rent(self.hybridcars, rentedcars, amount)
elif answer.lower() == 'electric':
self.rent(self.electriccars, rentedcars, amount)
else:
print 'Error, please check your spelling'
return
The problem is that you are passing an empty list through the rental_system method to the rented method.
You have defined rentedcars = [] in rental_system method and without modifying it you are trying to pop from it in the rented method.
Why don't you add the rented_cars as an attribute in your class design?