I'll start by saying that I did look up answers to this question and unfortunately, I just couldn't understand them or they didn't seem to work for me. This is of course down to me rather than the people who answered the question, so I do apologise in advance.
So pretty much I'm trying to call a variable that is assigned by the user from one function to the other, I'll give an example:
def function_one():
a = input("What is your name?")
return a
def function_two():
print("Nice to meet you, "a)
function_one()
function_two()
This of course does not work and I'm sure that is down to my own stupidity, I wasn't sure why at first because I saw other people saying to simply return the variable, which I did!
I also tried calling the variable from the other function, for example:
def function_two()
a = function_one()
but I realised that was pretty stupid since I'm just assigning that function as a, so it's not going to work.
I'd appreciate some insight, I know these are not the kind of questions you'd expect but yeah... I'm clueless.
I think what you want to do is take user input, store it in a variable, then greet the user using that variable:
def ask_for_users_name():
name = input("What is your name?")
return name
def greet_user(name):
print("Nice to meet you, " + name)
users_name = ask_for_users_name()
greet_user(users_name)
One important thing to note is that I had to concatenated the name with the string "Nice to meet you, " using the + operator.
Edit:
To answer to the question in the comments, you could do something like this in that case:
def ask_for_user_info():
name = input("What is your name?")
age = input("What is your age?")
return name, age
user_name, user_age = ask_for_user_info()
Best practice is to make functions that only do one thing, for many reasons, one is that the name of the function normally replaces any need for inline comments:
def ask_for_user_name():
name = input("What is your name?")
return name
def ask_for_user_age():
age = input("What is your age?")
return age
In the case of the ask_for_user_info() method, it isn't immediately clear what exactly it is doing from the name.
Edit 2:
You could then use those two functions like this, in either order:
age = ask_for_user_age()
name = ask_for_user_name()
or
name = ask_for_user_name()
or
age = ask_for_user_name()
you do have it. this should work.
def function_two():
a = function_one()
print('hi {}'.format(a))
then
>>>function_two()
Another way is to use this:
def ask_for_users_name():
name = input("What is your name?")
greet_user(name)
def greet_user(user_name):
print("Nice to meet you,"+user_name)
ask_for_users_name()
You merely call ask_for_users_name() at the end.
Edit:
greet_user_() is a void function, which means it does not return anything. In this case, all it does is receive input passed to it and prints it. If you want to perform other operations, you can pass it additional parameters, or keep it the way it is.
Version 1:
def ask_for_users_name():
name = input("What is your name?")
age = int(input("What is your age? "))
print("Your age is ", age)
greet_user(name)
def greet_user(user_name):
print("Nice to meet you,"+user_name)
ask_for_users_name()
In version 1, we are still utilizing greet_user() to just print one thing, and performing another print operation in ask_for_users_name().
Version 2:
def ask_for_users_name():
name = input("What is your name?")
age = int(input("What is your age? "))
greet_user(name, age)
def greet_user(user_name, user_age):
print("Nice to meet you,"+user_name)
print("Your age is", user_age)
ask_for_users_name()
In version 2, we are passing both age and name to greet_user(), which in turn prints out the passed variables. I hope this helps.
Related
I need to check whether the input is empty or not and cannot use if statements.
print("What is your name?")
name = input()
print("Hi, {}".format(name))
Use a while loop that only terminates if the length of name is 0:
name = ""
while len(name) == 0:
print("What is your name?")
name = input()
print("Hi, {}".format(name))
You could try something like this:
print("What is your name?")
name = input()
name = "Hi, {}".format(name)
while name == "Hi, ":
name = "You didn't key in any name"
print(name)
This is ugly, but it will produce the exact output you want.
The idea is to use a loop that will run only once, and will only run if the name variable is empty after input() is called.
I would recommend assert. It will stop your programming to continue running when the requirement is not met.
print("What is your name?")
name = input()
assert name != "", "You didn't key in any name"
print("Hi, {}".format(name))
What is your name?
AssertionError: You didn't key in any name
As my previous answer with the while loop received some criticism, I decided to demonstrate a less "naive" but perhaps more complicated solution, that actually does not use any kind of direct conditional operator:
print("What is your name?")
name = input()
answer = {}
answer[len(name)] = "Hi, {}".format(name)
answer[0] = "You didn't key in any name"
print(answer[len(name)])
Here we rely on a dictionary with the length of the input as an integer key.
We don't even need to compare the length to 0, we just overwrite the 0 key with the error message.
If input length is greater than 0, the name will be under its own key, and will be printed, if not, the empty "Hi" string will be replaced.
Would this ever be useful in the real world?
Probably not, unless there are many more than 2 options.
Does it comply with the task requirements?
Yes. It gives the desired output.
Why does my program return "function name at 0x3424243" whenever I call my defined function?
To let you know that 3424243 isn't the actual number, but either way it shows a very random number, whenever I call my defined function.
My code:
print("WELCOME!")
name = input("\nWhat is your name? ")
print("\nHello " + name + "!")
def name():
print(name)
print("\nGoodbye", name)
How can I fix this so that it says goodbye to the name I typed in. The code above generates "Goodbye, function name at 0x3424243>"
Don't use the same name for the input variable and the function.
First:
name = input("\nWhat is your name? ")
Will run and name will point to the input string.
When:
def name():
Is evaluated name will start pointing to the function instead of the input string.
Modify your code like this:
print("WELCOME!")
name = input("\nWhat is your name? ")
print("\nHello " + name + "!")
def fn(): # Changed the name of the function to avoid the clash.
return name # Return the name.
print("\nGoodbye", fn())
Output:
WELCOME!
What is your name?
Hello Dipen!
Goodbye Dipen
After reading your comments to Dipens's answer, I think what you are looking for is something like this:
print("\nGoodbye %s" % fn())
But in that case you don't want fn to actually print anything, only to return a string. In your original example the code would execute along the lines of the following:
print("text", print("name"))
... which would result in the same/similar behavior as you're experiencing.
I'm pretty new to coding and I'm making an adventure "game" to help me learn. The player has a bit of dialogue to get through and a decision to make, which leads to different choices, two of which ask for their name. I can't seem to make the player_name variable appear in the next function, it just stays blank. I just want it as a global variable where I can continue to use it throughout the game.
player_name = ("")
def path_2():
print("I found you lying in the hallway.")
print("Maybe I should have left you there...")
player_name = input("What is your name? : ")
return player_name
def path_1():
print("It's a pleasure to meet you.")
print ("My name is Azazel. I am the warden of this place.")
print ("I found you lying in the hallway,")
print ("bleeding profusely from you head there.")
print ("")
player_name = input("What is your name? : ")
return player_name
def quest():
print(("This is a long story ")+str(player_name)+(" you'll have to be patient."))
enter()
When you're doing player_name = input("What is your name? : "), you're re-defining player_name in the scope of your function, so it's no longer pointing to the global variable, what you could do is:
def path_2():
print("I found you lying in the hallway.")
print("Maybe I should have left you there...")
global player_name
player_name = input("What is your name? : ")
Notice that you don't need to return player name, because you're modifying the global variable.
use global keyword before using the same variable in a function
You have a couple of concepts here that you'll need to sharpen up on to make this work. The first is the scope of a variable. The second is parameters and return values of functions. Briefly (you should research this more), the variables you create in a function are not visible outside that function. If you return a value, then you can catch it from the calling location. Using global variables is possible, but usually not the best approach. Consider:
def introduce():
player_name = input("tell me your name: ")
print("welcome, {}".format(player_name))
return player_name
def creepy_dialogue(p_name, item):
print("What are you doing with that {}, {}?".format(item, p_name))
# start the story and get name
name = introduce()
weapon = "knife"
creepy_dialogue(name, weapon)
Here is my approach to simulate a goto sequence. Is there a more eloquent way?
PS: the idea with storing the variable in a class variable was just for fun (because of the .(format()) accessing story.
n=0
while n==0:
print("Whats your height?")
height=input()
print("Whats your age?")
age=input()
class loop:
h=height
a=age
print("Your height is {answer.h}".format(answer=loop()))
print("Would you like to continue?")
answer=input()
if answer=="yes":
++n
print("alright ONE MORE TIME!")
else:
print("see you")
Solution
class Person():
def __init__(self,name, height, age):
self.name = name
self.height = height
self.age = age
while True:
name = input("What's your name?\n")
height = input("What's your height?\n")
age = input("What's your age?\n")
user = Person(name, height, age)
print(f"\nHello {(user.name).title()}, your height is {user.height} and you are" \
f" {user.age} years old!")
answer = input("\nWould you like to continue?('yes' or 'no')\n")
if answer == 'yes':
print("alright ONE MORE TIME!")
continue
else:
print("See you!")
break
This is how I would go about this, although there is no reason to have a class here for what you are trying to accomplish, but since you had it in there I'm assuming you were using it as practice, so I threw in a class here as well.
Edit
Ah you mentioned the class was for fun, not claiming I used class in the best fashion here but it's an improvement for the way you attempted, would definitely look over proper utilization of class.
I have been trying to figure this out for way too long! What to do?
def fallBack(submission):
if (submission == ""):
submission = "fixed!"
return(submission)
name = input("What is your name?")
(fallBack(name))
location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")
I keep having the last input just print out nothing...
You need to store the result of fallBack().
Also, change fallBack() to return the original value if it is non-null:
def fallBack(submission):
if not submission:
return "fixed!"
else:
return submission
Then, use it like this:
name = fallBack(input("What is your name?"))
Just remove the brackets around fallBack(name)
def fallBack(submission):
if (submission == ""):
submission = "fixed!"
return submission
name = input("What is your name?")
name = fallBack(name)
location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")
Also remember that if using python 2.7 you should use raw_input instead of input
I'm not sure what you want to do, but I think this would do it:
def fallBack(submission):
if (submission == ""):
submission = "fixed!"
return (submission)
name = input("What is your name?")
name = fallBack(name)
location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")
Your two mistakes were not to return anything in case there is nothing to fix, and not to assin the value returned by the function.
By the way, there is a much more idiomatic way of doing this in Python:
name = input("What is your name?")
name = name or 'fixed!'
location = input("Hi "+name+"! Nice to meet you, I live inside a computer, where do you live?")
The second line tests if converting name to a boolean, and, if it returns False (for a string, it is equivalent to testing if it is not empty), replace it with 'fixed!'
The return is not well aligned! You are not returning anything unless submission is empty! :-)
def fallBack(submission):
if (submission == ""):
submission = "fixed!"
return(submission)