This question already has answers here:
Using global variables in a function
(25 answers)
Closed 5 years ago.
I'm trying to get rid of a error in python but so far every method i've tried hasn't worked. Any help would be greatly appreciated.
The code:
from sense_hat import SenseHat
import random
from guizero import App, PushButton,Text
import time
import pygame.mixer
from pygame.mixer import Sound
pygame.mixer.init()
sense = SenseHat()
app = App(title="Fruity Fruit Machine", bgcolor="yellow")
mario = Sound("SuperMarioBros.ogg")
money = 30.00
casino = 100.00
global money
global casino
def machine():
sense.clear(0,0,0)
images = ["apple.png", "orange.png", "lemon.png"]
fruit = []
money = money - 1.00
for i in range(3):
img = random.choice(images)
fruit.append(img)
sense.load_image(img)
time.sleep(3)
sense.clear(0,0,0)
if all_same(fruit) == True:
sense.show_message("You won £20!")
casino = casino - 20.00
money = money + 20.00
display_casino()
dispaly_money()
dc = "Casino money: " + casino
cm.set(dc)
md = "Your money: " + money
m.set(md)
else:
sense.show_message("You got 30p!")
money = money + 00.30
casino = casino + 00.70
display_casino()
display_money()
dc = "Casino money: " + casino
cm.set(dc)
md = "Your money: " + money
m.set(md)
def play_mario():
mario.play()
def all_same(items):
return all(x == items[0] for x in items)
button = PushButton(app, command=machine, text="SPIN")
button2 = PushButton(app, command=play_mario, text="Play Music")
cm = Text(app, text="",align="left")
m = Text(app, text="",align="right")
The error is: UnboundLocalError: local variable 'money' referenced before assignment. Python also sometimes comes up with a syntax warning: SyntaxWarning: name 'casino' is assigned to before global declaration
Try moving the global declarations inside your function:
from sense_hat import SenseHat
import random
from guizero import App, PushButton,Text
import time
import pygame.mixer
from pygame.mixer import Sound
pygame.mixer.init()
sense = SenseHat()
app = App(title="Fruity Fruit Machine", bgcolor="yellow")
mario = Sound("SuperMarioBros.ogg")
money = 30.00
casino = 100.00
def machine():
global money
global casino
sense.clear(0,0,0)
images = ["apple.png", "orange.png", "lemon.png"]
fruit = []
money = money - 1.00
for i in range(3):
img = random.choice(images)
fruit.append(img)
sense.load_image(img)
time.sleep(3)
sense.clear(0,0,0)
if all_same(fruit) == True:
sense.show_message("You won £20!")
casino = casino - 20.00
money = money + 20.00
display_casino()
dispaly_money()
dc = "Casino money: " + casino
cm.set(dc)
md = "Your money: " + money
m.set(md)
else:
sense.show_message("You got 30p!")
money = money + 00.30
You need to put global money and global casino within machine. Putting it outside a function does nothing. For an explanation of why, take a look at this answer.
Related
I am making a soccer game. I am new to Python. I am trying to make soccerplayers on a file, then import it to my main game.
Here is soccerplayer.py
class soccerp:
def __init__(self,overall,name,speed,shoot,ballc,defence):
self.overall = overall
self.name = name
self.speed = speed
self.shoot = shoot
self.ballc = ballc
self.defence = defence
Here is soccerkeeper.py
class soccerk:
def __init__(self,overall,name,dive,reactspeed,reach,jump):
self.overall = overall
self.name = name
self.dive = dive
self.reactspeed = reactspeed
self.reach = reach
self.jump = jump
Here is soccerplayerlist.py
from soccerplayer import soccerp
from soccerkeeper import soccerk
#name overall speed shootingpower ballcontrol defence
david = soccerp("david",114,181,179,183,148)
john = soccerp("john",119,179,185,187,151)
soccerplayers = [david,john]
And here is my game.py
import time
from soccerplayerlist import soccerplayers
#name overall speed shootingpower ballcontrol defence
ovr = [120,124,158,132,109] #will edit as the players overalls
teamovr = round(sum(ovr) / len(ovr))
def start():
print("Please pick your teams name : ")
team = input("> ")
print("")
time.sleep(1)
return team
def menu(team):
print("teams name : " + team)
print("team overall : " + str(teamovr))
def game():
team = start()
#while True:
teamovr = round(sum(ovr) / len(ovr))
menu(team)
print(david.name) #checking if the players were imported from soccerplayerlist.py
game()
when I run the code, It says
NameError: name 'david' is not defined
I think that it didnt import the players, I may be wrong, what am I doing wrong here?
The issue is that you're importing the list and not the values of the list.
If you do
print(soccerplayers[0].name)
You should get the desired result.
The name david is not the one you import it is the list of soccerplayers
what you can do is instead of this line.
print(david.name)
do this:
for player in soccerplayers:
if player.name == "david":
david = player
I personaly recommend on pygame it is a library in python which allows to make high level games.
So in short im making a python game using Tkinter for some GUI, Thats not the problem.
when im running the code its freesing for 10 second. tell me how i can fix this using threading.
sorry i cant write a question properly
def timepas():
global time0
global money
global total_money
global Invests
global Invests_money
global stopInvest
global countlocal
while stopInvest:
countlocal = countlocal + 1
Invests_money = Invests * 2
money = money + Invests_money
print(money)
time.sleep(1)
if countlocal == count:
stopInvest = False
continue
def work_money():
global money
money += 1
def BankAcc():
global money
messagebox.showinfo("Your Bank Account", "You have $:" + str(total_money))
def Inves():
global Invests
global money
if money >= 10:
Invests = Invests + 1
money = money - 10
def stop_investing():
global count
global countlocal
global total_money
global money
count = 10
countlocal
total_money = total_money + money
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 12 months ago.
Improve this question
i have a little problem with my code.
How can i make global variable in my code and functions?
Example in my project ( it's simple game ) i want have a wallet - so its must be a global to earn and lose gold. In this code player is in minigame and can lose or earn more money but I would like this wallet to be variable throughout the file and react along with the minigame and other things in the code.
How to do it correctly?
leave_action = 'n'
print("Welcome in dice poker.")
while leave_action.lower() != 'y':
wallet = 5
bounty_from_dice = 0
if wallet == 0:
leave_action = input("Do you want leave from table? \nY. \nN. \n")
bet = int(input("Ile chcesz postawic? "))
wallet = wallet - bet
dice = sorted([ri(1, 6) for _ in range(5)])
print(dice)
for i in range(5):
print(f'{i + 1} throw a dice, the drawn value is {dice[i]} ')
result = pair(dice)
result2 = triple(dice)
resultf = full(dice)
resultp = poker(dice)
resultk = kareta(dice)
resultss = smallstreet(dice)
if result:
print('PAIR!')
bounty_from_dice = bounty_from_dice + 1
else:
print('No pair here')
if result2:
print('FAIR!')
bounty_from_dice = bounty_from_dice + 2
else:
print('No fair here')
if resultf:
print("FULL!")
bounty_from_dice = bounty_from_dice + 5
else:
print("No FULL here")
if resultk:
print("KARETA!")
bounty_from_dice = bounty_from_dice + 5
else:
print("No kareta here")
if resultp:
print("POKER!")
bounty_from_dice = bounty_from_dice + 10
else:
print("No poker here")
if resultss:
print("Smallstreet!")
bounty_from_dice = bounty_from_dice + 15
else:
print("No smallstreet here")
hazard_award = bounty_from_dice * int(bet)
wallet = wallet + hazard_award
print("Your win ratio is : " + str(bounty_from_dice))
print("You won from dice poker : " + str(hazard_award))
leave_action = input("Do you want leave from table? \nY. \nN. \n")
print("Your current gold: " + str(wallet))
if leave_action == 'y':
print("You left from dice poker.")
```
Assuming the code you shared is within a function, you can do multiple things to have a global wallet.
Pass as an argument
wallet = 5
def playDicePoker(wallet):
# [your code here but without the wallet=5 line in the while loop]
return wallet # to recover the new wallet value
# Usage:
wallet = playDicePoker(wallet)
Make it a global variable
This will need more work if you split the code over multiple file.
global wallet
wallet = 5
def playDicePoker():
global wallet
# [your code here but without the wallet=5 line in the while loop]
# Usage:
playDicePoker()
# now wallet is updated
Have a Player class
This will allow you to easily store other informations about your player as well, like the number of wins, the number of game played for each game, and so on
class Player:
def __init__(self, initialWallet):
self.wallet = initialWallet
def playDicePoker(player):
# [your code here but replacing wallet by player.wallet]
# (also no player.wallet = 5 since it's already initialized)
# Usage:
player = Player(5)
playDicePoker(player)
I have a variable in my code (named totalPrice) which will set itself to a price given and then when the user adds a product to their list it will add that price to totalPrice. However, when running it, it resets the variable to 0. I believe it has something to do with the placement of it as I have placed it inside a subprogram. I do not know what to do with it as I can't seem to find a place for it.
My code is as follows:
import csv
import sys
import re
import os
addItem = ""
gtinNum = ""
quantity = 0
restart = ""
f = open("ChocolateCSV.csv", "rt")
global receipt
receipt = open("receipt.txt", "w+")
def restart():
restart = input("Would you like to restart? Y/N")
if restart.lower() == "y":
gtinQuestion()
else:
global receiptCont
receiptCont = receipt.read()
receipt.close()
print(receiptCont)
print("Total Price: " + "%.2f" % round(totalPrice, 2))
sys.exit()
def quantityQuestion():
quantity = input("How much would you like?")
if quantity.isdigit() == False:
quantityQuestion()
global price
price = ""
global totalPrice
totalPrice = 0
with open("ChocolateCSV.csv", 'r') as file2:
for row in csv.reader(file2):
if str(gtinNum) in row:
receipt.write(str(row) + "\n")
receipt.write(str("- Quantity: " + quantity + "\n"))
price = float(row[2]) * int(quantity)
totalPrice += price
receipt.write("- Price: " + str("%.2f" % round(price, 2)) + "\n")
restart()
break
def gtinQuestion():
global gtinNum
gtinNum = input("Please enter the GTIN-8 Code of the product you would like to order:")
if gtinNum.isdigit() == False or len(gtinNum) != 8:
gtinQuestion()
elif gtinNum.isdigit() == True and len(gtinNum) == 8:
quantityQuestion()
gtinQuestion()
totalPrice is not global within restart().
also think of re-designing your code, there's a lot of dangerous recursion and global variables. E.g. if quantity.isdigit() == False: within quantityQuestion calls quantityQuestion and continues despite the error with the computation.
The whole point of having functions is to hide computation and variables inside. Use function parameters etc and learn clean python (try import this within a python console).
I am working on a code that is a clicker game. I have done 90% myself as I have never used Tkinter module before so was a learning project really, anyway to the problem:
I have just sorted the auto clicking function and a label in the window attached to a variable (the amount of cash), at the moment I have the label at a .pack(), and set so it creates a new label after every second. Obviously this will create confusion and isn't what you would expect from a game, so I wondered if there was a way to either:
1) Make the label update every time the variable (Amount of cash) updates (This would be Ideal if you can help me with this)
2)Delete the label with a line of code and then put the new label in with the current variables number (Not as good as the first, but would still be great to have this one if the first isn't possible)
Here is the code so far:
import time
from tkinter import *
root=Tk()
CPS=0
cash=0
mult=1
def blankLine():
for i in range(16):
print ("")
def infoprint():
print("Cash =",cash)
print("")
print("Each click is worth",mult,"cash")
print("")
print("CPS =",CPS)
blankLine()
def CashASecond():
global root
global cash
global CPS
cash += CPS
root.after(1000, CashASecond)
CashASecond()
def CashLabel():
label1=Label(root,text=cash)
label1.pack()
root.after(1000, CashLabel)
CashLabel()
def ManualClicker():
global cash
global mult
cash += 1*(mult)
infoprint()
ManualClickerButton=Button(root,text="Click",command=ManualClicker)
ManualClickerButton.pack()
class upgrades():
def DoubleManualClicker():
global cash
global mult
if cash < 1000:
print("Not enough cash, sorry")
elif cash>= 1000:
print ("Double clicks purchased!")
mult *= 2
cash = cash - 1,000
DoubleManualClickerButton=Button(root,text="Purchase double clicks",command=DoubleManualClicker)
DoubleManualClickerButton.pack()
DoubleManualClickerLabel=Label(root,text="Each click is worth twice as much, costs 1,000 \n")
DoubleManualClickerLabel.pack()
def clicker():
global cash
global mult
global CPS
if cash < 25:
print("Not enough cash, sorry")
elif cash >=25:
CPS += 1
print("CPS is now",CPS)
cash = cash - 25
ClickerButton=Button(root,text="Purchase auto clicker", command=clicker)
ClickerButton.pack()
ClickerLabel=Label(root,text="+1 CPS, costs 25 \n")
ClickerLabel.pack()
def SingleMachine():
global cash
global mult
global CPS
if cash < 50:
print("Not enough cash, sorry")
elif cash >= 50:
CPS += 3
print("CPS is now",CPS)
cash = cash - 50
SingleMachineButton=Button(root,text="Purcahse Single Cash Printer",command=SingleMachine)
SingleMachineButton.pack()
SingleMachineLabel=Label(root,text="+3 CPS, costs 50 \n")
SingleMachineLabel.pack()
def LoftOfCashPrinter():
global cash
global mult
global CPS
if cash < 100:
print("Not enough cash, sorry")
elif cash >= 100:
CPS += 5
print("CPS is now",CPS)
cash=cash-100
LoftOfCashPrinterButton=Button(root,text="Purchase a loft of cash printers",command=LoftOfCashPrinter)
LoftOfCashPrinterButton.pack()
loftlabel=Label(root,text="+7 CPS, costs 100 \n")
loftlabel.pack()
root.title("Cash Clicker! ALPHA! By George Hill")
root.geometry("500x900+900+0")
root.mainloop()
Thanks in advance :)
I had this problem before and the way I managed to fix this was to use events and bindings. Note that I am using classes and Application. e.g.
def Click(self, event):
self.Label['text'] = ....
....
self.Buy = Button(....)
self.Buy.grid(....)
self.Buy.bind('<Button>', self.Click)
self.Label = Label(....)
self.Label.grid(....)
I understand this code is very basic (it won't work) and the use of .... is to show where the use of variables and the like will be used. This is written purely to show you how to bind widgets.