I'm trying to run this code in Python. (I omitted the body of the 'listAccounts' function because I have no problem with that)
import os
customers = []
numAccounts = 0
option = 0
def listAccounts(customers):
(...)
def createAccount(customers, numAccounts):
name = input('Enter a name: ')
lastname = input('Enter a lastname: ')
account = {'name':name, 'lastname':lastname, 'account':{'balance':0, 'accountNumber':numAccounts}}
customers.append(account)
numAccounts += 1
print("Account created")
input("Press Intro to continue...")
return customers, numAccounts
while ('3' != option):
option = input('''Please select an option:
1.- List Accounts
2.- Create Account
3.- Exit
''')
if option == '1':
listAccounts(customers)
elif opcion == '2':
createAccount(customers, numAccounts)
os.system("CLS")
print("End of the program")
The problem is when I create a new account with the 'createAccount' function. Everything works fine when I enter the values and saves it. I show the accounts and the first account number is 0. Everything is going well, but when I create a new account again and list them, I realize that both accounts have the number 0, even if I create a third account this has the value 0. Like if the 'numAccounts' variable is not increasing.
I debuged my program, and I notice that the value of 'numAccounts' really increases to 1, but when step to the 'return' line, it puts the value in 0 again. I comment the 'return' line, change the values, etc. But nothing works. Does anyone know what is wrong with my code?
The problem is the scope of the numAccounts variable, you defined your functions as createAccount(customers, numAccounts), that means that the numAccounts variable you're increasing by one is only alive inside the function. As you defined numAccounts variable as global you can defined your function like createAccount(customers, currentnumAccounts) and when you call the numAccounts+=numAccounts you're going to increase the global variable.
Because you are not storing what is returned by createAccount.
Though you have created your all variables at global level, you are receiving variables with same name so function will make a local copy of that variable and it would not change the global variable's value.
Your while loop should be as below
while ('3' != option):
option = input('''Please select an option:
1.- List Accounts
2.- Create Account
3.- Exit
''')
if option == '1':
listAccounts(customers)
elif opcion == '2':
customers,numAccounts = createAccount(customers, numAccounts)
os.system("CLS")
print("End of the program")
Related
No matter how many times I google variations of my question, I cannot seem to find a solution. I am a beginner programmer, trying to build a game that randomly generates events as you progress through the stages. The problem I am running into are return statements, and passing the values between different modules. Each method for each file are inside of classes. They are all static methods, and calling these methods is not my problem. It is transferring the value of the variables. I'm not sure where I am going wrong, whether it is how I am structuring it, or if I just don't understand how these return statements work.
This is the first File I am starting from. Print statements will be filled out after everything functions properly.
def story():
print("---Intro Story Text here--- ... we will need your name, Traveler. What might it be?")
user_prompt = Introduction.PlayerIntroduction
name = user_prompt.player_info(1)
print(f"Welcome {name}!")
print(f"----After name is received, more story... how old might you be, {name}?")
age = user_prompt.player_info(2)
This is the file I am trying to get the values from. File: Introduction, Class: PlayerIntroduction
#staticmethod
def player_info(funct_select):
if funct_select == 1:
name = PlayerIntroduction.get_player_name()
player_name = name
elif funct_select == 2:
age = PlayerIntroduction.get_player_age()
player_age = age
return player_name, player_age
#staticmethod
def get_player_name():
print("\n\n\nWhat is your name?")
players_name = input("Name: ")
while True:
print(f"Your name is {players_name}?")
name_response = input("Yes/No: ")
if name_response == "Yes" or name_response == "yes":
name = "Traveler " + players_name
break
elif name_response == "No" or name_response == "no":
print("Let's fix that.")
PlayerIntroduction.get_player_name()
else:
print("Please respond with 'Yes' or 'No'.")
return name
#staticmethod
def get_player_age():
print("\n\n\nHow old are you?")
age = input("Age: ")
while True:
print(f"Your age is {age}?")
age_response = input("Yes/No: ")
if age_response == "Yes" or age_response == "yes":
break
elif age_response == "No" or age_response == "no":
print("Let's fix that.")
PlayerIntroduction.get_player_age()
else:
print("Please respond with 'Yes' or 'No'.")
return age
I would like to use the values for "name" and "age" throughout multiple modules/multiple methods within my program. But in order to get those values, I need to assign a variable to the function call.. Resulting in prompting the user to re-enter their name/age at later stages in the game. My idea to combat this was in the first method of this module, creating a conditional statement "if 'example' == 1: 'run the name prompt' and elif == 2: run age prompt, thinking the initial run with the arguments defined would run these prompts, store the values into the variables (name, age), and finally pass the values to the new variables that are NOT assigned to the function call (p_name, p_age), avoiding triggering the user prompt over and over. Ultimately, this failed, and as the code sits now I am getting:
UnboundLocalError: local variable 'player_age' referenced before assignment
Why is this? The only instance 'player_age' is called that is reachable at this point is in the return statement, indented in-line with the conditional statement. The code should read (If I understand incorrectly, please explain) from top to bottom, executing in that order. The 'if' condition is met, so it should run that. If I were to define 'player_name' and 'player_age' as null at the top of this method to avoid this error, then every time I would need to reference these values initially entered by the user, they would be re-assigned to 'null', negating everything I am trying to do.
Thank you all for your patience, I tried to explain what I was doing and my thought process the best I could. Any feedback, criticism, and flaws within my code or this post are GREATLY appreciated. Everything helps me become a better programmer!! (:
In my code I have grabbed an integer from a text file and globally declared it as the variable 'accessLevel1', so it could be used to run validation checks in other areas of the code. However, despite the variable value being saved as '2' when using the first staff login details, an IF statement dependent on the variable being '2' is not running at all.
The contents of the text file titled 'staffDetails':
Jonas,Hills,JHills375,Sweirl900,2,
Ellie,Glover,EGlover919,KHaisen10,1,
Code used for grabbing the variable:
validateStaff = open("staffDetails.txt", "r")
for row in validateStaff:\
record = row.split(",")
if record[2] == (entered_text):
forename = record[0]
surname = record[1]
username = record[2]
password = record[3]
accessLevel = record[4]
if record[3] == (entered_text2):
global forename1
global accessLevel1
global surname1
surname1 = surname
forename1 = forename
accessLevel1 = accessLevel
The problem code
def modclick(): #A function that occurs when a button is pressed
print("Your access level is: " + (accessLevel1)) #This is here for demonstrative purposes of the problem
if accessLevel1 == '1':
errorLabelstock.config(fg='red') #this actually works somehow
if accessLevel1 == '2':
modifystock() #This function isn't called despite printing that the access level is 2
if accessLevel1 == '3':
modifystock()
Proof that the system interpretted the variable 'accessLevel1' to be of the value 2 yet not executing the IF statement:
Try adding the following line, this will fix it
accessLevel1 = str(accessLevel1).strip()
I am trying to verify the values entered by the user, The values that are entered by the user are being stored in one method and its values verification is done in the other method. But the problem I am facing is how to use variable values from one method to another. How can we do this in python?.I am getting error-"userDetailsValidation is not defined" Here is my code:
from userAccountDatabase import *
def userInputs():
userDetails=[]
firstName=str(input("Enter First Name").upper())
while True:
if(userDetailsValidation(firstName, "FirstName", accountDetails))==True:
userDetails.append(firstName)
break
else:
print('Enter valid First Name')
firstName=str(input("Enter First Name").upper())
LastName=str(input("Enter Last Name").upper())
while True:
if(userDetailsValidation(LastName, "LastName", accountDetails))==True:
userDetails.append(LastName)
break
else:
print('Enter valid last Name')
firstName=str(input("Enter Last Name").upper())
dateOfBirth=str(input("Enter date of birth"))
while True:
if(userDetailsValidation(dateOfBirth, "LastName", accountDetails))==True:
userDetails.append(dateOfBirth)
break
else:
print('Enter valid dateOfBirth ')
firstName=str(input("Enter dateOfBirth").upper())
# return firstName,LastName,dateOfBirth
userInputs()
def userDetailsValidation(value, fieldName, database):
print("The account does not exist with the given details,Enter valid First name")
for entry in database:
if fieldName in entry and entry[fieldName] == value:
print("correct value")
return True
else:
return False
def printRequiredUserInfo(FirstName,fieldname,AccountNumber,Accountbalance,Database):
for entry in Database:
if fieldname in entry and entry[fieldname] == FirstName:
print(entry)
printRequiredUserInfo(firstName,"FirstName","Account Number","Account Balance",accountDetails)
Your userDetailsValidation function is still not resolvable when you call it in if(userDetailsValidation(dateOfBirth, "LastName", accountDetails))==True:
You can move the implementation of userDetailsValidation() before userInputs() or just move the call to userInputs() after you define userDetailsValidation().
Regarding your question of using values of variables from one function in another, you have multiple options.
Declare the variables as global. This way, you can access them in all functions inside your module.
Implement the functions inside a class and create member variables for this class.
Return variables which is of interest.
Learning lists and arrays and I am not sure where I went wrong with this program. Keep in mind I am still new to python. Unsure if i am doing it right. Ive read a few tutorials and maybe Im not grasping list and arrays. Ive got it to where you can type a name but it doesnt transfer to a list and then i get list is empty constantly as well as other errors under other functions in the code.
def display_menu():
print("")
print("1. Roster ")
print("2. Add")
print("3. Remove ")
print("4. Edit ")
print("9. Exit ")
print("")
return int(input("Selection> "))
def printmembers():
if namelist > 0:
print(namelist)
else:
print("List is empty")
def append(name):
pass
def addmember():
name = input("Type in a name to add: ")
append(name)
def remove():
pass
def removemember():
m = input("Enter Member name to delete:")
if m in namelist:
remove(m)
else:
print(m, "was not found")
def index():
pass
def editmember():
old_name = input("What would you like to change?")
if old_name in namelist:
item_number = namelist.index(old_name)
new_name = input("What is the new name? ")
namelist[item_number] = new_name
else:
print(old_name, 'was not found')
print("Welcome to the Team Manager")
namelist = 0
menu_item = display_menu()
while menu_item != 9:
if menu_item == 1:
printmembers()
elif menu_item == 2:
addmember()
elif menu_item == 3:
removemember()
elif menu_item == 4:
editmember()
menu_item = display_menu()
print("Exiting Program...")
For starting out, you've got the right ideas and you're making good progress. The main problem is how you defined namelist = 0, making it a number. Instead, namelist needs to be an actual list for you to add or append anything to it. Also, you're append() method is not necessary since once you define namelist as a list, you can use the built-in list.append() method, without having to write your own method.
So here are a few suggestions/corrections, which once you have the basis working correctly, you should be able to work out the rest of the bug fixes and logic.
Since you don't have any main() method, you can define namelist on
the first line of code, before any other code, so that it is
referenced in each method:
namelist = [] # an empty list
Change addmember() method to:
def addmember():
name = raw_input("Type in a name to add: ")
namelist.append(name)
Since namelist is a list, we can use the built-in len() method on nameslist to check if it's empty when printing out its contents (if any):
def printmembers():
if len(namelist) > 0: # Get the length of the list
print(namelist)
else:
print("List is empty")
Now that the Add() menu option is working for adding a name to the namelist, you should be able to implement removing, and editing names to the list using similar logic.
You should consider initializing the list to be empty instead of zero (unless you want that element).
namelist = list()
Also, your append method does not perform any actions. It's also pretty unnecessary since you can just use the append method of list.
def addmember():
name = input("Type in a name to add: ")
namelist.append(name)
If you did want to make your own append method you should understand that the variables in the function definition are inputs, so just saying def append(name) won't perform any action. In this case name is the identifier you are applying to the input argument. You could just as easily call it anything you wanted. A good way to understand this is by assigning the argument a different variable name than the one you pass it. Like this:
def append(nameToAppend):
namelist.append(nameToAppend)
You can call your append method in addmember like this:
def addmember():
name = input("Type in a name to add: ")
append(name)
After getting name from input, you call the append(name) method, yet your append method doesn't do anything yet.
In your append method you have to add the name you get to your namelist, like how you do in the editmember method.
I am extremely new to Python, and to programming in general, so I decided to write some basic code to help me learn the ins and outs of it. I decided to try making a database editor, and have developed the following code:
name = []
rank = []
age = []
cmd = input("Please enter a command: ")
def recall(item): #Prints all of the information for an individual when given his/her name
if item in name:
index = name.index(item) #Finds the position of the given name
print(name[index] + ", " + rank[index] + ", " + age[index]) #prints the element of every list with the position of the name used as input
else:
print("Invalid input. Please enter a valid input.")
def operation(cmd):
while cmd != "end":
if cmd == "recall":
print(name)
item = input("Please enter an input: ")
recall(item)
elif cmd == "add":
new_name = input("Please enter a new name: ")
name.append(new_name)
new_rank = input("Please enter a new rank: ")
rank.append(new_rank)
new_age = input("Please input new age: ")
age.append(new_age)
recall(new_name)
else:
print("Please input a valid command.")
else:
input("Press enter to quit.")
operation(cmd)
I want to be able to call operation(cmd), and from it be able to call as many functions/perform as many actions as I want. Unfortunately, it just infinitely prints one of the outcomes instead of letting me put in multiple commands.
How can I change this function so that I can call operation(cmd) once, and call the other functions repeatedly? Or is there a better way to go about doing this? Please keep in mind I am a beginner and just trying to learn, not a developer.
Take a look at your code:
while cmd != "end":
if cmd == "recall":
If you call operation with anything than "end", "recall" or "add", the condition within while is True, the next if is also True, but the subsequent ifs are false. Therefore, the function executes the following block
else:
print("Please input a valid command.")
and the while loop continues to its next lap. Since cmd hasn't changed, the same process continues over and over again.
You have not put anything in your code to show where operator_1, operator_2, and operator_3 come from, though you have hinted that operator_3 comes from the commandline.
You need to have some code to get the next value for "operator_3". This might be from a list of parameters to function_3, in which case you would get:
def function_3(operator_3):
for loopvariable in operator_3:
if loopvariable == some_value_1:
#(and so forth, then:)
function_3(["this","that","something","something else"])
Or, you might get it from input (by default, the keyboard):
def function_3():
read_from_keyboard=raw_input("First command:")
while (read_from_keyboard != "end"):
if read_from_keyboard == some_value_1:
#(and so forth, then at the end of your while loop, read the next line)
read_from_keyboard = raw_input("Next command:")
The problem is you only check operator_3 once in function_3, the second time you ask the user for an operator, you don't store its value, which is why its only running with one condition.
def function_3(operator_3):
while operator_3 != "end":
if operator_3 == some_value_1
function_1(operator_1)
elif operator_3 == some_value_2
function_2
else:
print("Enter valid operator.") # Here, the value of the input is lost
The logic you are trying to implement is the following:
Ask the user for some input.
Call function_3 with this input.
If the input is not end, run either function_1 or function_2.
Start again from step 1
However, you are missing #4 above, where you are trying to restart the loop again.
To fix this, make sure you store the value entered by the user when you prompt them for an operator. To do that, use the input function if you are using Python3, or raw_input if you are using Python2. These functions prompt the user for some input and then return that input to your program:
def function_3(operator_3):
while operator_3 != 'end':
if operator_3 == some_value_1:
function_1(operator_3)
elif operator_3 == some_value_2:
function_2(operator_3)
else:
operator_3 = input('Enter valid operator: ')
operator_3 = input('Enter operator or "end" to quit: ')
looks like you are trying to get input from the user, but you never implemented it in function_3...
def function_3(from_user):
while (from_user != "end"):
from_user = raw_input("enter a command: ")
if from_user == some_value_1:
# etc...