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.
Related
i have saved the dictionary in a separeate document with all the correct syntax called directory.txt. The code is for a contacts book/directory using dictionaries. I'm not sure wheter im supposed to define functions before or after calling them but i've tried both and it still doesnt seem to work.
file = open("directory.txt","r+")
contacts = file.read()
def new():
print("Please enter the name of the new contact.")
name = input()
print("Please enter the number of the new contact.")
num = input()
contacts.update({name:num})
print("Contact has successfully been added.")
def view():
for keys, values in contacts():
print("\n*************************************************")
print("Name:",keys)
print("Number:",values)
print("*************************************************\n")
def edit():
for keys, values in contacts():
print("\n*************************************************")
print("Name:",keys)
print("Number:",values)
print("*************************************************\n")
print("Type the name of the contact you would like to edit.")
global name_two
name_two = input()
print("If you would like to edit the number, type 'number'.\nIf you would like to edit the name, type 'name'.\nIf you would like to delete this contact, type 'delete'.")
edit = input().lower()
if edit == "number":
num_edit()
elif edit == "name":
name_edit()
elif edit == "delete":
delete()
def num_edit():
print("What would you like to change the number to?")
num_two = input()
contacts[name_two] = num_two
print("Contact successfully changed.")
def name_edit():
num_save = contacts[name_two]
del contacts[name_two]
print("Enter the new name for the contact.")
name_new = input()
contacts.update({name_new:num_save})
print("Contact successfully changed.")
def delete():
del contacts[name_two]
print("Contact successfully deleted.")
print("Welcome to the Contacts Book.")
print("*****************************\n")
print("If you would like to make a new contact, type 'new'.\nIf you would like to view your contacts, type 'view'.\n If you would like to edit your contacts, type 'edit'.\nIf you would like to exit, type 'exit'")
mode = input().lower()
if mode == "new":
new()
elif mode == "view":
view()
elif mode == "edit":
edit()
else:
print("Goodbye.")
Here is the error message when i type 'view' as the first input:
File "c:\Users\brain\Downloads\contacts.py", line 56, in <module>
view()
File "c:\Users\brain\Downloads\contacts.py", line 11, in view
for keys, values in contacts():
TypeError: 'str' object is not callable
I think you have some variable named str in your code and that caused this problem. This is called shadowing the built in functions, you can try to find that variable with a search in your project file and change it to some other name and should solve it.
I believe you just have an unnecessary set of parenthesis after contacts (it's a var not a function as far as I can see), so just remove those and you should be good. EDIT: gimix reply is far more accurate than what I wrote here
This question already has answers here:
Using global variables in a function
(25 answers)
Closed 2 years ago.
I am trying make a script that will accept 3 inputs first is username as input second and third are bar codes i need to compare, but after the first input of the user I want it to stop asking me for the user and just save and use it and cant seem to do it. I am assigning the user_global to be None at start so can I use an if to run the get_user function but when the script runs it second loop time it gives None as value to the user again and i cant seem to remember how to remove the user from the loop and save it after the first iteration because i am real dumb, as I stated before. Here is the code:
while True:
def get_user():
user=input("Enter User :")
user_global = user
print(user)
print(user_global)
user_global = None
if user_global == None:
get_user()
a = datetime.datetime.now()
print(a)
def gun_read():
barcode1=input("Please the first barcode the barcode!?")
print(barcode1)
barcode2=input("Plese read the secdon barcode?!")
print(barcode2)
if barcode1 == barcode2:
print("GREEN LIGHT!!")
else:
print("you fcked up broooo!!")
# if os.cwd() ima csv file add to csv else create csv
gun_read()
Help, please ? Also ignore prints and datetime.
By default, Python doesn't allow you to assign global variables. In get_user() what it's doing is making a new variable called global_user. To change this behaviour, have global user_global on a line before you assign the variable.
Unless I'm missing something,
user = None
def get_user():
return input("Enter User :")
def gun_read():
barcode1 = input("Please the first barcode the barcode!?")
print(barcode1)
barcode2 = input("Plese read the secdon barcode?!")
print(barcode2)
if barcode1 == barcode2:
print("GREEN LIGHT!!")
return True
else:
print("you fcked up broooo!!")
return False
def main():
global user # so we can write to the global user variable
user = get_user() # grab the username and write it
while True: # repeat gun reads until the end of time
gun_read()
if __name__ == "__main__":
main()
first of all, keep your def functions always on top for readability, second of all why is the whole thing in while True:? And lastly in get_user() you can call gun_read()
def get_user():
user=input("Enter User :")
user_global = user
print(user)
print(user_global)
gun_read()
def gun_read():
barcode1=input("Please the first barcode the barcode!?")
print(barcode1)
barcode2=input("Plese read the secdon barcode?!")
print(barcode2)
if barcode1 == barcode2:
print("GREEN LIGHT!!")
else:
print("you fcked up broooo!!")
user_global = None
while True:
if user_global == None:
get_user()
else:
gun_read()
I have func1 that contains a variable, and I want to access that variable in func2. I have tried in the code below to return the variable in func1 and then set variable "user_name" to the function "first_name_information", but this makes func1 run two times, which I don't want to happen.
def func1():
user_name = input("What's your name? ")
if any(char.isdigit() for char in user_name):
print("You can't put a number in your name.")
sys.exit()
else:
pass
return user_name
def func2():
user_name = first_name_information()
last_name = input("What's your last name {}? ".format(user_name))
if any(char.isdigit() for char in last_name):
print("You can't put a number in your last name.")
sys.exit()
else:
pass
You could do this a few ways but probably this is good for your case, you just call func1 from func2:
def func1():
user_name = input("What's your name? ")
if any(char.isdigit() for char in user_name):
print("You can't put a number in your name.")
sys.exit()
return user_name
def func2():
user_name = func1()
last_name = input("What's your last name {}? ".format(user_name))
if any(char.isdigit() for char in last_name):
print("You can't put a number in your last name.")
sys.exit()
return (user_name, last_name)
func2()
You will need to return from your second function and carry both values back, probably as a tuple.
It seems like you are making some sort of game, you probably should use a class instead, which would make more sense to store the information for your user.
Also you are checking specifically for isdigit() but you could instead check the entire string for alphabetic characters using .isalpha() [docs]
If you want to make your code work with no any changes in the current code and just by adding 1 extra line in middle then have a look at below code after the func1's definition.
In Python, functions are first class object so you can assign 1 function to any variable, send as arguments etc. For example like: f = f2; f(); f2() | f = f2; f3(f, f2) etc.
def func1():
user_name = input("What's your name? ")
if any(char.isdigit() for char in user_name):
print("You can't put a number in your name.")
sys.exit()
else:
pass
return user_name
first_name_information = func1
def func2():
user_name = first_name_information()
last_name = input("What's your last name {}? ".format(user_name))
if any(char.isdigit() for char in last_name):
print("You can't put a number in your last name.")
sys.exit()
else:
# print("So, you are {0} {1}".format(user_name, last_name))
pass
func2()
Output:
What's your name? Rishikesh
What's your last name Rishikesh? Agrawani
Output: (when you uncomment the commented line in func2()). I have added it extra to make the execution little meaningful to me.
What's your name? Rishikesh
What's your last name Rishikesh? Agrawani
So, you are Rishikesh Agrawani
make a function that takes a text and outputs a string without numbers- let it repeat until the user cooperates (DRY - dont repeat yourself - you need this funcitonality twice so make it a function
rename your function to what they do func1 / func2 are bad function names
call the function from your second one and return both names from the second one
def get_string_no_numbers(text):
while True:
k = input(text)
if any(str.isdigit(x) for x in k):
print("No numbers allowed - try again!")
else:
return k
def get_first_name():
user_name = get_string_no_numbers("What's your first name? ")
return user_name
def get_full_name():
user_name = get_first_name() # func1 is called only once
last_name = get_string_no_numbers("What's your last name {}? ".format(user_name))
return user_name, last_name
first_name, last_name = get_full_name() # decompose returned tuple
print(first_name)
print(last_name)
Output:
What's your first name?
Jon21
No numbers allowed - try again!
What's your first name?
24
No numbers allowed - try again!
What's your first name?
John
What's your last name John?
Smith22
No numbers allowed - try again!
What's your last name John?
Smith
John
Smith
Functions are 1st class citizens and can have attributes as well (in your case this is not needed - but possible) - you could store something "at the function":
def f1():
# store the input as attribute of the function
f1.some_var = input()
def f2():
print(f1.some_var)
# f2() ->f1() not run yet: AttributeError: 'function' object has no attribute 'some_var'
f1() # creates the attribute on f1, input is: Jon21
f2() # prints Jon21
More info for input validation: Asking the user for input until they give a valid response
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")
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.