[英]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.