I am currently trying to build a simple ATM program(text based) from scratch. My problem is passing the user inputed variables between functions. The error I'm getting is ( init() takes exactly 3 arguments (1 given) ). Could someone explain what is happening and what I'm doing wrong?
class Atm:
acctPass = 0
acctID = 0
def __init__(self, acctID, acctPass):
#self.acctName = acctName
#self.acctBal = acctBal
self.acctPass = acctPin
self.acctID = acctID
def greetMenu(self, acctID, acctPass):
while acctPass == 0 or acctID == 0:
print "Please enter a password and your account number to proceed: "
acctpass = raw_input("Password: ")
acctID = raw_input("Account Number: ")
foo.mainMenu()
return acctPass, acctID # first step to transfer data between two functions
def mainMenu(self, acctID, acctPass):
print ""
acctpass = foo.preMenu(acctPass, acctID)
print acctPass
print "Made it accross!"
def deposit():
pass
def withdrawl():
pass
foo = Atm()
foo.greetMenu()
foo = Atm()
passes exactly 1 argument to Atm.__init__ -- the implicit self. The other two arguments (acctId and acctPass) are missing so python complains.
It looks to me like you can get rid of __init__ all together and bind the instance attributes in greetMenu:
class Atm:
acctPass = 0
acctID = 0
def greetMenu(self):
while self.acctPass == 0 or self.acctID == 0:
print "Please enter a password and your account number to proceed: "
self.acctpass = raw_input("Password: ")
self.acctID = int(raw_input("Account Number: "))
self.mainMenu()
# etc.
Here you'll still probably need to mess with mainMenu a bit to get it working (note now we're not passing the arguments around via function call arguments -- The values are stored on the class).
Thats the constructor called with foo = ATM()
def __init__(self, acctID=0, acctPass=0):
adding the =0 to the parameters initializes them to 0
and you have now overrode the constructor to accept 1,2 or 3 values.
in the greetmenu
def greetMenu(self, acctID, acctPass):
while acctPass == 0 or acctID == 0:
print "Please enter a password and your account number to proceed: "
acctpass = raw_input("Password: ")
acctID = raw_input("Account Number: ")
foo.mainMenu()
return acctPass, acctID # first step to transfer data between two functions
you need to either send in the parameters to the function ATM.greetmenu(1234,'pwd') or use the ones defined in the class like this.
def greetMenu(self):
while self.acctPass == 0 or self.acctID == 0:
print "Please enter a password and your account number to proceed: "
self.acctpass = raw_input("Password: ")
self.acctID = raw_input("Account Number: ")
foo.mainMenu()
#return acctPass, acctID # first step to transfer data between two functions
Related
I am creating a random name generator using OOP in python however i am very new to this concept which is why i am having so difficulties with accessing methods in other methods. I read a post on stack overflow which said to call a method inside another method in a class, you must add self.funcname(param) however i have already done this and it still does not work
class Rndm_nme_gen:
def __init__(self):
print("THE RANDOM NAME GENERATOR")
self.value = ""
self.range = 5
self.counter = 0
self.loop = True
self.names = []
self.loop2 = True
self.take_input()
def take_input(self):
while self.loop:
user_input = input("ENTER A NAME: ")
self.num_check(user_input)
if self.value == "true":
print("INVALID NAME")
loop = True
elif self.value == "false":
self.counter += 1
self.names.append(user_input)
if self.counter == 5:
self.loop = False
self.genname()
#i am trying to call this function but it is not working as i hoped it would
def num_check(self, string):
self.string = string
for char in self.string:
if char.isdigit():
self.value = "true"
else:
self.value = "false"
def genname(self):
while self.loop:
gen = input("TYPE ENTER TO GENERATE A NAME OR TYPE 'q' TO QUIT").strip().lower()
if gen == " " or gen == "":
num = random.randint(0, 5)
print("NAME : " + str(self.names[num]))
loop == True
elif gen == 'q':
quit()
else:
print("UNKNOWN COMMAND")
loop = True
user1 = Rndm_nme_gen()
In the initialisation method, i called the take_input function so it automatically runs and from that function, i attempted to run the code from the genname function however the program would simply end
If you would like to run the code to see how it works, feel free to do so
Expected output:
ENTER NAME FDSF
ENTER NAME dfsd
ENTER NAME sdfds
ENTER NAME sfdff
ENTER NAME sfdf
TYPE ENTER TO GENERATE A NAME OR TYPE 'q' TO QUIT
it does not say TYPE ENTER TO GENERATE A NAME OR TYPE 'q' TO QUIT when i run the program
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.
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"]:
I keep getting the error message "global name 'user_input' not defined. new to python and to SO, hope you can help. Here's my code. Sorry if it's a mess. just starting out and teaching myself...
def menu():
'''list of options of unit types to have converted for the user
ex:
>>> _1)Length
_2)Tempurature
_3)Volume
'''
print('_1)Length\n' '_2)Temperature\n' '_3)Volume\n' '_4)Mass\n' '_5)Area\n'
'_6)Time\n' '_7)Speed\n' '_8)Digital Storage\n')
ask_user()
sub_menu(user_input)
def ask_user():
''' asks the user what units they would like converted
ex:
>>> what units do you need to convert? meter, feet
>>> 3.281
'''
user_input = input("Make a selection: ")
print ("you entered", user_input)
#conversion(user_input)
return user_input
def convert_meters_to_feet(num):
'''converts a user determined ammount of meters into feet
ex:
>>> convert_meters_to_feet(50)
>>> 164.042
'''
num_feet = num * 3.28084
print(num_feet)
def convert_fahrenheit_to_celsius(num):
'''converts a user determined temperature in fahrenheit to celsius
ex:
>>> convert_fahrenheit_to_celsius(60)
>>> 15.6
>>> convert_fahrenheit_to_celsius(32)
>>> 0
'''
degree_celsius = (num - 32) * (5/9)
print(round(degree_celsius, 2))
def sub_menu(num):
'''routes the user from the main menu to a sub menu based on
their first selection'''
if user_input == '1':
print('_1)Kilometers\n' '_2)Meters\n' '_3)Centimeters\n' '_4)Millimeters\n'
'_5)Mile\n' '_6)Yard\n' '_7)Foot\n' '_8)Inch\n' '_9)Nautical Mile\n')
ask = input('Make a selection (starting unit)')
return
if user_input == '2':
print('_1)Fahrenheit\n' '_2)Celsius\n' '_3)Kelvin\n')
ask = input('Make a selection (starting unit)')
return
When you do:
user_input = input("Make a selection: ")
Inside the ask_user() function, you can only access user_input inside that function. It is a local variable, contained only in that scope.
If you want to access it elsewhere, you can globalise it:
global user_input
user_input = input("Make a selection: ")
I think what you were trying was to return the output and then use it. You kind of got it, but instead of ask_user(), you have to put the returned data into a variable. So:
user_input = ask_user()
THere's no need to globalise the variable (as I showed above) if you use this method.
In your menu function, change the line that says ask_user() to user_input = ask_user().