[英]Setting function to call raw_input in python
How do I make this work?我如何使这项工作? I'm trying to set a global function so that I can simply call it later for raw input rather than calling the raw input where I need it.我正在尝试设置一个全局函数,以便我可以稍后为原始输入调用它,而不是在需要的地方调用原始输入。
I think I have the essence to an extent of what I need but I'm stumped as to how to format this, or if it's even possible.我认为我在一定程度上掌握了我所需要的本质,但我对如何格式化它,或者是否可能进行格式化感到困惑。
Thank you in advance.先感谢您。
def choice_1():
choice_1 == raw_input("> ")
def choice_1a():
choice_1a = raw_input("> ")
def choice_1b():
choice_1b = raw_input("> ")
edit: I don't think I was clear enough in the purpose of my question.编辑:我认为我的问题的目的不够清楚。 Here's an update of the code I'm working on, perhaps this will clear things up.这是我正在处理的代码的更新,也许这可以解决问题。
print "You've arrived at your desk"
def choice_1(one):
choice_1a = raw_input("< ")
def choice_1a():
choice_1a = raw_input("> ")
def choice_1b():
choice_1b = raw_input("> ")
#Choice_1
print "What do you want to do?"
print "We can \n1. Read\n2. Draw\n3. Work on homework"
print choice_1
#choice 1 branch 1
if choice_1 == "1":
print "What book should we read today?"
print "We can read\n1. Tom Sawyer\n2. Quantum Physics \n3. Ray Bradbury"
print choice_1a
if choice_1a == "1":
print "Great choice!"
if choice_1a == "2":
print "Heavy stuff there."
if choice_1a == "3":
print "Entertaining author, that one there!"
else:
print "Let's go to the library, maybe they'll have that one."
#choice 1 branch 2
if choice_1 == "2":
print "What would you like to draw?"
print "We can draw a\n1. Tiger\n2. Fish\n3. Bear "
print choice_1b
if choice_1b == "1":
print "You drew a Tiger!"
if choice_1b == "2":
print "You drew a Fish!"
if choice_1b == "3":
print "You drew a Bear!"
else:
print "Time for some improvisation."
#choice 1 branch 3
if choice_1 == "3":
print ""
does this clear some confusion?这是否清除了一些混乱?
This will do what you want.这会做你想做的。 As @SethMMorton had noted, you had missed out on a return
正如@SethMMorton 所指出的,你错过了return
def choice():
return raw_input('> ‘)
By the way, this is not a nice thing to do, because, to someone reading your code, it will not be immediately clear what choice
is doing.顺便说一句,这不是一件好事,因为对于阅读您的代码的人来说,不会立即清楚choice
在做什么。
I did this:我这样做了:
print 'Your name is :' + choice()
And it worked as expected.它按预期工作。
EDIT : You should make your if statements thus:编辑:你应该这样做出你的 if 语句:
if choice() == "1"
: if choice() == "1"
:
def multiplier(x, y):
ans = x * y
print ans
This would be a use for a function and when ready to use it you would call it like this这将是一个函数的用途,当准备使用它时,你会像这样调用它
multiplier(5, 10)
50
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.