Transfer variables from one function to the next in Python - python

I need help, these are the errors: what am I doing wrong?
Traceback (most recent call last):
File "python", line 64, in <module>
File "python", line 6, in walmart
File "python", line 28, in shopping
File "python", line 53, in drink
File "python", line 61, in total_price
NameError: global name 'price' is not defined
My code:
def walmart():
print "Hello welcome to the store!"
answer = raw_input("What's your name?")
if len(answer) > 0:
print "okay great %s, Lets go!...." % (answer)
shopping()
else:
print "Sorry try typing something"
walmart()
def shopping():
print "Ok lets get shopping"
shop_list = {"pizza" : 10.00 , "fries" : 15.00 , "burger" : 15.00}
print "Here are a list of food avaliable..."
print shop_list
ans1 = raw_input("Please select your item...").lower()
price = shop_list[ans1]
if "pizza" in ans1:
print "Your current price is... " + str(shop_list[ans1])
drink(price)
elif "burger" in ans1:
print "Your current price is... " + str(shop_list[ans1])
drink(price)
elif "fries" in ans1:
print "Your current price is... " + str(shop_list[ans1])
drink(price)
else:
print "Please type something on the list..."
shopping()
return price
def drink(price):
print "Okay let's pick you a drink"
drink_list = {"water" : 1 , "soda" : 2 , "tea" : 3}
print "Here is a list of drinks..."
print drink_list
ans2 = raw_input("Please type your choice here...").lower()
price_drink = drink_list[ans2]
if "water" in ans2:
print "Great healthy choice!"
total_price(price_drink)
elif "soda" in ans2:
print "Not that heaalthy but whatever floats your boat!"
total_price(price_drink)
elif "tea" in ans2:
print "OOOOO Tea great choice "
total_price(price_drink)
else:
print " Try again!"
drink(price)
return price_drink
def total_price(price_drink):
totalprice = drink(price) + shopping()
print "Thanks for shopping....\nHere is your total price..."
print totalprice
walmart()

The problem is your variable "price" is local variable and exist only inside the function, therefore in function total_price, variable "price" does not exist. You could fix by making variable "price" a global variable by defining it outside of functions.
# Before functions
price = 0
# your functions go here
def ......

You don't transfer variables from one function to another. If you want to use a variable in multiple function what you can do is define that variable globally and then use it in different functions
global_var = 10
def func1():
global global_var
#rest of the function
def func1():
global global_var
#rest of the function
UPDATE I was thinking about the comment below and I thought I should share this with you. Although in your case global variable seems like a good choice but keep in mind that using globals are not considered as good practice. So I would recommend that you use parameter passing instead. I would recommend you go through this http://www.learncpp.com/cpp-tutorial/4-2a-why-global-variables-are-evil/

Related

Custom python function is not running

names=["aaa","bbb","ccc","ddd","eee"]
itMarks=[90,98,87,98,78]
def printMainMenu():
print(" Main Menu")
print(" =========")
print(" (1)Add Student")
print(" (2)Search Student")
print(" (3)Delete Student")
print(" (4)List Student")
print(" (5)Exit")
choice = int(input("Enter Your choice[1-5]:"))
return choice
def searchStudent(names,itMarks):
name = input("Enter Name")
i = names.index(names)
print("Index is" + i)
def deleteStudent(student,itMarks):
name = input("Enter Name to remove")
student.remove(names)
print("Successfully Deleted" + names)
def removeStudent(names):
name = input("Enter name to remove")
name.remove(name)
print("Successfully deleted" + names)
def addStudent(names, itMarkas):
name = input("Enter Name")
names.append(names)
itMarks = input("Enter IT Marks")
itMarks.append(itMarks)
def listStudent(names, itMarks):
for i in range(0, len(names)):
print(names[1], "", itMarks[i])
names = []
itMarks = []
choice = 1
while choice >= 1 and choice <= 4:
choice = printMainMenu()
if choice == 1:
addStudent(names, itMarks)
elif choice == 2:
searchStudent(names, itMarks)
elif choice == 3:
deleteStudent(names, itMarks)
elif choice == 4:
listStudent(names, itMarks)
elif choice == 5:
print("Exit from the program")
else:
print("invalid choice!")
choice = 1
I am new to the programming in Python. The following Python code is written to do some tasks with the array. There are two array named names and itMarks. And there are some functions :
addStudent() - To add students to the array
searchStudent() - To search a student with in the list.
deleteStudent() - To delete the given student from the list.
listStudent() - To list out the all the names of the students in the list.
When the program runs, it asks to select a choice. Then it do the task according to their choice. But when I run this coding it shows the errors.
Please help me. Thanks in advance.
ERROR :
When I select the choice 1 (Add student) and input name after the error is yield.
Traceback (most recent call last):
File "C:\Users\BAALANPC\Desktop\new 3.py", line 59, in <module>
addStudent(names, itMarks)
File "C:\Users\BAALANPC\Desktop\new 3.py", line 42, in addStudent
name = input("Enter Name")
File "<string>", line 1, in <module>
NameError: name 'rtrt' is not defined
Their so many mistakes in naming
In addStudent
def addStudent(names, itMarkas):
name = input("Enter Name")
names.append(name) # names cant appent it should be name
itMark = input("Enter IT Marks") # here itmark not itMarks
itMarks.append(itMark)
In searchStudent
def searchStudent(names,itMarks):
name = input("Enter Name")
i = names.index(name) # try to find index of name not names
print("Index is" + i)
In deleteStudent
def deleteStudent(student,itMarks):
name = input("Enter Name to remove")
student.remove(name) # try to remove name not names
print("Successfully Deleted" + name)
after change above I run its running you have to also change the naming of the variable for all methods
Output
Main Menu
=========
(1)Add Student
(2)Search Student
(3)Delete Student
(4)List Student
(5)Exit
Enter Your choice[1-5]:1
add student
Enter Name"aaa"
Enter IT Marks111
Main Menu
=========
(1)Add Student
(2)Search Student
(3)Delete Student
(4)List Student
(5)Exit
Enter Your choice[1-5]:
I'm assuming this is the correct form:
def searchStudent(names,itMarks):
name = input("Enter Name")
i = names.index(name)
print("Index is" + i)
note that I changed names to name.
also the same mistake again
def deleteStudent(student,itMarks):
name = input("Enter Name to remove")
student.remove(name)
print("Successfully Deleted" + names)
tl;dr revise your code
searchStudent(): You shouldn't need the itMarks argument if you're not using it inside your function at all. names refers to the list of names, but you are really trying to search name. i is an integer that is attempting to be concatenated with a string. Not allowed. It should be str(i).
deleteStudent(): Better to keep your arguments consistent and use names rather than student. Again, same problem as above, should be .remove(name) and you shouldn't need the itMarks argument. print statement should refer to name not names.
removeStudent(): This is the same code as deleteStudent(), but not used, so not sure why it's there.
addStudent(): Typo in the argument, .append(name). You have a global variable and a local variable named the same thing, which are conflicting to the program. Change the input set to itMark and .append(itMark).
listStudent(): print statement has a typo, 1 should be i. Not sure why the empty string is included as well.
Underneath your function def's, you restate your variables as empty lists. This can lead to ValueErrors from a lot of your functions as you're trying to look something up or modify something in an empty list. Simply delete this code.
Additionally, any error will break your while loop. I suggest adding more booleans or using a try except clause to catch these errors.
Good luck!

How to call a variable inside a function then use it in another function

im doing a little project for myself to understand the function, if statement in python. i want to call the "name" inside the user function and use it in jungle function.
def user():
global name
name = raw_input("Whats your name?")
def jungle():
print name, "Please, Select your Enemy"
print '\n'.join(jungle_enemy)
enemy = raw_input('> ')
if enemy == "1":
print "The Lion Will eat you alive."
game_over()
exit_countdown()
elif enemy == "2":
print "The Jaguar will tear you apart."
game_over()
exit_countdown()
elif enemy == "3":
print "The Snake will eat you whole."
game_over()
exit_countdown()
else:
try_again("Are You Noob? \nNone of the Choice!")
jungle()
when i run this code. it gives me an error.
NameError : global name 'name' is not define.
Global variables are a bad idea in general. Better pass the variable to whoever needs it:
def user():
return raw_input("Whats your name?")
def jungle(name):
print name, "Please, Select your Enemy"
# etc.
and then call the functions like this
username = user()
jungle(username)
If you have to use global names, you need to use the global statement in all the functions that use that variable - so you need to add global name at the start of jungle(). But don't do that. See where global variables have taken JavaScript - you don't want to do that in Python.

python NameError, but I think the name is defined

Ok I going through LPTHW and writing a game. We are supposed to section the game up into different scripts to see how importing them works. I have 4 scripts: ex45.py executes the main code, Engine45.py is the engine, Locations45.py is the list of locations, and Maps45.py is what holds the map values and moves through locations.
The error I get when running is:
Traceback (most recent call last):
File "ex45.py", line 2, in
import Maps45
File "C:\Users\Raistlin\Python\Maps45.py", line 1, in
import Locations45
File "C:\Users\Raistlin\Python\Locations45.py", line 4, in
class Map(object):
File "C:\Users\Raistlin\Python\Locations45.py", line 6, in Map
'Gold_gym' : Gold_gym(),
NameError: name 'Gold_gym' is not defined
I don't understand why I am getting a Gold_gym is not defined when it is defined in Locations45.py.
Code blocks below:
ex45.py
import Engine45
import Maps45
import Locations45
a_map = Map('Gold_gym')
a_game = Engine(a_map)
a_game.run()
Engine45.py
class Engine(object):
def __init__(self, location_map):
print "Engine __init__ has location_map", location_map
self.location_map = location_map
def run(self):
current_location = self.location_map.opening_location()
print "Play's first scene", current_location
while True:
print "\n"('-' * 20)
next_location_name = current_location.use()
print "next location", next_location_name
current_location = self.location_map.next_location(next_location_name)
print "map returns new location", current_location
Locations45.py
from random import randint
from sys import exit
class Location(object):
def use(self):
print "This is not configured."
exit(1)
class Loser_gym(Location):
quips = [
'You are worthless, goodbye.'
'Thanks for trying noob.'
'Sex and candy, not today.'
]
def use(self):
print Loser_gym.quips[randint(0, len(self.quips)-1)]
exit(1)
class Gold_gym(Location):
def use(self):
print "Welcome to the Gold Gym. This gym will test your physical prowess."
print "Before you there is a large pool of water with a center platform."
print "On your person is a satchel, a whip, a hat, and a gun."
print "Your goal is to find the way out of the gym."
print "Acceptable inputs are satchel, whip, hat, or gun."
print "Good Luck."
action = raw_input("What do you do:> ")
if action == 'satchel':
print "You throw your satchel towards the center platform."
print "It does absolutely nothing. Try again."
return 'Gold_gym'
elif action == 'whip':
print "You use your whip somewhat akin to Indiana Jones."
print "You swing from a pipe and land squarely on the center platform."
print "You have survived this turmoil."
return 'Sapphire_gym'
elif action == 'hat':
print "You valiantly toss your hat toward the center platform."
print "Your hat is caught by a gust of wind and blows away."
print "You cannot survive without your hat."
return 'Loser_gym'
elif action == 'gun':
print "You shoot your about wildly in the air."
print "A ricochet hits you in the head and you die."
return 'Loser_gym'
else:
print "DOES NOT COMPUTE, TRY AGAIN."
return 'Gold_gym'
class Sapphire_gym(Location):
def use(self):
print "Welcome to the Sapphire gym, here your cognitive ability will be tested."
print "Just kidding there is no way to figure this out consistently."
print "Before you stands a door, the door has a small keypad on it."
print "Below the keypad is what appears to be a smart card reader."
print "On your way to the location you picked up two smartcards off the ground."
print "One is red and one is green."
print "Clearly you will need to use a smartcard and guess a code(3-digits)."
card = raw_input('Which card do you choose:> ')
if card == 'red':
print "A laser beam comes out of the door and cauterizes your brain."
return 'Loser_gym'
elif card == 'green':
code = '%d%d%d' % (randint(0,9), randint(0,9), randint(0,9))
guess = raw_input('What code do you enter:> ')
guesses = 0
while guess != code and guesses < 20 and guess != '123':
print "INCORRECT!"
guesses += 1
guess = raw_input('What code do you enter:> ')
if guess == code or guess == '123':
print "Nice guess noob! You may press onward."
return 'Cerulean_gym'
else:
print "WRONG! TOO MANY GUESSES! DIE INFERIOR BEING!"
return 'Loser_gym'
class Cerulean_gym(Location):
def use(self):
print "Welcome to the final gym, the Cerulean Gym!"
print "Before you is a 3x3 platform, your job is to cross the platform."
print "Be warned that each tile can trigger a trap."
print "Good luck!"
correct_square = ['3', '1', '2']
jump = raw_input("Square 1, 2, or 3?:> ")
jumps = 0
while jumps < 3:
if jump == correct_square:
print "Nice job! You picked the correct square!"
jump += 1
correct_square = correct_square[0+jump]
jump = raw_input("Square 1, 2, or 3?:> ")
jumps += 1
else:
print "YOU FAIL! Goodbye you puny infidel."
return 'Loser_gym'
print 'NICE JOB. YOU WIN ALL THE BASE!'
Maps45.py
import Locations45
class Map(object):
locations = {
'Gold_gym' : Gold_gym(),
'Sapphire_gym' : Sapphire_gym(),
'Cerulean_gym' : Cerulean_gym(),
'Loser_gym' : Loser_gym()
}
def __init__(self, start_location):
self.start_location = start_location
print "start_location in __init__", self.start_location
def next_location(self, location_name):
print "start_location in next_location"
val = Map.locations.get(location_name)
print "next_location returns", val
return val
def opening_location(self):
return self.next_location(self.start_location)
Help please?
When you:
import Locations45
that module is imported under the namespace Locations45
So when you call
Gold_gym()
It looks in Maps45 for that object, never knowing to look in Locations45.
Change the line to read:
locations = {
'Gold_gym' : Locations45.Gold_gym(),
'Sapphire_gym' : Locations45.Sapphire_gym(),
'Cerulean_gym' : Locations45.Cerulean_gym(),
'Loser_gym' : Locations45.Loser_gym()
If you just do import Locations45, it doesn't import each of the names - instead, it imports it as a group. You can refer to individual things within the group using a period:
'Gold_gym': Locations45.Gold_gym(),
'Sapphire_gym': Locations45.Sapphire_gym(),
'Cerulean_gym': Locations45.Cerulean_gym(),
'Loser_gym': Locations45.Loser_gym()
Alternatively, you could import all of the names specifically:
from Locations45 import Gold_gym, Sapphire_gym, Cerulean_gym, Loser_gym
which would make those names available without needing to use the prefix.

global name 'doc' is not defined, trouble withvcall from one function to annother

I'm having some trouble with a piece of code I'm currently writing.
With the following code I get the NameError: global name 'doc' is not defined.
def createHtml():
name = input("\nEnter the name for your HTML-page: ")
doc = open(name + ".html", 'w')
def createTitle():
print (t[0], file=doc) #<!DOCTYPE html>
print (t[1], file=doc) #<html>
print (t[2], file=doc) #<head>
title = input("Enter your title here: ")
print (" <title>",title,"</title>", file=doc)
print (t[3], file=doc) #</head>
I know it's because the doc is only defined in the createHtml-function. But how do I get it to work if I want the same doc to work when called in a different function? I cant leave it out of the createHtml-function because it will mess up my program since I have a menu which allows the user to choose from the different functions.
Like this:
while True:
menu = input("\nPress 1 to enter the file name for the HTML-page"
"\nPress 2 to enter title for the HTML-page"
"\nPress 3 to start entering code in body"
"\nPress 4 to exit\n")
if menu == "1":
createHtml()
elif menu == "2":
createTitle()
elif menu == "3":
createBody()
else:
print ("Good bye!")
break
doc.close()
And the doc is defined by the name variable in:
name = input("\nEnter the name for your HTML-page: ")
Is there anyway to get doc from the createHtml-function to my other functions?
What about wrapping the functions inside a class?
class HtmlBuilder(object):
def __init__(self):
self.doc = None
def createHtml(self):
name = input("\nEnter the name for your HTML-page: ")
self.doc = open(name + ".html", 'w')
def createTitle(self):
print (t[0], file=self.doc) #<!DOCTYPE html>
print (t[1], file=self.doc) #<html>
print (t[2], file=self.doc) #<head>
title = input("Enter your title here: ")
print (" <title>",title,"</title>", file=doc)
print (t[3], file=self.doc) #</head>
def Dispose(self):
self.doc.flush()
self.doc.close()
And just use it like this:
hb = HtmlBuilder()
while True:
menu = input("\nPress 1 to enter the file name for the HTML-page"
"\nPress 2 to enter title for the HTML-page"
"\nPress 3 to start entering code in body"
"\nPress 4 to exit\n")
if menu == "1":
hb.createHtml()
elif menu == "2":
hb.createTitle()
elif menu == "3":
hb.createBody()
else:
print ("Good bye!")
break
hb.Dispose()
At the end of the day, this is a perfect use case for Object Oriented Programming isn't it? After this, a lot of good improvements can be done.
For example:
Replace the print statements from the function to the outer code.
Make your methods testable.
Unit testing.
GOOD STUFF :D
Your function createHtml() function will need to return doc, which you can then pass to createTitle(). Something like this:
def createHtml():
name = input("\nEnter the name for your HTML-page: ")
doc = open(name + ".html", 'w')
return doc
So then in your while loop:
doc = createHtml()
and then you can pass it to the other functions:
createTitle(doc)
Note that it doesn't have to be called the same thing in each function.

How to have a versatile function call that can call different functions in Python?

I'm trying to make a text-based game in Python, however, code could get out of hand pretty quickly if I can't do one thing on one line.
First, the source code:
from sys import exit
prompt = "> "
inventory = []
def menu():
while True:
print "Enter \"start game\" to start playing."
print "Enter \"password\" to skip to the level you want."
print "Enter \"exit\" to exit the game."
choice = raw_input(prompt)
if choice == "start game":
shell()
elif choice == "password":
password()
elif choice == "exit":
exit(0)
else:
print "Input invalid. Try again."
def password():
print "Enter a password."
password = raw_input(prompt)
if password == "go back":
print "Going to menu..."
else:
print "Wrong password. You are trying to cheat by (pointlessly) guess passwords."
dead("cheating")
def shell(location="default", item ="nothing"):
if location == "default" and item == "nothing":
print "Starting game..."
# starter_room (disabled until room is actually made)
elif location != "default" and item != "nothing":
print "You picked up %s." % item
inventory.append(item)
location()
elif location != "default" and item == "nothing":
print "You enter the room."
location()
else:
print "Error: Closing game."
def location():
print "Nothing to see here."
# Placeholder location so the script won't spout errors.
def dead(reason):
print "You died of %s." % reason
exit(0)
print "Welcome."
menu()
First, an explanation on how my game basically works.
The game has a 'shell' (where input is done) which receives information from and sends information to the different 'rooms' in the game, and it stores the inventory. It can receive two arguments, the location and an eventual item to be added to the inventory. However, line 40-42 (the first elif block in 'shell') and line 43-45 (the last elif block in 'shell') are supposed to go back to whatever location the location was (line 42 and 45, to be exact). I've tried "%s() % location" but that doesn't work, it seems to only work when printing things or something.
Is there any way to do this? If not, even writing an engine for this game would be a nightmare. Or I'd have to make an entirely different engine, which I think would be a way better approach in such a case.
Sorry if I made any mistakes, first question/post ever.
elif location != "default" and item != "nothing":
print "You picked up %s." % item
inventory.append(item)
location()
elif location != "default" and item == "nothing":
print "You enter the room."
location()
I guess you want to call a function having its name. For that you need a reference to the module or class inside which it was defined:
module = some_module # where the function is defined
function = getattr(module, location) # get the reference to the function
function() # call the function
If the function is defined in the current module:
function = globals()[location]
function() # call the function
If I correctly understand what you want is something like this : player will enter a location name and you want to call the related method. "%s"()%location will not work, a string (that is what is "%s" is not callable).
Let's try an OOP way :
class Maze:
def __init__(self):
# do what you need to initialize your maze
def bathroom(self):
#go to the bathroom
def kitchen(self):
# go to the kitchen
def shell(self, location="", item=""):
if location == "" and item == "":
print "Starting game..."
# starter_room (disabled until room is actually made)
elif location and item:
print "You picked up %s." % item
inventory.append(item)
getattr(self, location)()
elif location and item == "":
print "You enter the room."
getattr(self, location)()
else:
print "Error: Closing game."
maze = Maze()
while True: # or whatever you want as stop condition
location = raw_input("enter your location :")
item = raw_input("enter your location :")
maze.shell(location=location, item=item)
I think you can use the getattr() method.
Example : You want to call method "helloword()" from module "test", you would then do :
methodYouWantToCall = getattr(test, "helloworld")
caller = methodYouWantToCall()
Hope it gives you a clue.

Categories