python accessing another function variable error - python

I am trying to get input from one function and dispaying it in another function but i could not get the expected result
class Base(object):
def user_selection(self):
self.usr_input = input("Enter any choice")
user_input = self.usr_input
return user_input
def switch_selection(user_input):
print user_input
b = Base()
b.user_selection()
b.switch_selection()
When i execute this program i get
Enter any choice1
<__main__.Base object at 0x7fd622f1d850>
I should get the value which i entered but i get
<__main__.Base object at 0x7fd622f1d850>
How could i get the value which i entered?

def switch_selection(user_input):
print user_input
..
b.switch_selection()
You may notice that you're not passing any argument into switch_selection when calling it, yet you're expecting to receive one argument. That's something of a cognitive disconnect there. You happen to actually receive an argument though, which is b. An object method in Python receives its object instance as its first parameter. The argument you're receiving is not user_input, it's self. That's what you're printing, that's the output you're seeing.
Two possibilities to fix this:
class Base(object):
def user_selection(self):
self.user_input = input("Enter any choice")
def switch_selection(self):
print self.user_input
or:
class Base(object):
def user_selection(self):
return input("Enter any choice")
def switch_selection(self, user_input):
print user_input
b = Base()
input = b.user_selection()
b.switch_selection(input)

Try this Code Working perfect for me,
class Base(object):
def user_selection(self):
self.usr_input = input("Enter any choice")
user_input = self.usr_input
return user_input
def switch_selection(self,user_input):
print user_input
b = Base()
g=b.user_selection()
b.switch_selection(g)

Related

How to accept user input from within a function?

I am new to Python. This code snippet is supposed to define a function getinput(), which is supposed to accept user input and put that value into variable stuff. Then I call the function, and print the value of the variable stuff.
def getinput():
stuff = input("Please enter something.")
getinput()
print(stuff)
The problem is that the program is not working as expected and I get the error:
NameError: name 'stuff' is not defined
In contrast, without defining and calling a function, this code works just fine:
stuff = input("Please enter something.")
print(stuff)
And I can't figure out why that should be so.
Please help. I am learning Python to coach my kid through his school course, and I am using Google Colab with Python 3.7.11, I believe.
Variables defined within a function are local in scope to that function, however, you can return values from functions so you can do what you want like this:
def getinput():
sth = input("Please enter something.")
return sth
stuff = getinput()
print(stuff)
There is a lot of possibilities of printing stuff that you could do -
def getinput():
stuff = input("Please enter something.")
print(stuff)
getinput()
You can print it inside function and call it
def getinput():
stuff = input("Please enter something.")
return stuff
print(getinput())
You can return the stuff and print it (BEST Solution)
def getinput():
global stuff
stuff = input("Please enter something.")
getinput()
print(stuff)
Or you could use global keyword
In Python, there is a concept of the scope of a variable. You create a stuff variable inside a function and the variable can only be used there. There is no such variable outside the function. You can do this:
def getinput():
getinput.stuff = input('Please enter something')
getinput()
print(getinput.stuff)
Or you can return value from function:
def getinput():
stuff = input('Please enter something')
return stuff
s = getinput()
print(s)

Error while calling python function, TypeError: returnbook() missing 1 required positional argument: 'self'

I have created a python program where customers can return book and borrow book from Library, while executing I gets error * TypeError: borrow() missing 1 required positional argument: 'self' *
What changes I should make to execute the program successfully ?
I will call returnbook() function initially as the library have no books at present.
class Library:
def __init__(self):
self.availablebook = availablebook
def reducebook(self,book):
if book in self.availablebook:
self.availablebook.remove(book)
print('book is removed')
def addbook(self,book):
self.availablebook.append(book)
print('book added')
class Customer:
def borrow(self):
print('enter book')
book = input()
Library.reducebook(book)
def returnbook(self):
print('enter book')
book = input()
Library.addbook(book)
while True:
print('enter 1 for add book,2 for borrow book,3 to exit')
self.x = int(input())
if(x==1):
Customer.borrow()
elif(x==2):
Customer.returnbook()
else:
print('exiting')
quit()
Create an instance of the Customer class, do not use the class directly:
customer = Customer()
customer.borrow()
customer.returnbook()
availablebook should be a list in __init__ function.
self.availablebook = []
Also, Modify your while loop.
while True:
print('enter 1 for add book,2 for borrow book,3 to exit')
x = int(input())
if(x==1):
Customer().borrow()
elif(x==2):
Customer().returnbook()
else:
print('exiting')
quit()
There are some mistakes in your code :
self.x is not an attribute from a class. You can just write x.
You have to add the availablebook variable as an input of init function
You get a missing argument because you do not create your Library and Customer classes the good way. You can write Library([]).borrow() if you consider adding availablebook input, else just write Library().borrow().
I think the best is to create a library before you loop : my_lib = Library([])
Then add a library input in your Customer functions in order to edit the library you want and hence avoid creating a new library each time.
Here is the code I would suggest you :
class Library:
def __init__(self, availablebook):
self.availablebook = availablebook
def reducebook(self, book):
if book in self.availablebook:
self.availablebook.remove(book)
print('book is removed')
def addbook(self,book):
self.availablebook.append(book)
print('book added')
class Customer:
def borrow(self, library):
print('enter book')
book = input()
library.reducebook(book)
def returnbook(self, library):
print('enter book')
book = input()
library.addbook(book)
my_lib = Library([])
while True:
print('enter 1 for add book,2 for borrow book,3 to exit')
x = int(input())
if(x==1):
Customer().borrow(my_lib)
elif(x==2):
Customer().returnbook(my_lib)
else:
print('exiting')
quit()

How to end a method in a class if user input is blank

I'm new to programming so bear with me please!
I'm creating a class and having trouble getting the return message to show when the users input is empty.
Instead of returning my message it's just throwing me an error.
I want my code to return "please try again" and end, if the user input is blank.
Code:
class BankAccount():
def __init__(self):
# asking for a name
self.name = str(input("Hello! Welcome to the Bank of Alex.\nWhat is your name?"))
if self.name == "":
return "please try again"
else:
print(f"\nWelcome, {self.name.title()}.")
TypeError Traceback (most recent call last)
in
----> 1 account = BankAccount()
TypeError: init() should return None, not 'str
Your program structure is incorrect for using a class. You should not create an object until you know the input is valid. Have the calling program check it:
name = ""
while name == "":
name = input("Enter your name")
if name:
acct = BankAccount(name)
break
else:
print("Please try again")
Your __init__ method then merely crates the account -- no name check. This method implicitly returns the created object; you're not allowed to return anything else.
I was able to solve this with help from #Prune. I used the while loop he mentioned and put it under __ init __
So if user input is blank it will just keep prompting for an input. Not a perfect solution but it works.
class BankAccount():
def __init__(self):
self.name = input("Hello! Welcome to the Bank.\nWhat is your name?")
while self.name == "":
self.name = input("Please enter your name")
if self.name:
print(f"\nWelcome, {self.name.title()}.")

"AttributeError: 'list' object has no attribute 'SMSMessage'"

I have tried many ways but can't seem to get the length of my list through the method in my class my code:
SMSStore = []
unreadMessage = []
class SMSMessage(object):
def __init__(self, hasBeenRead, messageText, fromNumber):
self.hasBeenRead = hasBeenRead
self.messageText = messageText
self.fromNumber = fromNumber
hasBeenRead = False
def markAsRead(self, hasBeenRead):
hasBeenRead = True
def add_sms(self):
newMessage = (self.hasBeenRead, self.messageText, self.fromNumber)
return SMSStore.append(newMessage)
def get_count():
return len(SMSStore)
def get_message(self, i):
hasBeenRead = True
return SMSStore[i][1]
def get_unread_messages(i):
for i in SMSStore:
if SMSStore[i][0] == False:
unreadMessage.append(SMSStore[i])
print unreadMessage
def remove(self, i):
return SMSStore.remove(i)
This is how a message in the list would ideally look like:
#sample = SMSMessage(False, "Hello friend!", 0742017560)
And here is how the class is used
userChoice = ""
while userChoice != "quit":
userChoice = raw_input("What would you like to do - read/send/quit?")
if userChoice == "read":
print len(SMSStore)#this way i can get the length of the list anyway without using get_count
SMSStore(get_count()
unreadChoice = raw_input("Would you like to retrieve all unread messages or one of your own choice? - all unread/custom ")
if unreadChoice == "custom":
i = int(raw_input("Please enter which message number you want to read: "))
print get_message(i) #I dont understand how i works and how to get it working with the object definition
elif userChoice == "send":
messageText = raw_input("Please type in your message: ")
fromNumber = raw_input("Please type in the number it was sent from ")
newObject = SMSMessage(False, messageText, fromNumber)
newObject.add_sms()
print SMSStore
elif userChoice == "quit":
print "Goodbye"
else:
print "Oops - incorrect input"
I can just use len(SMSStore) but I want to be able to use the method inside the class to get it. Can point out any mistakes?
This was the question asked:
Open the file called​  sms.py​
Create a class definition for an SMSMessage which has three variables:
hasBeenRead, messageText, and fromNumber. 
The constructor should initialise the sender’s number. 
The constructor should also initialise hasBeenRead  to false
Create a method in this class called MarkAsRead which should change hasBeenRead to true.
Create a list called SMSStore to be used as the inbox.
Then create the following methods:
add_sms - which takes in the text and number from the received sms to
make a new SMSMessage object. 
get_count - returns the number of messages in the store.
get_message - returns the text of a message in the list.Forthis, allow the
user to input an index i.e. GetMessage(i) returns the message
stored at position i in the list. Once this has been done,
hasBeenRead should now be true. 
get_unread_messages - should return a list of all the messages which
haven’t been read. 
remove - removes a message in the SMSStore. 
Now that you have these set up, let’s get everything working! 
in your SMSMessage class
def get_count(self, *args):
return len(SMSStore)
in your script
# create instance
sms_msg = SMSMessage() # init arg needed
print sms_msg.get_count()
SMSStore is a global variable, you could remove get_count from SMSMessage scope
SMSStore = []
unreadMessage = []
class SMSMessage(object):
...functions...
def get_count(*args):
return len(SMSStore)
and call it regularly OR
ls = range(20)
class A(object):
# declare default value for your arguments
def __init__(self, hasBeenRead = False, messageText = "", fromNumber=0):
self.a = a
self.b = b
#using classmethod
#classmethod
def get_count(cls, *args):
return len(ls)
print A.get_count()

Returning values from callback(s) in Python

I am currently looking at trying to use a callback in Python.
What I would like to do is return a value from the callback and then use this return value for conditional processing. So for example if the user enters "Y" I would like to print something to the console.
As I am new to Python the code below is as close as I can get currently but:
a) I am not sure if it is the Pythonic way of doing it
b) the correct way of doing it?
class Observable:
def subscribe(self,callback):
self.callback = callback
def fire(self):
self.callback()
class CallBackStuff:
def doCallback(self):
userInput = raw_input("Please enter Y or N?")
return userInput
if __name__ == '__main__':
s = CallBackStuff()
o = Observable()
o.subscribe(s.doCallback)
t = o.fire()
print t
The easiest way I can think of to do this in your code is to just store the input as
a variable in the CallBackStuff object. Then after you've called the call-back function, you can just access the input data from the CallBackStuff instance. Example below.
class Observable:
def subscribe(self,callback):
self.callback = callback
def fire(self):
self.callback()
class CallBackStuff:
storedInput = None # Class member to store the input
def doCallback(self):
self.storedInput = raw_input("Please enter Y or N?")
if __name__ == '__main__':
s = CallBackStuff()
o = Observable()
o.subscribe(s.doCallback)
o.fire()
print s.storedInput # Print stored input from call-back object
class Observable(object):
def __call__(self, fun):
return fun()
class Callback(object):
def docallback(self):
inp = raw_input()
return inp
if __name__ == "__main__":
print Observable()(Callback().docallback)

Categories

Resources