首页 > 解决方案 > 我的代码有问题。它输出“无”

问题描述

“内部”列表应该输出一系列“真”和“假”,但它为所有 10 个值输出“无”

import random 
import math
random.seed(1)

def rand(): 
    number = random.uniform(-1,1)
    return number
print(rand())

def distance(x, y):
    for a,b in x,y:
        ans = math.sqrt((x[0] - y[0])**2 + (x[1] - y[1])**2)
        return ans
print(distance((0, 0), (1, 1)))

def in_circle(x, origin=(0,0)):
    print(distance(x, origin) <1)
print(in_circle((1,1)))  # this is supposed to print only "false" but it prints "False" and "None"

R = 10
inside = [in_circle((rand(), rand())) for i in range(R)]

print(inside[:3])

请帮忙!

标签: pythonpython-3.xfunction

解决方案


您必须在函数内部使用 return 而不是 print 。这应该适合你:

import random 
import math
random.seed(1)

def rand(): 
    number = random.uniform(-1,1)
    return number
print(rand())

def distance(x, y):
    for a,b in x,y:
        ans = math.sqrt((x[0] - y[0])**2 + (x[1] - y[1])**2)
        return ans
print(distance((0, 0), (1, 1)))

def in_circle(x, origin=(0,0)):
    return(distance(x, origin) <1)
print(in_circle((1,1)))  # this is supposed to print only "false" but it prints "False" and "None"

R = 10
inside = [in_circle((rand(), rand())) for i in range(R)]

print(inside[:3])

推荐阅读