函数在python中不起作用

时间:2014-11-06 00:55:08

标签: python function

新手编程。尝试使用Head First Programming书进行自学。 我无法使用以下代码;

            def make_smoothie():
                juice = input("What juice would you like?")
                fruit = input("Ok- and how about the fruit?")
                print "Thanks. Lets go!"
                print "Crushing ice..."
                print "Blending the %d" % fruit
                print "Now adding in the %d juice" %juice
                print "Finished! There's your %d and %d smoothie" %(fruit, juice)


            print ("Welcome to smoothie")
            another ="Y"
            while another=="Y":
                make_smoothie()
                another = input ("How about another (Y/N)?")

继续收到未定义果汁或水果输入的错误

2 个答案:

答案 0 :(得分:1)

它适用于我,我使用的是Python 2.x.您是否为果汁和水果提供数字,因为您使用%d进行文本格式化?

oltjano@baby:~/Desktop/unveil/tests$ python juice.py 
Welcome to smoothie
How about another (Y/N)?"Y"
What juice would you like?1
Ok- and how about the fruit?2
Thanks. Lets go!
Crushing ice...
Blending the 2
Now adding in the 1 juice
Finished! There's your 2 and 1 smoothie
How about another (Y/N)?

答案 1 :(得分:0)

只是一个猜测...如果您使用的是python 2,那么使用raw_input代替input ...(在python 2 input中将尝试评估用户输入到python对象(整数或变量名等)... raw_input将用户输入作为字符串返回)

考虑

>>> apple = 555
>>> print input("Enter Fruit:")
Enter Fruit:apple
555 #returns the value of the variable apple ... if that does not exist you get an error
>>> print raw_input("Enter Fruit:")
Enter Fruit:apple
apple #returns the string "apple"