2015-09-22 61 views
-3

這是我在11年級的計算機科學課上做的一個問題。我嘗試了很多次,但由於某種原因,我的嘗試似乎都沒有奏效。即時通訊使用Python 2.7.10Python提示計算器

Write a function called tipCalculator() that takes two parameters: bill and percentage, and calculates your total including a tip. The result should be printed in a pleasant format.

def tipCalculator(x,y): 
    x = bill 
    y = percentage 

    percentage = 0.15 
    meal = x * y 
    print(10,y) 
+0

作業的哪一部分給你帶來麻煩?它解析問題,代碼的語法,測試你的解決方案等? –

+0

2天前我剛剛開始用Python進行編程,我只想領先於我的課程,更好地理解python應該如何工作。所以我真的不知道問題到底是什麼。我查了很多YouTube視頻,但沒有一個能夠提供幫助。我把我的代碼放在人們看到的地方,但我知道它的全部錯誤。 –

+0

歡迎來到StackOverflow!你可能從http://www.sscce.org得到一些價值你上面的示例代碼,最值得注意的是,不能編譯(儘管這可能是一個格式問題?)。其次,你應該提供一些你可能通過這個函數輸入的例子,以及你對這個輸入的期望輸出。做這個練習將有助於澄清你對這個問題的思考! –

回答

1

有一些基本的瞭解,可以在這裏清理。讓我們來看看你目前在做什麼:

def tipCalculator(x,y): 
    x = bill # Assigning 'bill' to the name 'x'. 
    y = percentage # Assigning 'percentage' to the name 'y'. 

    percentage = 0.15 # Assigning '0.15' to the name 'percentage' 
    meal = x * y # Doing a calculation and assigning it to the name 'meal' 
    print(10,y) # Printing '10' and 'y'. 

人們似乎對如何Python's variable assignment works一些混亂。在您的第一行中,您嘗試將bill指定爲x ...但bill尚不存在!下面將總是會導致一個錯誤:

>>> def myfunc(x): 
...  x = bill 
...  print(bill, x) 
... 
>>> myfunc(10) 
Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
    File "<stdin>", line 2, in myfunc 
NameError: name 'bill' is not defined 

你真正想在這裏做的(我認爲)是這樣的:

>>> def myfunc(x): 
...  bill = x 
...  print(bill, x) 
... 
>>> myfunc(10) 
10 

注意,不會引發錯誤。但請注意,你可以命名你的函數的參數,你想要什麼,你並不需要「將」他們:

>>> def myfunc(bill): 
...  print(bill) 
... 
>>> myfunc(10) 
10 

我強烈建議你看了上面的鏈接,並嘗試去了解它。一旦命名完成,數學將會非常簡單地處理!