Python problems with "local variable referenced before assignment" - python

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

Related

Pygamezero code, My code works when I don't have any code after this, why is this?:

backg.pos = 242, 105
WIDTH = int(backg.width + 200)
HEIGHT = int(backg.height + 50)
def draw():
screen.clear()
backg.draw()
print("hi")
I have a picture called dining that I am trying to use as a background in a game which works just fine on its own, but when I add the rest of the code
name = input("What would you like to be called? >>> ")
inventory = []
def welcome():
print(f'Hello detective {name.title()}')
print("There has been a murder by poison in this house of a woman named Carla, you have to find the clues to unlock who the murderer is, there are 10 suspects and 5 rooms all with clues that will be useful to your mission. \n\nYOUR MISSION: FIND THE MURDERER AND BRING THEM TO JUSTICE!\n")
print("First question the suspects, then explore the rooms.")
question()
def dr():
drq = input("What do you want to do? \nA:Look in the cubbords \nB: Talk to Ella \nC: Go to a different room")
if drq.title == "A":
print("*You Find Insulin in the Cubbord*")
print("[Ella]>>> That was Carla's insulin, she had diabetes type one.")
inventory.insert("insulin")
print("*INSULIN HAS BEEN ADDED TO YOUR INVENTORY*")
elif drq.title == "B":
print("This is the Dining Room, Please talk to me if you need any infomation")
elif drq.title == "C":
rooms()
else:
print("Please pick a valid option A, B, C")
dr()
def lr():
lrq = input("What do you want to do? \nA:Check the book \nB:Check the fire place \n C:Talk to Ella \nD: Go to a different room")
if lrq.title == "A":
print("*Notice The Book Has Some Blood On It* [YOU]>>> Who's book was this?")
print("[Ella]>>> That's Johnny's book acctually, I better return it to him.")
print("[YOU]>>>I would like to keep it for evidence.")
inventory.insert("book")
print("*BOOK HAS BEEN ADDED TO INVENTORY")
elif lrq.title == "B":
print("*In the fire place you see a burnt note that reads \"THE DEED IS DONE\" *")
elif lrq.title == "C":
print("This is the Living Room, we all relaxed here after dinner")
elif lrq.title == "D":
rooms()
else:
print("Please pick a valid option A, B, C")
lr()
def mb():
mbq = input("What do you want to do? \nA:Check the draws \nB:Talk to Ella \nC: Go to a different room")
if mbq.title == "A":
print("you rummage through the draws and find jewlery, makeup, and a knife!\nYou deside not to tell Ella as she has been through enough trouble and you need more evidence.\n*KNIFE HAS BEEN ADDED TO INVENTORY!")
elif mbq.title == "B":
print("[Ella]>>> This is me and my husbands bedroom, we slept here last night when the murder occoured.")
elif mbq.title == "C":
rooms()
else:
print("Please pick a valid option A, B, C")
mb()
def rooms():
room = input("Which room would you like to go to? \nA:Dining Room \nB:Living Room \nC:Master Bedroom \nD:Carla's Room \nE:The Kitchen \n >>>")
if room.title == "A":
dr()
elif room.title == "B":
lr()
elif room.title == "C":
mb()
elif room.title == "D":
cr()
elif room.title == "E":
K()
else:
print("Please pick a valid option: A, B, C, D, E.")
rooms()
def question():
interview = input("Who do you want to question? Ella, Johnny, Harry, Lesley, Brook, Casey, Corey, Adrien, Hannah >>> ")
if interview.title() == "Ella":
print(f'\nI\'m Carla\'s Mother and i am so upset, I Think whoever did this NEEDS to be brought to justice, thank for spending your time to help us detective {name}')
elif interview.title() == "Johnny":
print(f'\nHello detective, I am Carla\'s brother. I was in my room when the murder occoured at 8 O\'clock, I heard her scream and being the scaredy cat I am, rather than going to see if I could find her and see if she was ok, I cowered in my bed.')
elif interview.title() == "Harry":
print(f'\nHello detective, I am Carla\'s Farther. I was with my darling Ella in our Master bedroom when the murder occoured, we had invited everyone over for dinner as it was, my beautiful daughters birthday, what a horrible day to be killed on')
elif interview.title() == "Lesley":
print('\nHello detective, I am Carla\'s nextdoor neighbour and we have been best friends for years, if you accuse me i will be very offended! This family seems to be addement it was me that killed her, I just think they don\'t want to belive it was part of their family that killed her')
elif interview.title() == "Brook":
print("\nHello detective, I am Carla\'s sister and although we have had our differences, I would never want to kill her, I was sleeping in the room next to Casey and Adrien.")
elif interview == "Blake":
print("\nCarla is my wife, I love her to pieces who ever did this, I will make them pay, with or without the Law on my side")
elif interview.title() == "Casey":
print("\nI\'m Carla\'s Mothers\'s neighbour, they invited me and my husband, Adrien, over for dinner and we politely refused'")
elif interview.title() == "Corey":
print("\nI\'m Carla\'s Godfarther and although we have never been very close i do love her dearly.'")
elif interview.title() == "Adrien":
print("\nI\'m Casey's husband and I don\'t really know what happend, I have had little to none contact with Carla and have know idea what was going on. Me and my wife just stayed over there's for the night as we were having work done to our house")
elif interview.title() == "Hannah":
print("\nI\'m Carla\'s Godmother and have always loved and cared for my Godchild, I do not know for certain but I think Adrien and Casey are acting quite suspicious")
else:
print("\n\nPlease pick a valid option\n\n")
question()
bigq()
def bigq():
answer = input("\nDo you want to \nA:Question anyone else \nor \nB:Do you want to investigate the rooms?\n>>>")
if answer.title() == "A":
print("\n\n")
question()
elif answer.title() == "B":
rooms()
else:
print("Please pick a valid option A or B")
bigq()
welcome()
(it's a murder mystery type thing and I just need help getting it to work)
i need to type as it says there is to much codeeeeeee
please reply for answers and if you need any more details
thank you everyone for you kindness and support :-)

Changing a variable in a def function

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)

Value defined in one function not available in another

Alright, so this is my first post. I have searched through here trying to find any questions for reference if I missed it I apologize.
So my daughter and I are writing a game together. I have been working on some of the foundation programming while she does the creative stuff.
I have a function where the user picks a "class" that assigns base values for certain aspects and returns them as a variable. Following other posts I first tried using return function but that didn't work so I tried global function. That allows the program to use the variable to simply print it outside the function, but when another function tries to use the variable it comes up as not variable referenced before assignment.
import random
import time
#these were another attempt at finding a way to make the classes
#available to other functions
combat = 0
strength = 0
agility = 0
magic = 0
intelligence = 0
def chose_class():
#I tried return "each characteristic" at the end, but it wouldn't
#even print out the returned value
global strength
global combat
global agility
global magic
global intelligence
health = 10
print("Chose your class:")
print("Warrior: 1")
print("Wizard: 2")
print("Philosopher: 3")
print("Thief: 4")
print("Help: 5")
dog1 = int(input(":"))
if dog1 ==1:
strength = 7
combat = 7
agility = 5
stealth = 3
magic = 1
intelligence = 1
elif dog1 == 2:
strength = 3
combat = 1
agility = 3
stealth = 3
magic = 8
intelligence = 6
elif dog1 == 3:
strength = 3
combat = 1
agility = 3
stealth = 3
magic = 2
intelligence = 8
elif dog1 == 4:
strength = 2
combat = 4
agility = 6
stealth = 8
magic = 1
intelligence = 6
elif dog1 == 5:
print("Warrior Dog:")
print(" Warrior Dogs possess great strength and combat ability")
print(" they have medium agility, but low stealth, magic and")
print(" intelligence.")
print("\n"*2)
print("Wizard Dog:")
print(" Wizard Dogs have low strength, combat, and agility,")
print(" they have medium stealth and high magic capabilities.")
print("\n"*2)
print("Philosopher Dog:")
print(" Philosopher Dogs are highly intelligent, while they")
print(" have low strength, they have medium combat ability.")
print(" Their agility, stealth, and magic start low but can")
print(" rapidly improve by finding hidden objects on quests.")
print("\n"*2)
print("Thief Dogs")
print(" Thief Dogs have high agility and stealth, as well as")
print(" average intelligence and combat. They have low combat,")
print(" magic, and strength.")
else:
chose_class()
def room17():
print("**Description**")
print("Do you want to fight the cat guard or sneak past it?")
print("Fight: 1")
print("Sneak Past: 2")
choice17 = str(input(":"))
if "1" in choice17:
fight17 = random.randint(0,5)
combat17 = combat * fight17
if combat17 <= 20:
print("You were successful")
combat = combat + 1
else:
print("You lost the fight and had to retreat")
health = health - 1
room1()
else:
sneak17 = random.randint(0,5)
stealth17 = sneak17 * stealth
if stealth17 <= 20:
print("You snuck past the guard")
stealth = stealth + 1
else:
print("The guard caught you, he attacks and you have to retreat")
health = health - 2
stealth = stealth - 1
room1()
chose_class()
# this was just to see if the value was returned
print("Combat:", combat)
# I'm jumping to the first combat event to try to test the program
room17()
Okay, so that should be enough of what I have to demonstrate the issue. I'm completely self taught so I'm sure there are tons of stylistic issues, which I'm perfectly happy to get help with. But if anyone can help with why the variable "combat" is returned from "def chose_class()" to the print command but then not assigned in the "def room17()" I would greatly appreciate it.

The script is not assigning points to the attribute

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.

Python Functions called before referencing error coming up?

I have a problem with the following code:
#1/usr/bin/env python3
import random
financialPoints = 0
debatePointsT = 0
marginalCheck = random.randint(0,1)
debatePointsTO = 0
Choice = random.randint(0,2)
popularity = 0
name = input("What is your first name")
nameSur = input("What is your surname")
print("This is the political campaign simulator")
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()
def debateT():
#My Code
if marginality == "safe":
campaignT()
def campaign():
#My Code
if elected == True:
debateT()
It tells me that I have called a function before referencing it, but I need it to be there for me to run another part of the code, as you can see above. Is there a way in python for me to get to functions to go side by side, or something like that?
The function definition must come before the code that references it.
Move debateT() and campaign() to the top of the file.
Move your defined functions to the top of your file like:
#1/usr/bin/env python3
import random
financialPoints = 0
debatePointsT = 0
marginalCheck = random.randint(0,1)
debatePointsTO = 0
Choice = random.randint(0,2)
def debateT():
#My Code
if marginality == "safe":
campaignT()
def campaign():
#My Code
if elected == True:
debateT()
popularity = 0
name = input("What is your first name")
nameSur = input("What is your surname")
print("This is the political campaign simulator")
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()

Categories

Resources