NameError: name 'warehouse_initial_quantity_aircondSec' is not defined - python

remaining code:
if id_parts == "EBS04":
piston_quantity_warehouse = warehouse_initial_quantity_aircondSec + order_from_supplier
return piston_quantity_warehouse
elif id_parts == "BWBS03":
door_quantity_warehouse = warehouse_initial_quantity_bodyworkSec + order_from_supplier
return door_quantity_warehouse
else:
print("No such id")
else:
print("Wrong supplier")
else:
print("Wrong supplier")
print(warehouseUpdateSupplier)
updateBiosWarehouseInventory()
Input:
Enter Supplier name: tab
The id of the part: abs01
How many orders from supplier: 2
Output:
NameError: name 'warehouse_initial_quantity_aircondSec' is not defined
Can anyone help me with this >< Been spending hours on it :\ Thank You so much

The variable warehouse_initial_quantity_aircondSec is local to the method initial_quantity(), you're calling it, but that doesn't give you the variable you have to store it. The name may be different
def initial_quantity():
warehouse_initial_quantity_aircondSec = 1000
return warehouse_initial_quantity_aircondSec
def updateBiosWarehouseInventory():
warehouse_initial_quantity_aircondSec = initial_quantity()
...
You can even do
def initial_quantity():
return 1000

Related

check_balance() function not giving out correct values / values are not stored

I'm new to Python and I'm writing a bank-teller project.
I'm creating a function called check_balance() to check the two types of balances and two other functions one named make_deposit() and the other make_withdrawal().
The thing is my check_balance() function is not giving out the supposedly-updated balances...seems like the make_deposit function did not store the values at all. I'm copy-pasting all codes below, please let me know why it's not working properly. Thanks !!
Code below:
checking_balance - 0
savings_balance = 0
def check_balance(account_type, checking_balance, savings_balance):
if account_type == "savings":
balance = savings_balance
elif account_type == "checking":
balance = checking_balance
else:
return "Unsuccessful, please enter \"checking\" or \"savings\""
balance_statement = "Your " + account_type + " balance is "+ str(balance)
return balance_statement
def make_deposit(account_type, amount, checking_balance, savings_balance):
deposit_status = ""
if amount > 0:
if account_type == "savings":
savings_balance += amount
deposit_status = "successful"
elif account_type == "checking":
checking_balance += amount
deposit_status = "successful"
else:
deposit_status = "Unsuccessful, please enter \"checking\" or \"savings\""
else:
deposit_status = "unsuccessful, please enter an amount greater than 0"
deposit_statement = "Deposit of " + str(amount) + " to your " + account_type + " account was " + deposit_status + " ."
print(deposit_statement)
return checking_balance, savings_balance
print(make_deposit("savings", 10, checking_balance, savings_balance)) ---> this gives a savings_balance of 10.
print(check_balance("savings", checking_balance, savings_balance)) ---> Now this gives 0 instead of 10.
I would recommend creating a class for this project and putting your functions in there. You can modify the code below to better fit your needs. This is a really good article showing how to use a class for a banking project (ironically enough) https://www.geeksforgeeks.org/python-program-to-create-bankaccount-class-with-deposit-withdraw-function/
class Bank_Account:
def __init__(self):
self.Chekingsbalance=0
self.Savingsbalance=0
print("Hello!!! Welcome to the Python bank")
def Deposit(self, AccountType):
if AccountType == "checking":
amount=float(input("Enter amount to be Deposited: "))
self.Chekingsbalance += amount
print("\n Amount Deposited into checking:",amount)
if AccountType == "savings":
amount=float(input("Enter amount to be Deposited: "))
self.Savingsbalance += amount
print("\n Amount Deposited into savings:",amount)
def Balance(self, AccountType):
if AccountType == "savings":
print("\n Net Available Balance=",self.Savingsbalance)
if AccountType == "checking":
print("\n Net Available Balance=",self.Chekingsbalance)
# Driver code
# creating an object of class
s = Bank_Account()
StopBanking = False
while StopBanking ==False:
tasks = (input('What would you like to do? enter [deposit], [check balance], or [quit]'))
# Calling functions with that class object
if tasks == 'deposit':
account = (input('deposit into which account? enter [checking] [savings]'))
if account == 'checking':
s.Deposit(account)
if account == 'savings':
s.Deposit(account)
if tasks == 'check balance':
accountbalance = (input('check balance of which account? enter [checking] [savings]'))
if accountbalance == 'checking':
s.Balance(accountbalance)
if accountbalance == 'savings':
s.Balance(accountbalance)
if tasks == 'quit':
print("thanks for banking!")
StopBanking =True

How can I check if a string has personalized errors?

I'm trying to make a program where I input a name and a surname and the code checks if the name is invalid (list of invalidiations below). If it has any invalidations, it asks me to say the name again and presents me a list of all the invalidations.
Invalidations list (I'll show the code version too):
- The name has digits
- The name has symbols
- The name has no spaces
- It has more then one space
- One of the names is either too short or too long
- The first letter of the name is a space
- The last letter of the name is a space
I can't use exceptions here, because these are not code erros. I've made it with Ifs, but it got to a point where there a simply lots of Ifs for it to be viable.
def has_digits(name):
digits = any(c.isdigit() for c in name)
if digits == True:
return True
print("Your name has digits.")
else:
return False
def has_symbols(name):
symbols = any(not c.isalnum() and not c.isspace() for c in name)
if symbols == True:
return True
print("Your name has symbols.")
else:
return False
def has_no_spaces(name):
spaces = any(c.isspace() for c in name)
if not spaces == True:
return True
print("You only gave me a name.")
else:
return False
def many_spaces(name):
m_s = name.count(' ') > 1
if m_s == True:
return True
print("Your name has more than one space.")
else:
return False
def unrealistic_length(name, surname):
length= (float(len(name)) < 3 or float(len(name)) > 12) or float(len(surname)) < 5 or float(len(surname) > 15)
if length == True:
return True
print("Your name has an unrealistic size.")
else:
return False
def first_space(name):
f_s = name[0] == " "
if f_s == True:
return True
print("The first letter of your name is a space.")
else:
return False
def last_space(name):
l_s = name[-1] == " "
if l_s == True:
return True
print("The last letter of your name is a space.")
else:
return False
name = "bruh browski"
namesplit = name.split(" ")
name1 = namesplit[0]
name2 = namesplit[1]
print(has_digits(name))
print(has_symbols(name))
print(has_no_spaces(name))
print(many_spaces(name))
print(unrealistic_length(name1, name2))
print(first_space(name))
print(last_space(name))
Maybe the prints shouldn't be in the defs themselves. I don't know. I'm almost sure doing a for loop is the way to go, but I just can't imagine how to do it.
Result:
False
False
False
False
False
False
False
The methods you've used to define exactly what counts as each "invalidation" will have to stay, unless you can replace them with something else that does the same thing. But you can check all of those conditions at once using a generator expression:
if any(is_invalid(name) for is_invalid in [
has_digits, has_symbols, has_no_spaces, many_spaces, unrealistic_length, first_name, last_name
]):
# then this string is invalid
# otherwise, all of those returned false, meaning the string is valid.
You can then use that condition to determine when to stop asking the user, or however else you need to.
If you wanted to not individually define all those functions, you could also maybe use lambdas to do the same thing.
As a sidenote, before actually using this in production for checking the validity of names, I advise having a look at the list of Falsehoods Programmers Believe about Names. It's a fun read even if it's not relevant to your use case, though.
You could have a single function which calls all of your other functions and handles it appropriately.
def master_verify(name):
# Put all your verify functions in the list below.
verify_funcs = [has_digits, has_symbols, has_no_spaces, many_spaces,
unrealistic_length, first_space, last_space]
# It will return True if any your functions return True. In this case,
# returning True means the name is invalid (matching your other
# function design). Returning False means the name is valid.
return any(is_invalid(name) for is_invalid in verify_funcs)
Since you mentioned you want the program to find any name errors and ask the user to try again, we can write a loop to handle this.
def get_name():
while True:
# Loop until you get a good name
name = input("Enter your name: ").strip()
if master_verify(name):
# Remember, if True this means invalid
print("Invalid name. Try again.")
continue # continue jumps to the top of a loop, skipping everything else.
return name # Will only get here if the name is valid.
I also suggest you should do the name and surname split inside your unrealistic_length function.
Then, all you need to do is
name = get_name()
# All of the validation has already happened.
print(f"The correct and validated name is: {name}")
Last but not least, anything in a function after a return is unreachable. So a lot of your prints will never happen. Put the print statements before your return.
Alright. I've managed to do it by myself. I still fill there's a better way to do it, but this is the way I found.
errors_list = []
print("Hi. Tell me your first and last name.")
def choose_name(name):
global fname
global sname
fname = ""
sname = ""
global errors_list
try:
no_letters = any(c.isalpha() for c in name)
no_spaces = name.count(" ") == 0
digits = any(c.isdigit() for c in name)
symbols = any(not c.isalnum() and not c.isspace() for c in name)
many_spaces = name.count(" ") > 1
first_space = name[0] == " "
last_space = name[-1] == " "
if no_letters == False:
errors_list.append("It has no letters")
if no_spaces == True:
errors_list.append("It has no spaces")
else:
namesplit = name.split(" ")
fname = namesplit[0]
sname = namesplit[1]
pass
if fname and sname is not "":
bad_length = (float(len(fname)) < 3 or float(len(fname)) > 12) or float(len(sname)) < 4 or float(len(sname) > 15)
if bad_length == True:
errors_list.append("One of your names has an unrealistic size")
pass
else:
bad_length = (float(len(name)) < 3 or float(len(name)) > 12)
if bad_length == True:
errors_list.append("It has an unrealistic size")
pass
if digits == True:
errors_list.append("It has digits")
pass
if symbols == True:
errors_list.append("It has symbols")
pass
if many_spaces == True:
errors_list.append("It has more than one space")
pass
if first_space == True:
errors_list.append("The first letter is a space")
pass
if last_space == True:
errors_list.append("The last letter is a space")
pass
except IndexError:
print("You must write something. Try again.")
name = input("My name is ").title()
choose_name(name)
name = input("My name is ").title()
choose_name(name)
while True:
if len(errors_list) != 0:
print("Your name has these errors:")
for i in errors_list:
print(" " + str(errors_list.index(i) + 1) + "- " + i + ".")
print("Try again.")
errors_list.clear()
name = input("My name is ").title()
choose_name(name)
else:
print("Nice to meet you, " + fname + " " + sname + ".")
break
Result when I type the name '----... '
Hi. Tell me your first and last name.
My name is ----...
Your name has these errors:
1- It has no letters.
2- It has symbols.
3- It has more than one space.
4- The last letter is a space.
Try again.
My name is

Manipulating Strings to return concatenated username

Whenever I try to display the Firstname with first initial attached to the end, I get an out of string index range error!
def ForeName():
return raw_input("Please enter your Forename: ")
def MiddleName():
return raw_input("please enter your middle name, if none leave blank: ")
def LastName():
return raw_input("Please enter your last name: ")
def Test():
ForeNameT = ForeName()
MiddleNameT = MiddleName()
LastNameT = LastName()
if not MiddleNameT:
first_username = ForeNameT[0:] + LastNameT[0]
elif ForeNameT:
first_username = ForeNameT[0:][0] #i want to display the first name with the initial of the first name attached to the end of the first name.
else:
first_username = ForeNameT[0:] + MiddleNameT[0]
return first_username
print Test()
You can add an argument to Test function by doing def Test(name_method): and then set if to if name_method == 'without_middlename':.
Try to figure out yourself what you would change print Test() to.
I think i know what you are trying to do, try changing your Test function:
def Test():
ForeNameT = ForeName()
MiddleNameT = MiddleName()
LastNameT = LastName()
if not MiddleNameT:
first_username = ForeNameT + LastNameT
else:
first_username = ForeNameT + MiddleNameT + LastNameT
return first_username
notice the changes to the variable names vs. the function names and the return value so print has something to actually print

How to properly use __repr__ when two classes are involved

I am working on some Python code where I create a basic ATM. The issue I am having is I am not able to get the result that I want its printing "<'function Account.balance at 0x012CBC90>" Instead of the actual balance number. So far I have only tested using jsmith. Feel free to call out any other issues that may cause a problem later.
class Account:
def __init__(self,user,pin,balance):
self.user = user
self.pin = pin
self.balance = int(balance)
def get_user(self):
return self.user
def get_pin(self):
return self.pin
def balance(self):
return int(self.balance)
def setBalance(self,newBalance):
self.balance = newBalance
def __repr__(self):
return str(self.user) + " " + str(self.pin) + " " + str(self.balance)
class ATM:
def withdraw(self,Person,amount):
result = Person - amount
return result
def check(self,Person):
Person = Account.balance
return str(Person)
def transfer(self,id1,id2):
pass
def __str__(self):
return self
def main():
Chase = ATM()
Database = []
Teron_Russell = Account("trussell",1738,0)
Joe_Smith = Account("jsmith",1010,1350)
print(Teron_Russell)
Database.append(Teron_Russell)
Database.append(Joe_Smith)
print("Welcome to the ATM")
id = input("Please enter your user ID: ")
pin = input("Enter your pin: ")
chosen = ""
for i in Database:
print("Test1")
name = Account.get_user(i)
print(name)
checkPin = Account.get_pin(i)
print(checkPin)
if id == name and pin == checkPin:
chosen = i
choice = input("What would you like to do. (Type 'Check','Withdraw','Transfer': ")
if(choice == "Check" or "check"):
print(Chase.check(chosen))
# if(choice == "Withdraw" or "withdraw"):
# wAmount = eval(input("How much would you like to Withdraw: "))
# # Chase.withdraw(Account.balance,)
# elif(choice == "Check" or "check"):
# Chase.check()
# else:
# print("Invalid Choice!")
if __name__ == "__main__":
main()
You named a variable and a method the same name, so the interpreter is confused on which one to use. Change the name of either the method or variable balance and you won't have this problem. Additionally, this isn't java, and you shouldn't use classes for no reason. Since you aren't using any instance variables, it is pointless to have all of those methods inside that class.

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"]:

Categories