簡體   English   中英

如何在多次使用的函數中聲明變量?

[英]How can I declare a variable inside a function thats used more than once?

我第一次開始使用函數,而我遇到的問題是在函數中聲明了一個變量,該變量已被多次使用。 在嘗試添加功能之前,我已使該程序正常運行,因此唯一不正確的事情(即假設)是我嘗試使用功能。

print ("Welcome to August's binary arithemetic caclulator.")
firstvalue = input("What is the first binary value?")
secondvalue = input("What is the second binary value?")
operation = input("What operation would you like to carry out? + or - or * or ^")

def bintoint():
    prod, ans, power = 0, 0, 0
    for i in range (-1,-len(firstvalue) - 1,-1):
        try:
            prod = ((int(firstvalue[i])) * ((2**power)))
        except ValueError:
            continue
        ans += prod
        prod = 0
        power += 1
    global ans

firstvalueans = ans

bintoint()
bintoint(firstvalue="secondvalue")

secondvalueans = ans

#prod, ans, power = 0, 0, 0
#for i in range (-1,-len(secondvalue) - 1,-1):
#    try:
#        prod = ((int(secondvalue[i])) * ((2**power)))
#    except ValueError:
#        continue
#    ans += prod
#    prod = 0
#    power += 1
# global secondvalueans
# secondvalueans = ans

if operation == "+":
    totalans = (firstvalueans + secondvalueans)
if operation == ("-"):
    totalans = (firstvalueans - secondvalueans)
if operation == ("*"):
    totalans = (firstvalueans * secondvalueans)
if operation == ("^"):
    totalans = (firstvalueans ** secondvalueans)
try:
    totalans = int(totalans)
except NameError:
    print ("Please enter a valid operator.")
    import sys
    sys.exit()

invertedbinary = []
while totalans >= 1:
    totalans = (totalans/2)
    invertedbinary.append(totalans)
    totalans = int(totalans)
for n,i in enumerate(invertedbinary):
    if (round(i) == i):
        invertedbinary[n]=0
    else:
        invertedbinary[n]=1
if (firstvalue[0] == "-") ^ (secondvalue[0] == "-"):
    invertedbinary.append("-")

invertedbinary.reverse()
result = ''.join(str(e) for e in invertedbinary)
print ( firstvalue , operation , secondvalue , "=" ,result)

注意唯一聲明的函數,以及注釋的代碼塊。 除單個變量外,代碼均相同。 因此,我嘗試通過更改變量的唯一區別來兩次執行該函數。 我想更改的變量可以在def bintoint()視為firstvalue 第二次調用該函數時,我希望將firstvalue替換為`secondvalue,就像注釋的代碼一樣。

該腳本的想法是獲取兩個二進制值,將它們轉換為整數,在兩個整數之間執行各自的運算,轉換回二進制數並print ( firstvalue , operation , secondvalue , "=" ,result)

因此,可以說我按以下順序輸入了兩個值:

100

011

*

預期產量:

100 * 011 = 1100

實際輸出:

TypeError: bintoint() got an unexpected keyword argument 'firstvalue'

因此,我理解在函數中更改變量的嘗試是有問題的。 bintoint(firstvalue="secondvalue")我也嘗試不帶引號,但仍然給我同樣的錯誤。

我究竟做錯了什么?

使用函數的兩個重要方面是傳遞參數和返回結果。 如果傳入參數,則每次調用該函數時都會收到一個可能不同的值。 如果返回結果,則每次調用函數時,調用代碼將收到不同的答案。

嘗試這樣的事情:

def bintoint(value):
    prod, ans, power = 0, 0, 0
    for i in range (-1,-len(value) - 1,-1):
        try:
            prod = ((int(value[i])) * ((2**power)))
        except ValueError:
            continue
        ans += prod
        prod = 0
        power += 1
    return ans

然后,在您的主要代碼中:

firstvalueans = bintoint(firstvalue)
secondvalueans = bintoint(secondvalue)

有關函數的更多信息,請參見“ Python教程 ”中的“ 定義函數”部分。

另外 :在您的示例中,使用int()構造函數兩參數形式可能更容易,如下所示:

firstvalueans=int(firstvalue, 2)

暫無
暫無

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

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