簡體   English   中英

無法弄清楚此編碼出了什么問題

[英]Can not figure out what is going wrong with this coding

我想弄清楚為什么我沒有在 python 中得到這個編碼的正確答案。 到目前為止,這是我的代碼:

def main():
    base = input('Enter an integer for the base: ')
    exponent = input('Enter an integer for the exponent: ')
    print(base,'to the power', exponent,'equals', power)

def power(base, exponent):
    if exponent <= 1:
       return base
    else:
       return base * power(base, exponent - 1)
main()

當我用 2 和 5(底數,指數)運行程序時,我得到了這個:

Enter an integer for the base: 2
Enter an integer for the exponent: 5
2 to the power 5 equals <function power at 0x03DDC300>
>>> 

我的問題是:為什么我得到“0x03DDC300 的功能功率”或類似的答案,而不是正確答案 32?

您需要使用適當的整數參數調用函數power以獲得正確的輸出。

print(base,'to the power', exponent,'equals', power(int(base), int(exponent))) # call the function `power`

沒有這個, power只會返回一個可調用的。

In [1]: def some_func():
   ...:     return 2 
   ...: 

In [2]: print some_func # print the function without calling 
<function some_func at 0x601a050> # returns a callable

In [3]: print some_func() # call the function
2
print(base,'to the power', exponent,'equals', power)

看線。 您不是在調用函數,而只是在編寫函數名稱。

您需要調用該函數。

更改powerpower(base,exponent)

例如,如果要計算 2 的 3 次方,請將上面的行更改為:

print(base,'to the power', exponent,'equals', power(2,3)) 

因為power()是一個函數,所以你需要調用它,而不僅僅是打印它。
並且您的函數power()需要兩個參數,因此您可以嘗試以下代碼:

def main():
    base = int(input('Enter an integer for the base: '))
    exponent = int(input('Enter an integer for the exponent: '))
    # use `int()` function if you wish user enter a intege


    print(base,'to the power', exponent,'equals', power(base, exponent))

def power(base, exponent):
    if exponent <= 1:
       return base
    else:
       return base * power(base, exponent - 1)

main()

演示:

Enter an integer for the base: 10
Enter an integer for the exponent: 20
10 to the power 20 equals 100000000000000000000

當你有一個沒有括號的函數時,返回值會告訴你這個函數,而不是返回值。 為了獲得返回值,您必須分別插入函數power()的參數、基數和指數。

此外,當一個函數使用另一個函數時——比如函數 1 使用函數 2——你應該先定義函數 2,反之亦然。

這應該有效:

def power(base, exponent): if exponent <= 1: return base else: return base * power(base, exponent - 1) def main(): base = input('Enter an integer for the base: ') exponent = input('Enter an integer for the exponent: ') print(base,'to the power', exponent,'equals', power(base, exponent)) main()

暫無
暫無

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

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