簡體   English   中英

設置函數在python中調用raw_input

[英]Setting function to call raw_input in python

我如何使這項工作? 我正在嘗試設置一個全局函數,以便我可以稍后為原始輸入調用它,而不是在需要的地方調用原始輸入。

我認為我在一定程度上掌握了我所需要的本質,但我對如何格式化它,或者是否可能進行格式化感到困惑。

先感謝您。

   def choice_1():
        choice_1 == raw_input("> ")
    def choice_1a():    
        choice_1a = raw_input("> ") 
    def choice_1b():    
        choice_1b = raw_input("> ")

編輯:我認為我的問題的目的不夠清楚。 這是我正在處理的代碼的更新,也許這可以解決問題。

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 ""

這是否清除了一些混亂?

這會做你想做的。 正如@SethMMorton 所指出的,你錯過了return

def choice():
    return raw_input('> ‘)

順便說一句,這不是一件好事,因為對於閱讀您的代碼的人來說,不會立即清楚choice在做什么。

我這樣做了:

print 'Your name is :' + choice()

它按預期工作。

編輯:你應該這樣做出你的 if 語句:

if choice() == "1"

 def multiplier(x, y):
     ans = x * y
     print ans

這將是一個函數的用途,當准備使用它時,你會像這樣調用它

 multiplier(5, 10)
      50

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM