I am attempting to create a contact list with a def() function to easily loop back to the top later in the code. The issue I am having is that I define "function_question" in the def portion but when I run the code it gives me a NameError saying "function_question" is not defined. Any help or suggestions is appreciated!!
#Created a def so I can easily run back the code to the top.
def user_prompt():
print('Welcome to your contact directory.')
function_question = int(input("What would you like to do? \n1 Add Conctact \n2 Find Contact \n3 Edit Contact \n4 Delete Contact:"))
user_prompt()
#Adding a contact to the contact list.
while function_question == 1:
name = input('What is the persons name? ')
phone_number = input('What is the phone number? ')
email = input('What is your email? ')
address = input('What is the person adress? ')
if len(phone_number) != 10:
phone_number = input("the phone number you provided is not the proper length. Re-enter:")
contact = [] + [name] + [phone_number] + [email] + [address]
contact_list.append(contact)
ans = input('Would you like to add another contact? ')
if ans == 'yes':
continue
if ans == 'no':
user_prompt()
You could simply return the value from the function and save it to a variable outside the function. Like:
def user_prompt():
print('Welcome to your contact directory.')
return int(input("question"))
input_question = user_prompt()
The issue is that the variable function_question is empty.
In your code you defined two variables function_question with the same name but with different memory address; the first is a local variable that works only into the user_prompt() function.
The correct code is:
#Created a def so I can easily run back the code to the top.
def user_prompt():
print('Welcome to your contact directory.')
return int(input("What would you like to do? \n1 Add Conctact \n2 Find Contact \n3 Edit Contact \n4 Delete Contact:"))
function_question = user_prompt()
#Adding a contact to the contact list.
while function_question == 1:
...
I suggest you to search about python scope variable for more details.
The function_question variable is in the scope of the user_prompt function so you cannot use it in the global scope. You need to make it global for it to be acessible
I reccomend reading through this,
https://www.w3schools.com/PYTHON/python_scope.asp
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
im on the first part of my course work and im cleaning it up
i want to keep copying and pasting but i know looping it is time efficient and infinite
username = ["bob", "kye", "mes", "omar", "luke", "ben", "robin", "sam"]
name=str(input("whats name 1 "))
round=0
if name in username:
print(" p1 Authenticated")
name2=str(input("whats name 2 "))
if name2 in username:
print(" *STARTING GAME* ")
else:
print("Invalid User")
else:
print("Invalid User")
if you type and name not previously made it should loop like try again till a valid name is typed up
but if i type something wrong code continues and stops when they needs the name
This piece of code would ask for the name as many times needed until the user inserts the valid name.
name_one = ''
name_two = ''
usernames = ['bob', 'kye', 'mes', 'omar']
while name_one not in usernames:
name_one = input('Insert first name: ')
while name_two not in usernames:
name_two = input('Insert first name: ')
Another way would be:
names = []
usernames = ['bob', 'kye', 'mes', 'omar']
while len(names) < 2:
name = input('Insert name: ')
if name in usernames:
names.append(name)
else:
print('Invalid user, try again')
The second example you make a loop that is aways verifying if the list of names has at least two names if it does the loops breaks and the code continues. Then to access each name you use names[0] and names[1].
As commented by Patrick, you should try reading about loops.
I am trying to allow a member to leave the Team if they so wish. By doing this, the system will delete them and their user ID will become available to the next person who wishes to join the team. I am receiving an error with my code. Can someone please advise what I am doing wrong and how this can be achieved?
I would like my add members and remove members to update all the time, based on user input and the needs of the members. I hope this makes sense!
For example: If 'Carl' decided to leave, he would be removed and the next member to join would be assigned the membership ID '2'
Below is my code:
all_users = []
class Team(object):
members = []
user_id = 0
def __init__(self, first, last, address):
self.user_id = Team.user_id
self.first = first
self.last = last
self.address = address
self.email = first + '.' + last + '#python.com'
Team.user_id += 1
Team.members.append(self)
def __str__(self):
print()
return 'Membership ID: {}\nFirst Name: {}\nSurname: {}\nLocation: {}\nEmail: {}\n'.format(self.user_id,
self.first, self.last,
self.address,
self.email)
print()
#staticmethod
def all_members():
for user in all_users:
print(user)
#staticmethod
def add_member():
print()
print("Welcome to the team!")
print()
first_name = input("What's your first name?\n")
second_name = input("What's your surname?\n")
address = input("Where do you live?\n")
all_users.append(Team(first_name, second_name, address))
#staticmethod
def remove_member():
print()
print("We're sorry to see you go , please fill out the following information to continue")
print()
first_name = input("What's your first name?\n")
second_name = input("What's your surname?\n")
address = input("Where do you live?\n")
unique_id = input("Finally, what is your User ID?\n")
if unique_id in all_users:
del unique_id
all_users(User(first_name, second_name, address))
def main():
user_1 = Team('Chris', 'Parker', 'London')
user_2 = Team('Carl', 'Lane', 'Chelsea')
all_users.extend([user_1, user_2])
continue_program = True
while continue_program:
print("1. View all members")
print("2. Want to join the team?")
print("3. Need to leave the team?")
print("3. Quit")
try:
choice = int(input("Please pick one of the above options "))
if choice == 1:
Team.all_members()
elif choice == 2:
Team.add_member()
elif choice == 3:
Team.remove_member()
elif choice == 4:
continue_program = False
print()
print("Come back soon! ")
print()
else:
print("Invalid choice, please enter a number between 1-3")
main()
except ValueError:
print()
print("Please try again, enter a number between 1 - 3")
print()
if __name__ == "__main__":
main()
The remove_member method is wrong for several reasons. The line del unique_id will not remove the value from all_users, which is just a list of Team Members. And you shouldn't have to ask the user for all of this information - just the ID (or the name) would be enough.
What I suggest is:
#staticmethod
def remove_member():
print()
print("We're sorry to see you go , please fill out the following information to continue")
print()
unique_id = input("what is your User ID?\n")
unique_id = int(unique_id)
for i, user in enumerate(all_users):
if user.user_id == unique_id:
all_users.remove(i)
break
If it is important that the user ids are reused, you can keep a list of user ids that are available again. When creating a new member, you can first check that list, and use an old id if there is one.
You can also choose not to reuse the user ids of removed users. An id doesn't really have a meaning and not reusing it makes it simpeler for you.
Finally, you might want to restructure your code:
Team(first_name, second_name, address)
This doesn't make sense: a team with a first name, last name and adress! Better would be to have two classes:
team = Team()
user = User(first_name, second_name, address)
team.add_member(user)
team.remove_member(user)
Some other tips:
# This won't work, because all_users contains Team instances, not numbers. So the user will never be found.
if unique_id in all_users:
# This won't do anything: `del` only removes the access to the variable (might free up memory in heavy applications). It doesn't remove the user from all_users
del unique_id
The purpose of this program is to create a list of names for people attending a party. I would like to be able to grant the user the ability to continue adding names until they chose YES as an option to exit the loop. However, I have am stomped when it comes to having them enter a name they would like to remove in case they added someone by accident or if they would like to edit the list and remove or replace someone.
I am currently a newbie to programming, hence the lack of classes to this code. Any help would be greatly appreciated. Thank you all in advance!
#Initialize empty list
partyList = []
#Initilize empty entry
inviteeName = ''
endEntry = ''
#Run loop until YES is entered as a value
while endEntry != "Yes":
inviteeName = input("Please enter the name of the person you are inviting below." + "\nName: ")
inviteeName = inviteeName.title()
# Verifies if a name was not entered.
while inviteeName == "":
inviteeName = input("\nPlease enter the name of the person you are inviting below." + "\nName: ")
inviteeName = inviteeName.title()
endEntry = input("\tPress ENTER to continue or type Yes to finish: ")
endEntry = endEntry.title()
#Append every new name to the list
partyList.append(inviteeName)
#Adds the word "and" to finish sentence if there are more than one invitees. NOTE: Make a class please!
numOfInvitees = len(partyList)
if numOfInvitees > 1:
partyList.insert(-1, 'and')
#Remove brackets and quotes.
partyList = ', '.join(partyList)
#Print message
print("\nThis will be your final message:\n" + str(partyList) + "\nYou are invited to my party!\n")
I was trying to use this to assist the user with removing names entered by accident.
submit = input('Submit?: '.title())
submit = submit.title()
if submit == 'Yes':
print('Invite has been sent!')
elif submit == 'No':
remNameConfirmation = input('Would you like to remove a name from the list?: ')
remNameConfirmation = remNameConfirmation.title()
if remNameConfirmation == 'Yes':
uninviteName = (input('Who would you like to remove?: '))
uninviteName = uninviteName.title()
Here is the line that is giving some trouble
partyList.remove(uninviteName)
print(partyList)
When your code reaches
partyList = ', '.join(partyList)
it will set the variable partyList to a string. Since it is no longer a list it does not have the .remove method.
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)