I am working on some Python code where I create a basic ATM. The issue I am having is I am not able to get the result that I want its printing "<'function Account.balance at 0x012CBC90>" Instead of the actual balance number. So far I have only tested using jsmith. Feel free to call out any other issues that may cause a problem later.
class Account:
def __init__(self,user,pin,balance):
self.user = user
self.pin = pin
self.balance = int(balance)
def get_user(self):
return self.user
def get_pin(self):
return self.pin
def balance(self):
return int(self.balance)
def setBalance(self,newBalance):
self.balance = newBalance
def __repr__(self):
return str(self.user) + " " + str(self.pin) + " " + str(self.balance)
class ATM:
def withdraw(self,Person,amount):
result = Person - amount
return result
def check(self,Person):
Person = Account.balance
return str(Person)
def transfer(self,id1,id2):
pass
def __str__(self):
return self
def main():
Chase = ATM()
Database = []
Teron_Russell = Account("trussell",1738,0)
Joe_Smith = Account("jsmith",1010,1350)
print(Teron_Russell)
Database.append(Teron_Russell)
Database.append(Joe_Smith)
print("Welcome to the ATM")
id = input("Please enter your user ID: ")
pin = input("Enter your pin: ")
chosen = ""
for i in Database:
print("Test1")
name = Account.get_user(i)
print(name)
checkPin = Account.get_pin(i)
print(checkPin)
if id == name and pin == checkPin:
chosen = i
choice = input("What would you like to do. (Type 'Check','Withdraw','Transfer': ")
if(choice == "Check" or "check"):
print(Chase.check(chosen))
# if(choice == "Withdraw" or "withdraw"):
# wAmount = eval(input("How much would you like to Withdraw: "))
# # Chase.withdraw(Account.balance,)
# elif(choice == "Check" or "check"):
# Chase.check()
# else:
# print("Invalid Choice!")
if __name__ == "__main__":
main()
You named a variable and a method the same name, so the interpreter is confused on which one to use. Change the name of either the method or variable balance and you won't have this problem. Additionally, this isn't java, and you shouldn't use classes for no reason. Since you aren't using any instance variables, it is pointless to have all of those methods inside that class.
Related
Being relatively new to coding, some of the small issues I have not yet learn to tweak out. In this code my goal is to print the account's name, plus their balance based off of a withdraw, deposit, or simply checking. The name and values will print, however, they are not in a line, as well as "none" prints at the end, and i cannot seem to rid it. I need suggestions on how to fix. I believe the problem stems somewhere within the methods and calling them but am not sure.
class Account:
def __init__(self, name, balance):
self.name = name
self.balance = balance
def Withdraw(self):
if Amount1 > self.balance:
self.withdraw = "You have exceeded your balance."
print (self.withdraw)
elif Amount1 < self.balance:
self.withdraw = (self.balance - Amount1)
print (self.withdraw)
def Deposit(self):
self.deposit = (self.balance + Amount2)
print (self.deposit)
def CheckBalance(self):
self.check = self.balance
print (self.check)
account1 = Account("Barbara", 500.00)
account2 = Account("Joe", 150.00)
account3 = Account("Frank", 20.00)
Action = input("What would you like to do; check balance(c), deposit(d), or withdraw(w)? ")
if Action == "w":
Amount1 = int(input("What amount would you like to withraw?"))
print (account1.name + str(account1.Withdraw()))
print (account2.name + str(account2.Withdraw()))
print (account3.name + str(account3.Withdraw()))
if Action == "d":
Amount2 = int(input("What amount would you like to deposit? "))
print (account1.name + str(account1.Deposit()))
print (account2.name + str(account2.Deposit()))
print (account3.name + str(account3.Deposit()))
if Action == "c":
print (account1.name + str(account1.CheckBalance()))
print (account2.name + str(account2.CheckBalance()))
print (account3.name + str(account3.CheckBalance()))
This is the code i have running so far
I would like to make a list that stores all objects of the JoJo class in a list according to the desired amount of users.
Example: If I want to create two users of the JoJo class, the code will allow me to enter the name and stand of these users and print them at the end of the code. The necessary changes for this will be on the main.py page.
jojo.py
class JoJo:
# Construct
def __init__(self):
self.status_stand = False
# Destruct
def __del__(self):
print (f"The user {self.getName()} was deleted by the destruct.")
# Getter
def getName(self): return self.name
def getStand(self): return self.stand
# Setter
def setName(self, noma): self.name = name
def setStand(self, stand): self.stand = stand
# Method activeStand()
def activeStand(self):
if self.status_stand:
print(f"{self.getStand()} is already invoked.")
else:
self.status_stand = True
print(f"{self.getStand()} was invoked.")
# Méthod desactiveStand()
def desactiveStand(self):
if self.status_stand == False:
print(f"{self.getStand()} is already hidden.")
else:
self.status_stand = False
print(f"{self.getStand()} was hidden.")
# Method talk()
def talk(self):
print(f"Name: {self.getName()} | Stand: {self.getStand()}")
print ("Stand status: " + {True: "Active.", False: "Inactive."}[self.status_stand])
self.activeStand() if self.status_stand else self.desactiveStand()
main.py
from jojo import JoJo
jojo = JoJo()
while True:
name = str(input("Enter username: "))
if (len(nome.strip()) <= 0):
print("Username cannot be empty.")
else:
jojo.setNome(name.title())
break
while True:
stand = str(input(f"Enter the name of the {jojo.getName()} stand: "))
if (len(stand.strip()) <= 0):
print(f"The name of {jojo.getNome()} stand cannot be empty.")
else:
jojo.setStand(stand.title())
break
jojo.talk()
del jojo
All you need is a list object. Assuming we accept user names until a blank value tells us to stop:
jojo_list = list()
while True:
name = input("Enter username: ")
if name.strip() == '':
break
jojo = JoJo()
jojo.setName(name.strip().title())
jojo_list.append(jojo)
Now you can simply loop over your list of jojo objects and do things to them:
for jojo in jojo_list:
print(jojo.getName())
Details on list objects: https://docs.python.org/3/tutorial/datastructures.html
I am trying to code something really simple but can't figure out how to use the variable I declared in the first function, in the second function.
Any ideas you might have?
import random
def request_info():
name = input("What is your name?: ")
email = input("What is your email?: ")
def print_user_info():
print("Your name " + name)
print("Your email " + email)
num = random.randrange(100_000, 10**8)
I would create a class:
import random
class request_info(object):
def __init__(self):
self.name = input("What is your name?: ")
self.email = input("What is your email?: ")
def print_user_info(self):
print("Your name " + self.name)
print("Your email " + self.email)
num = random.randrange(100_000, 10**8)
return num
r = request_info()
r.print_user_info()
# What is your name?: Test
# What is your email?: Test#gmail.com
# Your name Test
# Your email Test#gmail.com
# 90584743
I would just pass the variables into the other function like the following code shows:
import random
def print_user_info(name,email):
print("Your name " + name)
print("Your email " + email)
num = random.randrange(100_000, 10**8)
def request_info():
name = input("What is your name?: ")
email = input("What is your email?: ")
print_user_info(name,email)
You will of course also have to invoke the request_info function once so that the other function gets called.
There are a few ways to do this, but you should think of scope before anything else.
The dirtiest way is to declare a global variable that will be set outside of the function, then assigned within the function.
global someVariable
someVariable = None
someVariable2
someVariable2 = None
def someFunction():
global someVariable
someVariable = 12
global someVariable2
someVariable2 = 24
someFunction()
print(someVariable)
This will get you by, but it's not the best way to work with variables. If all you're writing is 11 or so lines of code, it'll do the trick.
Returns is another way to handle this.
def someFunction():
someVariable = 4
someVariable2 = 13
return (someVariable,someVariable2)
print(someFunction())
By having the function return a tuple will allow you to get both variables accessible to the next function.
Finally, there's classes. I would recommend Classes for more complex code as it keeps things in a nice and neat little container.
class myClass:
someVariable = None
someVariable2 = None
def __init__(self):
self.someVariable = 50
self.someVariable2 = -12
def retValues(self):
someVariable = self.someVariable
someVariable2 = self.someVariable2
return (someVariable,someVariable2)
print(myClass().retValues())
More on Classes here: https://docs.python.org/3/tutorial/classes.html
What you're looking for are return statements, which you can use to assign the output of a function to a variable.
Here, we'll return a tuple and use multiple assignment to call the values in the tuple name and email:
import random
def request_info():
name = input("What is your name?: ")
email = input("What is your email?: ")
return (name, email) # this function now 'returns' this tuple
def print_user_info(name, email):
print("Your name " + name)
print("Your email " + email)
num = random.randrange(100_000, 10**8)
So if you ran the following:
name, email = request_info()
print_user_info(name, email)
(For clarity, this is what's happening in the first line above, but you can combine it into 1 line instead of 3)
user_info = request.info()
name = user_info[0]
email = user_info[1]
Your program would run like so:
What is your name?: Joe Smith
What is your email?: jsmith#gmail.com
Your name Joe Smith
Your email jsmith#gmail.com
Here is one way of doing it. Using a class can help share variables and functions.
import random
class User:
def __init__(self, name, email):
self.name = name
self.email = email
self.num = random.randrange(100_000, 10**8)
def print_info(self):
print(f"Your name is: {self.name} \nYour email is: {self.email}")
new_user = User(input("What is your name?"), input("What is your email?"))
new_user.print_info()
Code is not printing the multiple elements that I add to it. Instead it is just printing out the recently added element. can anyone guide me on this?
class bikes:
def __init__(self,make,name,model):
self.make = make
self.name = name
self.model = model
self.all_bikes = []
def total_bikes(self):
self.counter = 0
dict_bikes = {"Make": self.make,
"Name": self.name,
"Model": self.model}
self.all_bikes.append({self.counter : dict_bikes})
self.counter = self.counter + 1
def show_all_bikes(self):
print(self.all_bikes)
class user(bikes):
def __init__(self):
self.user_make = make = input("Enter the Company name: ")
self.user_name = name = input("Enter the Bike name: ")
self.user_model = model = input("Enter the Model name: ")
super().__init__(make,name,model)
bikes.total_bikes(self)
while True:
menu = input("Enter Add,View to Add a new bike and View all bikes: ")
if menu.upper() == "ADD":
add_bike = user()
elif menu.upper() == "VIEW":
add_bike.show_all_bikes()
else:
print("Invalid Command")
This construct
while True:
menu = input("Enter Add,View to Add a new bike and View all bikes: ")
if menu.upper() == "ADD":
add_bike = user()
elif menu.upper() == "VIEW":
add_bike.show_all_bikes()
else:
print("Invalid Command")
if ADD is choice then new instance of user class is created, which has empty all_bikes. You need to equip your class with seperate method for adding bike and __init__ and createdinstance of user class before entering while loop.
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