如果这是一个新手问题请原谅,我在运行我的程序时遇到错误“TypeError: unsupported operand type(s) for &: ‘float’ and ‘float’”,我想知道为什么会这样。我的程序应该是通过我指定的数字数量(精度变量)来尝试猜测我的数字,并在3个数字的范围内平均这些数字以获得接近我的数字。我刚开始学习Python,欢迎建议更高效的代码编写方式…
__author__ = 'Vansh'import randomdef avg(*args, length): nums = 0 for num in args: nums += num return nums/lengthdef standby(): i = input(">>> ") if i != "close": standby()def ai(): x = float(input("Enter A Number: ")) y = int(input("Enter Precision: ")) z = [] for i in range(y*5): random_guess = random.randrange(-1, 101) decimal = random.randrange(-1, 10) random_guess = float(random_guess + (decimal/10)) while random_guess > x-3 & random_guess < x+3: print() z.append(random_guess) print("Number Guess: {}".format(avg(z, len(z)))) standby()ai()
回答:
&
是 Python 中的按位与
运算符,我认为你应该使用and
运算符来代替。
应该是 –
while random_guess > x-3 and random_guess < x+3:
也可以写成 –
while (x-3) < random_guess < (x+3):