【发布时间】:2020-07-06 04:29:26
【问题描述】:
我正在尝试定义一个函数来将二进制数转换为十进制数并检查它是否是绝对平方。我将二进制数列表作为参数传递,并且该函数应该以与列表元素相同的顺序打印“True”或“False”作为输出;描述它们是否是绝对正方形。
在尝试时,我在第 9 行遇到语法错误,我试图通过将每个二进制数字由于其位置而产生的各个值相加来计算二进制数字的十进制等效值。 执行逻辑:二进制中的 1001 表示十进制中的 [pow(2,3)*1 + pow(2,2)*0 + pow(2,1)*0 + pow(2,0)*1]。它等于 9,它是 3 的绝对平方。所以输出应该是“真”
import math
n = int(input("Enter the total no of elements to check: "))
num_list = []
for k in range (n):
print("Enter the number at position "+str(k)+" : ")
num = int(input())
num_list.append(num)
#print(num_list) for debugging purpose
def Binary_SquareRoot_Checker(input_list):
for i in input_list:
q = str(i)
no_of_digit = len(q)
#For each element of the list, we need to count the no of digits present
addition_num = 0
for p in range (no_of_digit):
r = q[p]
value = (2**(no_of_digit - (p+1)) * int(r)
addition_num = addition_num + value
#print(addition_num) just to see the decimal number
root = math.sqrt(sum_num)
if int(root + 0.5) ** 2 == sum_num:
#Checking for absolute square property
print("True")
else:
print("False")
Binary_SquareRoot_Checker(num_list)
我在addition_num = addition_num + value收到语法错误
请告诉我为什么会报告这个错误?
【问题讨论】:
-
缺少关闭
)在上面的行(上面的行本身在语法上技术上是正确的;缺少的关闭括号使 Python 假设它在下一行继续,但随后=无效,因此“错误”行出现语法错误)
标签: python for-loop syntax-error