[英]Syntax Error while Summation Operation in for loop of Python
我正在尝试定义一个函数来将二进制数转换为十进制数并检查它是否是绝对平方数。 我传递一个二进制数列表作为参数,该函数应该以与列表元素相同的顺序打印“真”或“假”作为输出; 描述它们是否是绝对平方。
在尝试时,我在第九行遇到语法错误,我试图通过添加每个二进制数字由于其位置而产生的各个值来计算二进制数字的十进制等效值。 执行逻辑:二进制中的 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
处收到语法错误
请告诉我为什么会报告此错误?
在第 20 行,更改:
value = (2**(no_of_digit - (p+1)) * int(r)
到:
value = (2**(no_of_digit - (p+1)) * int(r) )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.