Python variables and function not defined - python

in order to fix the NameError (name not defined problem) I used the global keyword like this, but I don't think it's a good solution. And I want to put the last part of the code into a function (main()), but then again the not defined error occurs with purchase_item function, Can someone help me improve this code?
from RetailItem import RetailItem
class CashRegister:
global Item_List
global Cashier_List
global total
Item_List = [ RetailItem("Item 1","Jacket", 12, 59.95),
RetailItem("Item 2", "Designer Jeans", 40, 34.95),
RetailItem("Item 3", "Shirt", 20, 24.95) ]
Cashier_List = []
total = 0
def purchase_item(RetailItem):
global Cashier_List
Cashier_List.append(RetailItem)
def get_total():
global Cashier_List
global total
for o in Cashier_List:
total += o.getPrice()
return total
def show_items():
global Cashier_List
for o in Cashier_List:
print(o)
def clear():
global Cashier_List
del Cashier_List[:]
print("Here are available items:")
for o in Item_List:
print(o)
while True:
x = input("Select items by number to buy or enter \"n\" to finish shopping: ")
if x != "n":
try:
purchase_item(Item_List[int(x)-1])
print("ADDED!")
except ValueError:
print("Invalid number, try again!")
except IndexError:
print("Invalid number, try again!")
else:
break
print("......The total price is ${:0.2f}\n......This is your checkout items:".format(get_total()))
show_items()

Related

Unable to access what should be a global variable from function

from better_blackjack.preset_folder import build_deck
"""
This file is used to load all the things we need to run game.py (player_chips, deck, number of hands, bet amount)
"""
with open(r"C:\Hacks\python\programs\better_blackjack\Save_settings/chips.txt", "r") as file:
file_data = file.read()
if len(file_data) == 0:
player_chips = 1000000 # This will get altered (live amount of chips)
else:
try:
player_chips = int(file_data)
except ValueError:
print('File corrupted... restarting player chips ')
player_chips = 1000000
print(player_chips)
def get_num_hands():
try:
num_hands = (int(input('How many hands would you like ? ')))
get_bet_amount(num_hands)
except ValueError:
print('Use a valid number.')
get_num_hands()
def get_bet_amount(num_hands):
list_of_bets = []
for i in range(1, num_hands+1):
try:
print('How much would you like to bet on hand', i, ' Balance', player_chips)
bet_amount = int(input())
list_of_bets.append(bet_amount)
player_chips = player_chips - bet_amount
if player_chips < 0:
print('Bets exceed player balance... Restarting betting process')
player_chips = int(file_data)
get_bet_amount(num_hands)
return None # ends func
except ValueError:
print('Please use numbers only !... Restarting betting process')
player_chips = int(file_data)
get_bet_amount(num_hands)
return None # ends func
deck = build_deck.deck
get_num_hands()
I am getting the error 'player_chips' referenced before assignment on the following line - print('How much would you like to bet on hand', i, ' Balance', player_chips)
However it is defined before we call any of our functions how could this be ?
If a variable is modified inside a function, it is a local variable, and has nothing to do with the global variable of the same name. Hence player_chips inside get_bet_amount has nothing to do with the variable of the same name used at top level.
Add global player_chips inside your function to override this behavior.

how to print out something instead of geting an error when list.pop function is out of range?

My training course task is to make a shoppingcart, everything works as intented but I can't figure out the function pop out of range problem.
My code:
# -*- coding: cp1252 -*-
class Cart:
shoppingcart = []
def addstuff(self):
esine = input("What will be added?: ")
self.shoppingcart.append(esine)
def remove(self):
esine2 = input("Which item is deleted?: ")
self.shoppingcart.pop(int(esine2))
def main():
customer = Cart()
while True:
selection = input("Would you like to \n"
"(1)Add or \n"
"(2)Remove items or \n"
"(3)Quit: ")
if selection == "1":
customer.addstuff()
if selection == "2":
print("There are", len(customer.shoppingcart), "items in the list.")
customer.remove()
if selection == "3":
print("The following items remain in the list:")
for i in \
customer.shoppingcart:
print(i)
break
if selection > "3":
print("Incorrect selection.")
if __name__ == "__main__":
main()
Problem is while deleting(poping) an item that is out of range it gives an error but instead should print out "incorrect selection."
I tried adding if True and else argument into def remove part but that doesn't help.
Use try except blocks.
emptylist = []
try:
emptylist.pop()
except IndexError:
print('pop failed')
In your code:
def remove(self):
esine2 = input("Which item is deleted?: ")
try:
self.shoppingcart.pop(int(esine2))
except IndexError:
print('no item at index {}'.format(int(esine2))
Do note that pop(i) removes the item in the list at place i, not the item with value i.

How to pass a local list of lists to a global outside outside function? And how can i check if csv file DNE or is empty?

I know that moving the information in the file_open into global would fix my issue but my professor insisted that I move it all that code into a function which is why I'm having problems.
def file_open():
my_data = open('vgsales.csv')
data = csv.reader(my_data)
data_list = list(data)
my_data.close()
def year_release_count()->None:
"""
Tells the user how many games in a specific
year was released
"""
count = 0
year = input("Enter Year: ")
for index in range(len(data_list)):
if(data_list[index][3] == year):
count += 1
print(count)
def info()->None:
print("Which function would you like to run?")
print("Enter 1, to see the number of games released in specific year")
value = int(input("Enter: "))
if(value == 1):
year_release_count()
if __name__ == "__main__":
file_open()
info()

NameError: global name 'numKilos' is not defined

def inputKilos():
while True:
numKilos = float(raw_input("Enter a number of Kilometers. Enter 0 to end program. "))
if numKilos == 0:
break
else:
convert_kilos(numKilos)
return
def convert_kilos(numKilos):
numMiles = numKilos * 0.6214
print_output()
return
def print_output():
print numKilos, "kilometers eqauls", numMiles, "miles."
def main():
inputKilos()
main()
When I try to run the program it says "NameError: global name 'numKilos' is not defined" I don't know why it says numKilos isn't defined. numKilos is equal to the number that the user enters.
numKilos is a local variable in both inputKilos and convert_kilos, but not print_output. Local variables can only be accessed from within that function.
To pass variables around, use return <value> to return a value from the function, then collect it by using result = function(), or do the reverse by passing values into functions (like you did with convert_kilos.
Those are local variables not global.
You can try this:
#!/usr/bin/python
def inputKilos():
while True:
numKilos = float(raw_input("Enter a number of Kilometers. Enter 0 to end program. "))
if numKilos == 0:
break
else:
miles = convert_kilos(numKilos)
print_output(numKilos,miles)
return
def convert_kilos(numKilos):
numMiles = numKilos * 0.6214
return numMiles
def print_output(numKilos,numMiles):
print numKilos, "kilometers eqauls", numMiles, "miles."
inputKilos()
Or using global keyword:
#!/usr/bin/python
numKilos=0
numMiles=0
def inputKilos():
while True:
global numKilos
numKilos = float(raw_input("Enter a number of Kilometers. Enter 0 to end program. "))
if numKilos == 0:
break
else:
convert_kilos(numKilos)
print_output
def convert_kilos(numKilos):
global numKilos
global numMiles
numMiles = numKilos * 0.6214
def print_output:
global numKilos
global numMiles
print numKilos, "kilometers eqauls", numMiles, "miles."
inputKilos()
Here's a refactored version:
MILES_PER_KM = 0.621371
def get_float(prompt=''):
while True:
try:
return float(raw_input(prompt))
except ValueError:
pass
def main():
while True:
kms = get_float('Enter a distance in kms (or 0 to exit): ')
if kms:
miles = MILES_PER_KM * kms
print ' {} kilometers is {} miles.'.format(kms, miles)
else:
break
if __name__=='__main__':
main()

name 'times' is used prior to global declaration - But IT IS declared

I'm coding a small program to time and show, in a ordered fashion, my Rubik's cube solvings. But Python (3) keeps bothering me about times being used prior to global declaration. But what's strange is that IT IS declared, right on the beggining, as times = [] (yes, it's a list) and then again, on the function (that's where he complains) as times = [some, weird, list] and "globaling" it with global times. Here is my code, so you may analyse it as you want:
import time
times = []
def timeit():
input("Press ENTER to start: ")
start_time = time.time()
input("Press ENTER to stop: ")
end_time = time.time()
the_time = round(end_time - start_time, 2)
print(str(the_time))
times.append(the_time)
global times
main()
def main():
print ("Do you want to...")
print ("1. Time your solving")
print ("2. See your solvings")
dothis = input(":: ")
if dothis == "1":
timeit()
elif dothis == "2":
sorte_times = times.sort()
sorted_times = sorte_times.reverse()
for curr_time in sorted_times:
print("%d - %f" % ((sorted_times.index(curr_time)+1), curr_time))
else:
print ("WTF? Please enter a valid number...")
main()
main()
Any help would be very appreciated as I'm new in the world of Python.
The global declaration is when you declare that times is global
def timeit():
global times # <- global declaration
# ...
If a variable is declared global, it can't be used before the declaration.
In this case, I don't think you need the declaration at all, because you're not assigning to times, just modifying it.
From the Python documentation:
Names listed in a global statement must not be used in the same code block
textually preceding that global statement.
https://docs.python.org/reference/simple_stmts.html#global
So moving global times to the top of the function should fix it.
But, you should try not to use global in this situation. Consider using a class.
From the Python Docs
Names listed in a global statement must not be used in the same code block textually preceding that global statement.
This program should work but may not work exactly as you intended. Please take note of the changes.
import time
times = []
def timeit():
input("Press ENTER to start: ")
start_time = time.time()
input("Press ENTER to stop: ")
end_time = time.time()
the_time = round(end_time - start_time, 2)
print(str(the_time))
times.append(the_time)
def main():
while True:
print ("Do you want to...")
print ("1. Time your solving")
print ("2. See your solvings")
dothis = input(":: ")
if dothis == "1":
timeit()
elif dothis == "2":
sorted_times = sorted(times)
sorted_times.reverse()
for curr_time in sorted_times:
print("%d - %f" % ((sorted_times.index(curr_time)+1), curr_time))
break
else:
print ("WTF? Please enter a valid number...")
main()
import time
times = []
def timeit():
global times
input("Press ENTER to start: ")
start_time = time.time()
input("Press ENTER to stop: ")
end_time = time.time()
the_time = round(end_time - start_time, 2)
print(str(the_time))
times.append(the_time)
main()
def main():
print ("Do you want to...")
print ("1. Time your solving")
print ("2. See your solvings")
dothis = input(":: ")
if dothis == "1":
timeit()
elif dothis == "2":
sorte_times = times.sort()
sorted_times = sorte_times.reverse()
for curr_time in sorted_times:
print("%d - %f" % ((sorted_times.index(curr_time)+1), curr_time))
else:
print ("WTF? Please enter a valid number...")
main()
main()
that should work. The "global[varname]" have to be at start from definition ;)
For the main program, you can declare it on the top. Ther will be no warning. But, as said, the global mention is not useful here. Each variable put in the main program is in the global space. In functions, you must declare that you want use the global space for it with this keyword.
I got the same error below:
SyntaxError: name 'x' is used prior to global declaration
When trying to use the local and global variables x in inner() as shown below:
x = 0
def outer():
x = 5
def inner():
x = 10 # Local variable
x += 1
print(x)
global x # Global variable
x += 1
print(x)
inner()
outer()
And, when trying to use the non-local and global variables x in inner() as shown below:
x = 0
def outer():
x = 5
def inner():
nonlocal x # Non-local variable
x += 1
print(x)
global x # Global variable
x += 1
print(x)
inner()
outer()
So, I renamed x to y for the local variable as shown below:
x = 0
def outer():
x = 5
def inner():
y = 10 # Here
y += 1 # Here
print(y) # Here
global x
x += 1
print(x)
inner()
outer()
Then, the error was solved as shown below:
11
1
And, I renamedx to y for the non-local variable as shown below:
x = 0
def outer():
y = 5 # Here
def inner():
nonlocal y # Here
y += 1 # Here
print(y) # Here
global x
x += 1
print(x)
inner()
outer()
Then, the error was solved as shown below:
6
1

Categories