This question already has answers here:
Returning a value from function?
(2 answers)
Closed 4 years ago.
im trying to make a simple text game for a school project and also make the code somewhat clean therefore I started using functions and classes.
The problem is im stuck on trying to access a variable from a function that asks the user for their username.
Here is my code
def playername():
print("What is your name?")
playername = input()
how can I access the playername variable without running the whole function again so once I run it at the start and get the username I can use that same input username later on in the code?
You can define your function like this:
def get_playername():
playername = input('Whats is your name? ')
return playername
Then,use it:
name = get_playername()
store it as a variable outside of function. for example string playerName = playername() and add return playername to the end of the function "playername"
def playername():
print("What is your name?")
playername = input()
return playername
def main():
playerName = playername()
print(playerName)
main()
Firstly, it's a good idea to name your function and variables differently. So, I'd use something like "name" to store the name of the player.
You can print the question and store the value at the same step with the input() function
def playername():
name = input("Enter you name: ")
print("Hello {}".format(name))
return name
name = playername()
playername variable is limited (scoped) to playername function, it cannot be accessed from outside the function
You should return the playername value, so that the function caller can store and use this value
def playername():
print("What is your name?")
playername = input()
return playername
def main():
my_playername = playername()
# use my_playername as much as you like
...
main()
Returning values from a function is a basic programming skill. I strongly recommend that you work through class materials or a tutorial on the topic.
def get_player_name():
print("What is your name?")
name = input() # Do NOT give two program objects the same name.
return name
# Main Program
victim_name = get_player_name()
Related
This question already has answers here:
Cannot change global variables in a function through an exec() statement?
(3 answers)
Closed 2 years ago.
I'm learning python and trying to use a function to choose and change a global variable.
I want to use the console to choose which variable to change and then choose the new value.
I'm using global inside the function to access the variables and I'm using exec() to proceed with the desired modification captured through input(). But something is not working.
Can someone please figure out what is wrong here?
name = "John"
age = 45
gender = "male"
def identify_yourself():
print("My name is " + name + ".")
print("I'm " + str(age) + " years old.")
print("I'm " + gender + ".")
def change_something():
global name, age, gender
something = input("Which variable do you want to change?\n> ")
# I then input "name"
new_value = input("Change to what?\n> ")
# I Then input "Paul"
exec(something + " = '" + new_value + "'")
identify_yourself()
identify_yourself()
# This first prints...
#
# My name is John.
# I'm 45 years old.
# I'm male.
change_something()
# On the second time this SHOULD print...
#
# My name is Paul.
# I'm 45 years old.
# I'm male.
#
# ... but it's not working.
# It keeps printing "My name is John" even after I run the change_something() function
The exec() uses globals() and locals() as defaults for their global and local variables. It defaults to changes in the locals(), not the globals. You therefore have to explicitly tell it to overwrite globals. You can do this the following way:
exec(something + " = '" + new_value + "'", globals())
Im making an AI/Chat Bot from scratch and I want to make code where the bot uses dictionaries of its known stuff and uses them to talk to the user. However, when I try to make the answer appear on the screen using a variable, an error appears
Ive tried making the code so that when the user writes down something in the greetings dictionary, the bot will say "Hello!". But when i run the code, this error comes up: 'set' object is not callable' on line 7 of the code.
MY_NAME = input("What is my name? \n")
Greeting = {"Hi", "Hello", "Hey"}
while True:
input = input("Talk to " + MY_NAME + "\n")
if input == Greeting():
print ("Hello!")
I want the fixed code to this. Thankyou!
Problems:
Greeting is a set. You use it like calling a function which results in your error.
Change variable input because it conflicts with the original input function. In the next iteration, it will throw error as "str object is not callable".
You need a membership check:
while True:
inp = input("Talk to " + MY_NAME + "\n")
if inp in Greeting:
print ("Hello!")
Try using in, and rename input to inp since input will override the default input keyword:
MY_NAME = input("What is my name? \n")
Greeting = {"Hi", "Hello", "Hey"}
while True:
inp = input("Talk to " + MY_NAME + "\n")
if inp in Greeting:
print ("Hello!")
So I am a beginner to Python (previous experience with Java), and I was creating a simple OOP program. Here is my class:
from Tools.scripts.treesync import raw_input
class Info:
def startGame(self):
name = raw_input('What is your name?\n')
age = raw_input("What is your age?\n")
color = raw_input("What is your favorite color\n")
print("Your name is %s, your age is %s, and your favorite color is %s" % (name, age, color))
return Info
class App:
def build(self):
game_app = Info()
game_app.startGame()
return game
if __name__ == "__main__":
obj = App()
game = Info()
obj.build()
This is the output:
Your name is Chris
, your age is 18
, Sand your favorite color is Red
I am confused as to why it is printing on 3 lines? Is there any way to print this onto a single line?
The raw_input you're importing is keeping the CRLF in the input you entered. Why not use the built-in input() function (you are using Python 3, right)?
>>> from Tools.scripts.treesync import raw_input
>>> raw_input("> ")
> abc
'abc\n'
>>> input("> ")
> abc
'abc'
Also, Python is not Java. No need to put everything in classes.
You are using raw_input, which includes a line ending to the string, you can just use input() to obtain the string without a line ending.
Currently my code has a main menu, it asks the user to choose from the option it prints out, this is inside a 'def' function. At the end of the variable I define, there is a input prompt to ask the user for their input named 'option'. However when i run the code i get a syntax. i.e:
The code:
def main_menu():
print ("\nMain Menu ")
print ("\n1. Alphabetical Order (Highest Score only) = 'alpha'")
option = input ("\nEnter your Option: ")
main_menu()
option_class = input("\nWhich Class do you wish to preview: ")
one = "1.txt"
if option == "alpha".lower():
if option_class == "1":
with open (one, "r") as r:
for line in sorted(r):
print (line, end='')
when running the code I receive the following syntax:
NameError: name 'option' is not defined
option is locally defined. You can return entered value from function and assign it to option like this:
def main_menu():
print ("\nMain Menu ")
print ("\n1. Alphabetical Order (Highest Score only) = 'alpha'")
return input ("\nEnter your Option: ")
option = main_menu()
Your variable option is only defined locally in your function main_menu(), not globally.
The variable option is only local to the function main_menu. You can fix it by making option global:
def main_menu():
global option
#...
option = '...'
See: Global vs local variables
Like I said in my previous question, I'm a python amateur. I've made a couple silly mistakes. I'm attempting to make a highly simple greeting program using Python 3.4 however I have encountered an error. The error I have is:
UnboundLocalError: local variable 'lastNameFunction' referenced before assignment
Here's my code (I know I probably don't need to post it all, but there isn't much of it):
def main():
import time
running = True
while (running):
firstNameInput = input("What is your first name?\n")
firstName = firstNameInput.title()
print ("You have entered '%s' as your first name. Is this correct?"%firstName)
time.sleep (1)
choice = input("Enter 'Y' for Yes or 'N' for No\n")
if(choice.upper() == "Y"):
lastNameFunction()
elif(choice.upper() == "N"):
main()
def lastNameFunction():
lastNameInput = input("Hi %s. Please enter your last name. \n"%firstName)
lastName = lastNameInput.title()
if __name__ == '__main__':
main()
I'd appreciate any help and advice! Please take into consideration I am really new to this stuff. I'm also not quite sure on having a function inside of a function, but I thought it would be a fix so that the 'firstName' was available when entering the 'lastName'.
Thanks in advance! :)
You need to move the lastNameFunction declaration somewhere before you call it using lastNameFunction(), e.g.:
def main():
import time
running = True
while (running):
firstNameInput = input("What is your first name?\n")
firstName = firstNameInput.title()
print ("You have entered '%s' as your first name. Is this correct?" % firstName)
time.sleep (1)
choice = input("Enter 'Y' for Yes or 'N' for No\n")
def lastNameFunction():
lastNameInput = input("Hi %s. Please enter your last name. \n" % firstName)
lastName = lastNameInput.title()
if(choice.upper() == "Y"):
lastNameFunction()
elif(choice.upper() == "N"):
main()
if __name__ == '__main__':
main()
You can also move it outside the main function, but you will then need to pass the firstName in using the function arguments:
def lastNameFunction(firstName):
lastNameInput = input("Hi %s. Please enter your last name. \n" % firstName)
lastName = lastNameInput.title()
def main():
...
lastNameFunction(firstName)
...
Move your lastNameFunction to somewhere before the call. Ideally, you would place this above the main function.
def lastNameFunction():
lastNameInput = input("Hi %s. Please enter your last name. \n"%firstName)
lastName = lastNameInput.title()
def main():
...
The problem is you called lastNameFunction() before you defined it in the while loop. Try defining the function outside the while loop.
The organisation of the whole program seems a little bit off.
Imports usually go at the top of the module.
Functions defined in functions are usually just for closures, which you a) don't need here and b) might be a bit advanced for your current experience level.
Recursive calls like your calling main() from within main() are wrong. When you adopt that style of control flow instead of a loop, you will eventually run into limitations of recursive calls (→ RuntimeError). You already have the necessary loop, so simply leaving out the elif branch already asks the user again for the first name.
running isn't used anywhere, so you can remove it and just use while True:.
I would move asking the user for ”anything” + the question if the input was correct into its own function:
def ask_string(prompt):
while True:
result = input(prompt).title()
print("You have entered '{0}'. Is this correct?".format(result))
choice = input("Enter 'Y' for Yes or 'N' for No\n")
if choice.upper() == 'Y':
return result
def main():
first_name = ask_string('What is your first name?\n')
last_name = ask_string(
'Hi {0}. Please enter your last name.\n'.format(first_name)
)
print(first_name, last_name)
if __name__ == '__main__':
main()