笨辦法19函數和變量
阿新 • • 發佈:2017-10-11
nor log 描述 查看 ack lan eno 結果 alt
以下為代碼:
1 def cheese_and_crackers(cheese_count, boxes_of_crackers): #定義函數 2 print "You have %d cheeses!" % cheese_count 3 print "You have %d boxes of crackers!" % boxes_of_crackers 4 print "Man that‘s enough for a party!" 5 print "Get a blanket.\n" 6 7 8 print "We can just give the function numbers directly:" 9 cheese_and_crackers(20, 30) 10 11 print "OR, we can use variables from our script:" #通過變量執行 12 amount_of_cheese = 10 13 amount_of_crackers = 50 14 cheese_and_crackers(amount_of_cheese, amount_of_crackers) 15 16 print "We can even do math inside too:" #通過math執行 17 cheese_and_crackers(10 + 20, 5 + 6)18 19 print "And we can combine the two, variables and math:" #通過變量+math執行 20 cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 1000)
輸出結果:
獲取用戶輸入:
1 def cheese_and_crackers(cheese_count, boxes_of_crackers): 2 print "You have %d cheeses!" % cheese_count 3 print "You have %d boxes of crackers!\n" % boxes_of_crackers 4 5 num1 = raw_input("cheeses:") 6 num2 = raw_input("crackers:") 7 8 cheese_and_crackers(num1, num2)
然而執行到用戶輸入後,報錯
查看問題發現,報錯由於變量的類型不正確,即%d和raw_input的問題,原因是raw_input() 將所有輸入作為字符串看待,返回的是字符串類型。可以有以下解決辦法:
1. 將%d換成%r或者%s
2. 將raw_input換成input,input() 返回所輸入的數字的類型( int, float )
3. 第8行加入int: cheese_and_crackers(int(num1), int(num2))
以下用方法2
1 def cheese_and_crackers(cheese_count, boxes_of_crackers): 2 print "You have %d cheeses!" % cheese_count 3 print "You have %d boxes of crackers!\n" % boxes_of_crackers 4 5 num = "Please enter the number" 6 num1 = input(num + ", cheeses:") 7 num2 = input(num + ", crackers:") 8 9 cheese_and_crackers(num1, num2)
順利輸出結果:
笨辦法19函數和變量