When I enter data in to my function directly I get the right output but when I use input from the user to fill the list nothing happens. I don't get any errors or output what so ever.
The data from input should enter the list and the index from input should be deleted from the list.
#!/usr/bin/env python3
#class definitions
class record:
def __init__(self,telephone,lastname,firstname):
self.telephone = telephone
self.lastname = lastname
self.firstname = firstname
def __str__(self):
return f"Last name: {self.lastname}, First Name: {self.firstname}, Telephone: {self.telephone}"
class PhoneBook:
def __init__(self):
self.phonebook = []
def addrecord(self, record):
self.phonebook.append(record)
return self.phonebook.index(record)
def deleterecord(self, i):
self.phonebook.pop(i-1)
def printphonebook(self):
x = 1
for entry in self.phonebook:
print(x,'. ',entry,sep='')
x = x + 1
#Main
select = None
while select != 'exit':
ph = PhoneBook()
ph.addrecord(record(515,'fin','matt'))
ph.addrecord(record(657,'fisher','bill'))
select = input('Main Menu \n1. show phonebook \n2. add record \n3. remove record\nor "exit" to exit program\n')
test = False
while test == False:
if select == '1':
ph.printphonebook()
test = True
elif select == '2':
x = int(input('Enter telephone number.\n'))
y = str(input('Enter last name.\n'))
z = str(input('Enter first name.\n'))
ph.addrecord(record(x,y,z))
test = True
elif select == '3':
i = int(input('Enter the record number youd like to delete.\n'))
ph.deleterecord(i)
test = True
elif select == 'exit':
break
else:
print('Invalid selection. Please try again.')
test = True
The desired output would be getting the data to correctly enter and exit the list based on my x, y and z inputs and take out the specified index of the list based on the i input.
You clear and create a new Phonebook() object every time your first while loop runs.
I'm new and not skilled enough to fix every problem in a short amount of time.
You don't see your new entries, because they get wiped out every time.
Try using one while loop and a switch statement.
Related
#bll
class cms():
def __init__(self):
self.namelist = []
self.idlist = []
self.moblist = []
self.emaillist = []
self.reslist = []
def addcustomer(self):
self.idlist.append(id)
self.namelist.append(name)
self.moblist.append(mob)
self.emaillist.append(email)
return print("Customer Added")
def showcustomer(self):
print(self.idlist, self.namelist, self.moblist, self.emaillist)
#pl
while(1):
print("Enter Your Choice Enter 1 to Add, 2 to search, 3 to delete, 4 to Modify, 5 to Display All, 6 to Exit")
ch = input("Enter your choice")
conman = cms()
if ch == '1':
id = input("ENter your id")
name = input("Enter Your name")
mob = input("Enter your mobile no")
email = input("Enter your email")
conman.addcustomer()
elif ch == '2':
conman.showcustomer()
this is my code when I am entering 1 then the customer gets added,but when I call another method to print that appended item it returns blank list
Output:-
Enter your choice2
[] [] [] []
Help!! Please.
conman = cms()
Because this is inside the loop, each time through the loop, this creates a separate, new cms with its own lists of data, and makes conman be a name for the new value.
elif ch == '2':
conman.showcustomer()
This, therefore, displays information from the new conman, ignoring everything that was done in the previous iteration of the loop.
I am self-learning Python (no prior programming experience) and I am trying this question:
ask the user to input as many bank account numbers as they’d like, and store them within a list initially. once the user is done entering information, convert the list to a frozenset and print it out.
This is my code:
# create global variables
b_accounts = []
fzb_accounts = frozenset()
# Create add account function
def addAccount(account):
b_accounts.append(account)
print('Account number: {} has been added'.format(account))
return b_accounts
# create covert from a list to a frozenset function
def convertFz():
if b_accounts:
globals()['fzb_accounts'] = frozenset(b_accounts)
return fzb_accounts
else:
print('List of account does not exist!')
# create show account function
def showAccount():
convertFz()
if fzb_accounts:
#print('Here your enique entered accounts:{}'.format(fzb_accounts))
for acc in fzb_accounts:
print(acc)
else:
print('No account!')
# create main function
def main():
done = False
while not done:
ans = input('Please select add/show/quit account: ').lower()
if ans == 'add':
account = input('Enter account number: ')
addAccount(account)
elif ans =='show':
showAccount()
elif ans =='quit':
done = True
print('Bye!')
else:
print('Invalid option')
main()
I want to add the following account numbers:
1234
12345
1234
the output should be:
1234
12345
Thank all, code updated and work as expected.
I am trying to add a very simple score function to an also very simple flashcard game and I can't make the game remember the value of the variable containing the score (it always resets it 0). The score is obviously relying on the honesty of the user (and that's fine) that has to press "Y" when guessing the word.
from random import *
def add_score():
pos_score = 0
score = input("Press Y if you got the correct word or N if you got it wrong!" )
if score == 'Y':
pos_score += 1
print(pos_score)
def show_flashcard():
""" Show the user a random key and ask them
to define it. Show the definition
when the user presses return.
"""
random_key = choice(list(glossary))
print('Define: ', random_key)
input('Press return to see the definition')
print(glossary[random_key])
def add_flashcard():
""" This function allows the user to add a new
word and related value to the glossary. It will
be activated when pressing the "a" button.
"""
key = input("Enter the new word: ")
value = input("Enter the definition: ")
glossary[key] = value
print("New entry added to glossary.")
# Set up the glossary
glossary = {'word1':'definition1',
'word2':'definition2',
'word3':'definition3'}
# The interactive loop
exit = False
while not exit:
user_input = input('Enter s to show a flashcard, a to add a new card. or q to quit: ')
if user_input == 'q':
exit = True
elif user_input == 's':
show_flashcard()
add_score()
elif user_input == 'a':
add_flashcard()
else:
print('You need to enter either q, a or s.')
Some notes:
I am aware that right now only the positive score is implemented in the code, but I figured it would be better to proceed step by step and have that working first.
Problem
In your def add_score(), you initialise the variable to 0 every time. Also, it is a local variable, which means you can only reference it from within your function add_score(). This means that every time you exit that function, that variable is completely deleted.
Solution
You need to make that a global variable, that is, initialise it to 0 at the start of the game, and outside your function. Then inside your add_score you simply reference to the global variable and increase it without initialising it every time:
from random import *
def add_score():
score = input("Press Y if you got the correct word or N if you got it wrong!" )
if score == 'Y':
global pos_score
pos_score += 1
print(pos_score)
# Set up the glossary
glossary = {'word1':'definition1',
'word2':'definition2',
'word3':'definition3'}
# The interactive loop
pos_score = 0 #NOTE you initialise it here as a global variable
exit = False
while not exit:
user_input = input('Enter s to show a flashcard, a to add a new card. or q to quit: ')
if user_input == 'q':
exit = True
elif user_input == 's':
show_flashcard()
add_score()
elif user_input == 'a':
add_flashcard()
else:
print('You need to enter either q, a or s.')
Note I skipped the irrelevant functions. However, usually changing the scope of variables like this is considered bad practice. What you should do is either have a class -- a bit overly complicated for this example -- or return a value to add from your add_score and add that value in the main loop. This would be the code:
from random import *
def add_score():
score = input("Press Y if you got the correct word or N if you got it wrong!" )
if score == 'Y':
#global pos_score
#pos_score += 1
#print(pos_score)
return 1
return 0
def show_flashcard():
""" Show the user a random key and ask them
to define it. Show the definition
when the user presses return.
"""
random_key = choice(list(glossary))
print('Define: ', random_key)
input('Press return to see the definition')
print(glossary[random_key])
def add_flashcard():
""" This function allows the user to add a new
word and related value to the glossary. It will
be activated when pressing the "a" button.
"""
key = input("Enter the new word: ")
value = input("Enter the definition: ")
glossary[key] = value
print("New entry added to glossary.")
# Set up the glossary
glossary = {'word1':'definition1',
'word2':'definition2',
'word3':'definition3'}
# The interactive loop
pos_score = 0 #NOTE you initialise it here as a global variable
exit = False
while not exit:
user_input = input('Enter s to show a flashcard, a to add a new card. or q to quit: ')
if user_input == 'q':
exit = True
elif user_input == 's':
show_flashcard()
pos_score += add_score()
print(pos_score)
elif user_input == 'a':
add_flashcard()
else:
print('You need to enter either q, a or s.')
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
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"]: