Variable in function python [closed] - python

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)

Related

Attribute error from an object that isn't called upon [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am working on a Mastermind game in python, and one of my classes is called the Game class. This runs a 'setup' of the game as such (like finding the player count, player names etc.). However, one of my methods which checks the name inputted against a player list previously defined/stored in a separate class is bringing up an AttributeError when I try to append the name to a new list created in my Game class. This is what my Game class currently looks like:
class WorldOfMastermind:
"""WOM class - Runs whole game, takes results from other classes and stores them (namely players and their scores)"""
def __init__(self):
self.__playerList = []
self.__playerDetails = dict()
def run(self):
"""Run method - holds the menu screen - allows for the user to add player, show scores, play game or quit"""
cpuNames = ComputerPlayer.addDetails(self)
self.__playerList.extend((cpuNames))
start = input('What would you like to do?\n (r) register a new user\n (s) show the score board\n (p) play a game\n (q) quit\n')
if start == 'r':
tempName = HumanPlayer.addDetails(self)
for i in self.__playerList:
if i == tempName:
print('')
print('Sorry, that name already exists')
print('')
self.run()
self.__playerList.append(tempName)
self.__playerDetails[tempName] = [0, 0, float(0)]
print('Welcome,', tempName + '!')
print('')
self.run()
elif start == 's':
self.printScoreBoard()
elif start == 'p':
print('Let\'s play the game of Mastermind!')
Game.startPrep(self, self.__playerList)
elif start == 'q':
print('Thank you for playing the World of Mastermind!')
exit()
else:
print('\nSorry, that is an invalid input')
print('')
self.run()
def printScoreBoard(self):
""" Print the scoreboard by iterating through the dictionary """
print('=====================================')
print('Name Score Games Average ')
print('=====================================')
for i in self.__playerDetails:
print('{:<15} '.format(i), '{:>5}'.format(self.__playerDetails[i][0]), '{:>5}'.format(self.__playerDetails[i][1]), '{:>7}'.format(self.__playerDetails[i][2]))
print('=====================================\n')
self.run()
class Game:
"""Begin the initialization of the game and return results to WOM class"""
def __init__(self, playerCount):
self.__playerCount = playerCount
self.__playingList = []
def startPrep(self, playerList):
"""Prepares the game"""
Game.getPlayerCount(self)
Game.getPlayerNames(self, playerList)
def getPlayerCount(self):
"""Gathers the number of players"""
while True:
try:
self.__playerCount = int(input('How many players (2-4)?'))
except ValueError:
print('Only numbers allowed')
else:
if self.__playerCount < 2 or self.__playerCount > 4:
print('Player count must be between 2-4 inclusive')
else:
break
def getPlayerNames(self, playerList):
"""Gathers names of players and puts them into a list"""
while True:
if self.__playerCount == 2:
while True:
player1 = input('What is the name of player #1?')
if player1 in playerList:
print('successful')
self.__playingList.append(player1)
break
else:
print('Invalid username')
while True:
player2 = input('What is the name of player #2?')
if player2 in playerList:
if player2 not in self.__playingList:
print('successful')
self.__playingList.append(player2)
break
else:
print(player2, 'is already in the game.')
else:
print('Invalid username')
break
Where I feel the error is coming from is in the calling of the getPlayerNames method. As it takes a parameter (the player list from another class), this is purely to check that the name inputted is actually in the game, and if so it prints 'successful' (which it does) but when trying to append the inputted name into the new 'playingList' it brings up the error. I'm not sure why this is as the append line doesn't have any need to reference attributes from another class. Any advice would be appreciated thanks!
Your code works for me, formatted as below.. If I run the following, it asks for the player count and makes sure the names you give are in the eligible player list.
class Game:
"""Begin the initialization of the game and return results to WOM class"""
def __init__(self, playerCount=0):
self.__playerCount = playerCount
self.__playingList = []
def startPrep(self, eligible):
"""Prepares the game"""
self.getPlayerCount()
self.getPlayerNames(eligible)
def getPlayerCount(self):
"""Gathers the number of players"""
while True:
try:
self.__playerCount = int(input('How many players (2-4)?'))
except ValueError:
print('Only numbers allowed')
else:
if self.__playerCount < 2 or self.__playerCount > 4:
print('Player count must be between 2-4 inclusive')
else:
break
def getPlayerNames(self, playerList):
"""Gathers names of players and puts them into a list"""
for i in range(self.__playerCount):
while True:
s = 'What is the name of player #%d? '%(i+1)
player = input(s)
if player in playerList:
print('successful')
self.__playingList.append(player)
break
else:
print('Invalid username')
g = Game()
g.startPrep(['bob','bill'])

Writing to a file in a for loop and def is not defined

In Python, This can not loop many times and cannot find ID number in def.
Every time I try to run the program I get the error
"NameError: name 'askname' is not defined"
and in textfile Keep only the latest data
I expect the output of #def new_booking to be Keep data in files continuously but the actual output is kept data in files just one sentence
I expect the output of #def pre_booked to be Extract data from a file but the actual output is
"NameError: name 'askname' is not defined"
import random
# total=0
# people=0
total1 = 0
total2 = 0
# mini bar
def mini_bar():
mini_bar_total = 0
print("£50 for the Bar")
askbar = input("Would you like a mini bar? Y/N")
if askbar.upper() == "Y":
mini_bar_total = mini_bar_total + 50
return mini_bar_total
# breakfast
def breakfast(people, asknights):
breakfast_total = 0
print("£25 for breakfast")
askdinner = input("Would you like dinner? Y/N")
if askdinner.upper() == "Y":
breakfast_total = (people * 25) * asknights
print("total: £", breakfast_total)
return breakfast_total
# dinner
def dinner(people, asknights):
dinner_total = 0
print("£25 for Dinner")
askdinner = input("Would you like dinner? Y/N")
if askdinner.upper() == "Y":
dinner_total = (people * 25) * asknights
return dinner_total
# number customers
def num_customers():
customer_total = 0
print("£50 an Adult")
askadult = int(input("How many adults? "))
customer_total = askadult * 50
print("total: £", customer_total)
print("£25 a Child")
askchild = int(input("How many children? "))
customer_total = (askchild * 25) + customer_total
print("total: £", customer_total)
return customer_total, askadult, askchild
# number of nights (multiplier)
def num_nights(customer_total):
nights_total = 0
waiting = True
while waiting == True:
try:
asknights = int(input("How many nights are you staying for? "))
nights_total = customer_total * asknights
print("total: £", nights_total)
break
except ValueError:
print("invalid input!")
return nights_total, asknights
# New Booking *********
def new_booking():
askname = str(input("Please enter your name? "))
idnumber = random.randint(100, 999)
customer_total, numAdults, numChild = num_customers()
Num_people = numAdults + numChild
nights_total, asknights = num_nights(customer_total)
askbar = mini_bar()
askbreakfast = breakfast(Num_people, asknights)
askdinner = dinner(Num_people, asknights)
total = askdinner + askbreakfast + askbar + asknights
detailslist = (idnumber, askname, numAdults, numChild, asknights, askbar, askbreakfast, askdinner)
for i in detailslist:
f = open('newbooking.txt', 'w')
f.write(str(detailslist) + '\n')
print(i)
print("your total amount is: £", total)
print("your Name & ID number is: ", askname, idnumber)
# Pre booking ***** is not defind
def pre_booked():
name = input("enter your name or ID number: ")
if name == (askname) or (idnumber):
detailslist = [idnumber, askname, askadult, askchild, asknights, askbar, askbreakfast, askdinner]
for i in detailslist:
print(i)
print("total: £", total)
# main menu, start of program.
def main_menu():
print("##################### WELCOME TO BAY HOTEL ###########################")
print('''Please see what is available at the Hotel,\nAdult Prices per night: £50pp,\nChild price: £25pp,\nMiniBar price: £50 per room,\nBreakfast: £20pp,\nDinner: £25pp''')
while True:
prebook = input("Have you booked? Y/N")
if prebook.upper() == "N":
new_booking()
elif prebook.upper() == "Y":
pre_booked()
main_menu()
- I expect the output of #def new_booking to be Keep data in files continuously but the actual output is keep data in files just one sentence
- I expect the output of #def pre_booked to be Extract data from file but the actual output is "NameError: name 'askname' is not defined"
I think it's because your way to writing data in files.
Working with files has 3 step:
1) Opening file
2) Read [from] / Write [to] file
3) Closing file
third step is what you don't handled it.
You want to write a list in file and you are opening that file in each iteration. It's not a good idea (opening and closing files have their overhead) when you can do it once.
I changed some of your new_booking function and wrote it here:
# New Booking *********
def new_booking():
askname = str(input("Please enter your name? "))
idnumber = random.randint(100, 999)
customer_total, numAdults, numChild = num_customers()
Num_people = numAdults + numChild
nights_total, asknights = num_nights(customer_total)
askbar = mini_bar()
askbreakfast = breakfast(Num_people, asknights)
askdinner = dinner(Num_people, asknights)
total = askdinner + askbreakfast + askbar + asknights
detailslist = (idnumber, askname, numAdults, numChild, asknights, askbar, askbreakfast, askdinner)
# I handled opening and closing file with [python with statement]
# It close files automatically at the end
with open('newbooking.txt', 'w') as f:
for i in detailslist:
f.write(str(detailslist) + '\n')
print(i)
print("your total amount is: £", total)
print("your Name & ID number is: ", askname, idnumber)
The problem here is that you havent actually defined askname in your pre_booked() function so you cant compare against it. In new_booking() you are asking for the username with askname = str(input("Please enter your name? ")) however in the pre_booked() case you dont so you cant use it there without first getting the values from somewhere.
Seeing that you save the new_booking() to a file you probably want to load the data from your file like this:
accounts = []
with open(r"<FILEPATH", "r") as booking_file:
for line in booking_file:
accounts.append(line)
In your new_booking function it might be better to put all the related data in line by line or maybe even use dicts so you can later be sure which values belong together instead of writing all the values into their own line. So you might want to do this instead:
with open('newbooking.txt', 'w') as booking_file:
f.write(detailslist)
Then you can read line by line and possibly use ´eval()´ to get a list or dictionary right from your string or atleast you know the values in one line belong together later on.
You might also want to consider using "a" for append instead of w for write in your bookings file depending if you want to have multiple booking values in your file or just the one.

Problems transferring information from one part of a function to another

While working on my program I have run into a problem where the information stored in Menu option 1 is not being transferred to Menu option 2. As you can see it is correctly stored when in menu one. When it returns to go to menu option 2 its like it never went to option 1.
update #1:
some suggestions I've had is to understand scope? from what I can tell the program is not passing the data along to its parent program even though I've typed out return in each of the definitions.
#Must be able to store at least 4 grades
#Each class can have up to 6 tests and 8 hw's
#Weighted 40%*testavg 40% hw average attendance is 20%
#User must be able to input a minimum grade warning
#after each test the your program must calculate the students average and issue warning if necessary
##Define the Modules##
import math
def menu (a): #2nd thing to happen
menuend = 'a'
while menuend not in 'e':
menuend = raw_input("Type anything other then 'e' to continue:\n")
print "What would you like to do ?"
menudo = 0
print "1 - Enter Courses\n2 - Select Course to Edit\n3 - Save File\n4 - Load File\n5 - Exit\n"
menudo = input("Enter Selection:")
if (menudo == 1):
menuchck = 0
menuchck = raw_input("\nYou have entered #1 (y/n)?:\n")
if menuchck in ["Yes","yes","y","Y"]:
x = m1()
else:
print "I'm sorry,",nam,",for the confusion, lets try again\n"
menu()
elif (menudo == 2):
menuchck1 = 0
menuchck1 = raw_input("\nYou have entered #2 (y/n)?:\n")
if menuchck1 in ["Yes","yes","y","Y"]:
x = m2()
else:
print "I'm sorry,",nam,",for the confusion, lets try again\n"
menu()
elif (menudo == 3):
print "Entered 3"
elif (menudo == 4):
print "Entered 4"
else:
print "Anything Else Entered"
def course(): #3rd thing to happen
b = {}
while True:
while True:
print "\n",name,", please enter your courses below ('e' to end):"
coursename = raw_input("Course Name:")
if (coursename == 'e'):
break
will = None
while will not in ('y','n'):
will = raw_input('Ok for this name : %s ? (y/n)' % coursename)
if will=='y':
b[coursename] = {}
print "\n",name,", current course load:\n",b
coursechck = None
while coursechck not in ('y','n'):
coursechck = raw_input("Are your courses correct (y/n)")
if coursechck =='y':
return b
else:
b = {}
print
##Menu Options##
def m1():
a = course()
return a
def m2():
print "Excellent",name,"lets see what courses your enrolled in\n"
print x
return x
###User Input Section###
name = raw_input("Enter Students Name:\n")
a = {}
menu(a)
raw_input("This is the end, my only friend the end")
In your if-elif blocks in the do==1 case, you write m1(), but for the last case, you write x=m1(). You should have the latter everywhere (by typing m1() you only run the function, but do not store the returned x anywhere).
By the way, you can avoid this if-elif confusion using if chck in ["Yes","yes","Y","y"]:

Python custom modules - error with example code

I am reading the book "Python Programming for the Absolute Beginner (3rd edition)". I am in the chapter introducing custom modules and I believe this may be an error in the coding in the book, because I have checked it 5 or 6 times and matched it exactly.
First we have a custom module games.py
class Player(object):
""" A player for a game. """
def __init__(self, name, score = 0):
self.name = name
self.score = score
def __str__(self):
rep = self.name + ":\t" + str(self.score)
return rep
def ask_yes_no(question):
""" Ask a yes or no question. """
response = None
while response not in ("y", "n"):
response = input(question).lower()
return response
def ask_number(question, low, high):
""" Ask for a number within a range """
response = None
while response not in range (low, high):
response = int(input(question))
return response
if __name__ == "__main__":
print("You ran this module directly (and did not 'import' it).")
input("\n\nPress the enter key to exit.")
And now the SimpleGame.py
import games, random
print("Welcome to the world's simplest game!\n")
again = None
while again != "n":
players = []
num = games.ask_number(question = "How many players? (2 - 5): ", low = 2, high = 5)
for i in range(num):
name = input("Player name: ")
score = random.randrange(100) + 1
player = games.Player(name, score)
players.append(player)
print("\nHere are the game results:")
for player in players:
print(player)
again = games.ask_yes_no("\nDo you want to play again? (y/n): ")
input("\n\nPress the enter key to exit.")
So this is exactly how the code appears in the book. When I run the program I get the error IndentationError at for i in range(num):. I expected this would happen so I changed it and removed 1 tab or 4 spaces in front of each line from for i in range(num) to again = games.ask_yes_no("\nDo you want to play again? (y/n): ").
After this the output is "Welcome to the world's simplest game!" and that's it.
I was wondering if someone could let me know why this is happening?
Also, the import games module, is recognized in Eclipse after I added the path to PYTHONPATH.
I actually have this book myself. And yes, it is a typo. Here is how to fix it:
# SimpleGame.py
import games, random
print("Welcome to the world's simplest game!\n")
again = None
while again != "n":
players = []
num = games.ask_number(question = "How many players? (2 - 5): ", low = 2, high = 5)
for i in range(num):
name = input("Player name: ")
score = random.randrange(100) + 1
player = games.Player(name, score)
players.append(player)
print("\nHere are the game results:")
for player in players:
print(player)
again = games.ask_yes_no("\nDo you want to play again? (y/n): ")
input("\n\nPress the enter key to exit.")
All I did was indent num 4 spaces and lined it up with the first for-loop.
You have an infinite loop here:
again = None
while again != "n":
players = []
If this is exactly the way it's printed in the book, the book does have an error.
You've got these two lines:
num = games.ask_number(question = "How many players? (2 - 5): ", low = 2, high = 5)
for i in range(num):
The second one is more indented than the first. That's only legal if the first one is a block-introducer like a for or while or if. Since it's not, this is an IndentationError. And that's exactly what Python is telling you.
(It's possible that you've copied things wrong. It's also possible that you're mixing tabs and spaces, so it actually looks right in your editor, but it looks wrong to Python. But if neither of those is true, the book is wrong.)
So, you attempted to fix it by dedenting everything from that for loop on.
But when you do that, only one line is still left under the while loop:
while again != "n":
players = []
There's nothing that can possibly change again to "n", so this will just spin forever, doing nothing, and not moving on to the rest of the program.
So, what you probably want to do is to indent the num = … line to the same level as the for i… line, so both of them (and all the stuff after) ends up inside the while loop.

Python Not Running Code [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
I wrote a python script which just stopped working suddenly. I'm not sure why so any help would be appreciated. The console just doesn't display anything. I called the function start on the bottom but no luck.
import random
year = 1
our_score = 0
their_score = 0
games_played = 0
#opponent's strategy:
def op_strategy():
for i in range (0,1):
rand = random.randint(0,1)
if rand == 0:
return "war"
if rand == 1:
return "peace"
def start():
global our_score, their_score, year
print "====="
print "Year " + str(year)
print "Our Score: " + str(our_score)
print "Their Score: " + str(their_score)
print ""
strategy = raw_input("What is your strategy this year? ")
inputs(strategy)
def inputs(strategy):
our_score = 0
global our_score, their_score, year
if str(strategy) == "peace" or str(strategy) == "war":
print "You chose: " + str(strategy)
op_strat = str(op_strategy())
print "They chose: " + op_strat
if str(strategy) == "war" and str(op_strat) == "war":
print ">>> Everyoner to arms!"
our_score = our_score + 1
their_score = their_score + 1
year = year + 1
elif str(strategy) == "peace" and str(op_strat) == "peace":
print ">>> Peace for everyone!"
our_score = our_score + 3
their_score = their_score + 3
year = year + 1
elif str(strategy) == "peace" and str(op_strat) == "war":
print ">>> They crushed us!"
our_score = our_score
their_score = their_score + 5
year = year + 1
elif str(strategy) == "war" and str(op_strat) == "peace":
print ">>> We crushed them!"
our_score = our_score + 5
their_score = their_score
year = year + 1
if str(year) == "11":
print "====="
print "Final"
print str(our_score)
print str(their_score)
if our_score > their_score:
print ">>>>> We win! <<<<<"
if their_score > our_score:
print ">>>>> They win! <<<<<"
if their_score == our_score:
print ">>>>> It's a tie! <<<<<"
play = raw_input("Play again?")
if play == "y":
start()
if play == "n":
pass
else:
play = raw_input('Invalid response. Please enter "y" or "n".')
if str(strategy) != "peace" and str(strategy) != "war":
strategy = raw_input('Invalid strategy. Enter "peace" or "war": ')
inputs(strategy)
start()
start()
The code is executing, but it is stuck at the raw_input call, and not printing until it completes, which of course the user does not know to do because nothing has printed.
The buffer is not automatically flushed. If you start python with the -u option, the buffer will be flushed with the raw_input call, and the prompt will be apparent.
Load this up in Idle and you'll see the following error:
SyntaxError: name 'our_score' is assigned to before global declaration (, line 1)
One these lines:
def inputs(strategy):
our_score = 0
global our_score, their_score, year
As detailed here:
If the global statement occurs within a block, all uses of the name
specified in the statement refer to the binding of that name in the top-level
namespace... i.e. the namespace of the module containing the code block
You've assigned to a local variable our_name and then you're telling the function to use a global variable of the same name. There should be no problems after fixing this.

Categories