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()
Related
Usage
I am using the replit browser IDE for this project. Also, I am using replit's database for this project.
Problem
So as you can see, in the code below, I am asking the user to log in or Sign up, while saving the user's data of money, deposits, inventory in a key-value pair into the database of replit. It is simple to do that, first I import replit:
from replit import db
And then I assign the key-value pairs to a list like:
username = input("Enter new Username: ")
password = input("Enter new password: ")
db[username] = [password, 300000, [], 500, 0, False]
# the password, money, inventory, allowed deposit, deposited, and boolean for working or not, respectively.
But to actually uses the user's stats saved to their value pair, I have to make the username available in all places in the code. Rather I assigned them to variables:
self.money = db[username][1]
self.inventory = db[username][2]
self.deposit_allowed = db[username][3]
self.deposited = db[username][4]
self.working = db[username][5]
But despite doing that, I get errors that "user name is not defined" and "self.inventory is not defined". I am getting the values using the list as you will see below
The Real Question
My real question is that how can I make the variables, that I have put up, have the values of the list that I have assigned to the value pair of the user's name and make it work globally. Because later in the code, I append to the self.inventory list which is in the value pair list assigned to the user.
Code
Here is a portion of the important code that I am using.
class Game:
def __init__(self, username):
self.money = db[username][1]
self.inventory = db[username][2]
self.deposit_allowed = db[username][3]
self.deposited = db[username][4]
self.working = db[username][5]
def database(self):
enter_game = input("Do you want to [1] Login\n[2] Signup:\n>")
while enter_game == '1' or enter_game == '2':
if enter_game == '1':
username = input("Enter user name: ")
password = input("Enter password: ")
if username in db.keys():
if db[username][0] == password:
print("Loggedd In")
break
else:
print("Invalid Username, Password")
break
if enter_game == '2':
username = input("Enter new Username: ")
password = input("Enter new password: ")
db[username] = [password, 300000, [], 500, 0, False]
break
Also, the project is literally massive, so rather, I have attached a link to go to the real code(The code that is used here is in the gameplay.py file):
Click here to go to the repl with the code.
Or if that doesn't work, click here:
https://replit.com/#OldWizard209/Life-SIMULATOR-In-Development-2#gameplay.py
Below is an example of the code, essentially I am taking input received and attempting to modify an existing CSV value. The problem is the code runs and produces the "print" output as expected, but the values are not being modified to "True" or "False" based on the if and else statements:
def test():
sn_cmn = pd.read_csv('cmn_location.csv')
wan = re.findall(r'Tunnel12', str(router_output)) or re.findall(r'Tunnel13', str(router_output))
hostname = re.search(r'...-....-R.', str(router_output))
hostname_string = str(hostname)
site_code = hostname_string[-13:-10]
if wan == ['Tunnel12'] or wan == ['Tunnel13']:
answer = 'Yes'
if answer == 'Yes':
for site in sn_cmn.u_site_code:
sn_cmn.loc[sn_cmn['u_site_code'] == site_code, 'u_iwan_3'] = 'TRUE'
else:
for site in sn_cmn.u_site_code:
sn_cmn.loc[sn_cmn['u_site_code'] == site_code, 'u_iwan_3'] = 'FALSE'
sn_cmn.to_csv('new_cmn_location.csv')
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")
I am working through the chapter exercises in Tony Gaddis's "Starting Out With Python" 3rd edition from a class I have taken previously. I'm in chapter 9 and Exercise 8 requires me to write a program that pickles a dictionary (name:email) to a file when it closes and unpickles that file retaining the data when it is opened. I have read every word in that chapter and I still don't understand how you can do both in the same file. When you use the open function it creates a file which, in my understanding, is a new file with no data. I'm thinking it may be a sequencing issue, as in where to put the dump and load lines of code but that doesn't make sense either. Logic dictates you have to open the file before you can dump to it.
If the 'open' function creates a file object and associates it with a file and this function appears early in the code (as in def main), what keeps it from zeroing out the file each time that line is called?
This is not a homework assignment. I have completed that class. I am doing this for my own edification and would appreciate any explanation which would help me to understand it. I have included my attempt at the solution which is reflected in the code below and will keep gnawing at it until I find the solution. I just thought since the gene pool is deeper here I would save myself some time and frustration. Thank you very much to those that choose to reply and if I am lacking in any pertinent data that would help to clarify this issue, please let me know.
import pickle
#global constants for menu choices
ADDNEW = 1
LOOKUP = 2
CHANGE = 3
DELETE = 4
EXIT = 5
#create the main function
def main():
#open the previously saved file
friends_file = open('friends1.txt', 'rb')
#friends = pickle.load(friends_file)
end_of_file = False
while not end_of_file:
try:
friends = pickle.load(friends_file)
print(friends[name])
except EOFError:
end_of_file = True
friends_file.close()
#initialize variable for user's choice
choice = 0
while choice != EXIT:
choice = get_menu_choice() #get user's menu choice
#process the choice
if choice == LOOKUP:
lookup(friends)
elif choice == ADDNEW:
add(friends)
elif choice == CHANGE:
change(friends)
elif choice == DELETE:
delete(friends)
#menu choice function displays the menu and gets a validated choice from the user
def get_menu_choice():
print()
print('Friends and Their Email Addresses')
print('---------------------------------')
print('1. Add a new email')
print('2. Look up an email')
print('3. Change a email')
print('4. Delete a email')
print('5. Exit the program')
print()
#get the user's choice
choice = int(input('Enter your choice: '))
#validate the choice
while choice < ADDNEW or choice > EXIT:
choice = int(input('Enter a valid choice: '))
#return the user's choice
return choice
#the add function adds a new entry into the dictionary
def add(friends):
#open a file to write to
friends_file = open('friends1.txt', 'wb')
#loop to add data to dictionary
again = 'y'
while again.lower() == 'y':
#get a name and email
name = input('Enter a name: ')
email = input('Enter the email address: ')
#if the name does not exist add it
if name not in friends:
friends[name] = email
else:
print('That entry already exists')
print()
#add more names and emails
again = input('Enter another person? (y/n): ')
#save dictionary to a binary file
pickle.dump(friends, friends1.txt)
friends1.close()
#lookup function looks up a name in the dictionary
def lookup(friends):
#get a name to look up
name = input('Enter a name: ')
#look it up in the dictionary
print(friends.get(name, 'That name was not found.'))
#the change function changes an existing entry in the dictionary
def change(friends):
#get a name to look up
name = input('Enter a name: ')
if name in friends:
#get a new email
email = input('Enter the new email address: ')
#update the entry
friends[name] = email
else:
print('That name is not found.')
#delete an entry from the dictionary
def delete(friends):
#get a name to look up
name = input('Enter a name: ')
#if the name is found delete the entry
if name in friends:
del [name]
else:
print('That name is not found.')
#call the main function
main()
If you open a file for reading with open("my_file","r") it will not change the file. The file must already exist. If you open a file for writing with open("my_file","w") it will create a new file, overwriting the old one if it exists. The first form (reading) is the default so you can omit the second "r" argument if you want. This is documented in the Python standard library docs.
Use open("myfile", 'r+') this allows both read and write functions. (at least in 2.7)
I have been testing my code for the past few hours and I am stumped. This program takes a text file of names, turns the names into a list, prints the names, sorts the names, prints the sorted names, then allows you to search through the list. Everything seems to be working fine, but the one issue I have is exiting the while loop. If y or Y is selected you can search again, but that also happens if anything else is selected. I added a print statement outside the loop so if anything other than y is selected then the program should end with that last printed string, but it doesn't seem to be working. Does anyone have any ideas about why it isn't working and what I could change to get it to work?
Thank you for your time.
#define the main function
def main():
#create a variable to control the loop
keep_going = 'y'
#setup loop to search for name
while keep_going == 'y' or keep_going == 'Y':
#call input name function
names = input_name()
#call print name function
print_name(names)
#sort the printed list
names.sort()
#call the print name function
print_name(names)
#call the output name function
output_name(names)
#call the search name function
search_name(names)
#add user input for another search
search_again = input('Would you like to make another search?(y for yes): ')
#print if anything other than y or Y is selected
print()
print('Goodbye!')
#define the input function
def input_name():
#open the names.txt file
infile = open('names.txt', 'r')
#read contents into a list
names = infile.readlines()
#close the file
infile.close()
#strip the \n from each element
index = 0
while index < len(names):
names[index] = names[index].rstrip('\n')
index += 1
#return the list back to main function
return names
#define the print name function
def print_name(names):
#print the contents of the list
for name in names:
print(name)
#define the output name function
def output_name(names):
#open file for writing
outfile = open('sorted_names.txt', 'w')
#write the list to the file
for item in names:
outfile.write(item + '\n')
#close the file
outfile.close()
#return to main function
return
#define the search name function
def search_name(names):
#add a user input to search the file
search = input('Enter a name: ')
#determine whether the name is in the list
if search in names:
#get the names index
name_index = names.index(search)
#print the name was found and give the items index
print(search, "was found in list. This item's index is", name_index)
else:
#print the item was not found
print(search, 'was not found in the list.')
main()
#create a variable to control the loop
keep_going = 'y'
#setup loop to search for name
while keep_going == 'y' or keep_going == 'Y':
#add user input for another search
search_again = input('Would you like to make another search?(y for yes): ')
You never set keep_going to something else. Instead, you ask the user to enter y to continue but store it in search_again (which is then thrown away). You will want to change that to store the value in keep_going.
You are testing keep_going, but setting search_again
Replace line 29 which states:
search_again = input('Would you like to make another search?(y for yes): ')
with the following:
keep_going = input('Would you like to make another search?(y for yes): ')
Because when you enter y or Y then you are defining the variable search_again to that letter not the variable keep_going which is needed to change for the loop to stop.