How to accept user input from within a function? - python

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)

Related

Player not defined

Im having some issues with player not defined errors this is the error and the codes i have putten links to the pictures of it.Im pretty new at python and i don't understand most of the errors,i will be happy if someone could help.
Player not defined errors
Code
Code
I have created a minimal working code about your attached pictures. Mostly your global variable handling was not correct. You can find my comments in the below code as comments.
Code:
# Define global variable
current_player = None
class Player(object):
def __init__(self, name):
self.name = name
self.other = 100
def main():
option = input("Option: ")
if option == "1":
start()
def start():
# Use the global variable inside the function.
global current_player
user_name = input("Name: ")
# Assign the Player instance to the global variable.
current_player = Player(name=user_name)
start1()
def start1():
# Use the global variable inside the function.
global current_player
# Get the "name" attribute of the "Player" object.
print("Hello my friend: {}".format(current_player.name))
main()
Output:
>>> python3 test.py
Option: 1
Name: Bill
Hello my friend: Bill
>>> python3 test.py
Option: 1
Name: Jill
Hello my friend: Jill
Note:
I suggest to get rid of the global variable usage. Pass the required variables as parameters. I have implemented a version which doesn't contain global variables.
def start():
user_name = input("Name: ")
# Assign the Player instance to the global variable.
current_player = Player(name=user_name)
start1(current_player)
def start1(current_player_info):
# Get the "name" attribute of the "Player" object.
print("Hello my friend: {}".format(current_player_info.name))
PS:
In your next question, do not attach or link pictures. Please add a minimal code and your issue (traceback). Please read it: https://stackoverflow.com/help/how-to-ask

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()

Call a function from within another function in Python without using class

I'm stuck at calling one function from within other function. I know this question was asked many time here but I couldnt find the right answer.
Here's an example:
Make a function shout(word) that accepts a string and returns that string in capital letters.
def shout(word):
return word.upper()
shout("bob")
Make a function introduce() to ask the user for their name and shout it back to them. Call your function shout to make this happen.
def introduce():
name = input("What's your name: ")
print(f"Hello {name}")
introduce()
My question is: How can I call shout() func from within introduce() func without using class? So the result looks like this:
What's your name?
Bob
HELLO BOB
Thank you for your time and answers.
Just call function shout.
def shout(word):
return word.upper()
def introduce():
name = input("What's your name: ")
name = shout(name)
print(f"Hello {name}")
introduce()
You call functions from inside other functions the same way you call them from outside functions. Put the function name first, put the argument(s) in parentheses.
def introduce():
name = input("What's your name: ")
print(shout(f"Hello {name}"))
You can just call shout() function inside introduce():
def shout(word):
return word.upper()
def introduce():
name = input("What's your name: ")
print(shout(f"Hello {name}")) << just like this.

keeping changed data global variables

I have a global variable that I change in a function but when I call the global variable later in code in a different function, it doesn't store the change when the variable is first called:
name = "noname"
def username():
print ("It would help if I had a name to go by, please enter a name.")
global name
name = input()
def character():
global name
print ("Character overview:\nName:"+name+"")
And the output of character() is noname instead of the input.
Is there a way keeping the change in the first function?
This works for me.
name = "noname"
def user():
global name
name = input()
def char():
# Works with or without global here
print(name)
user()
char()

python accessing another function variable error

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)

Categories

Resources